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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.837   ! raeburn     4: # $Id: lonnet.pm,v 1.836 2007/02/23 15:49:23 www 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.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %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.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.807     albertel   56: use LONCAPA qw(:DEFAULT :match);
1.740     www        57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
1.836     www       204:     &logthis("Trying to reconnect lonc");
1.1       albertel  205:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  206:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  207: 	my $loncpid=<$fh>;
                    208:         chomp($loncpid);
                    209:         if (kill 0 => $loncpid) {
                    210: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    211:             kill USR1 => $loncpid;
                    212:             sleep 1;
1.836     www       213:          } else {
1.12      www       214: 	    &logthis(
1.672     albertel  215:                "<font color=\"blue\">WARNING:".
1.12      www       216:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  217:         }
                    218:     } else {
1.836     www       219: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  220:     }
                    221: }
                    222: 
                    223: # ------------------------------------------------------ Critical communication
1.12      www       224: 
1.1       albertel  225: sub critical {
                    226:     my ($cmd,$server)=@_;
1.89      www       227:     unless ($hostname{$server}) {
1.672     albertel  228:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       229:                " Critical message to unknown server ($server)</font>");
                    230:         return 'no_such_host';
                    231:     }
1.1       albertel  232:     my $answer=reply($cmd,$server);
                    233:     if ($answer eq 'con_lost') {
                    234: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  235: 	my $answer=reply($cmd,$server);
1.1       albertel  236:         if ($answer eq 'con_lost') {
                    237:             my $now=time;
                    238:             my $middlename=$cmd;
1.5       www       239:             $middlename=substr($middlename,0,16);
1.1       albertel  240:             $middlename=~s/\W//g;
                    241:             my $dfilename=
1.305     www       242:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    243:             $dumpcount++;
1.1       albertel  244:             {
1.448     albertel  245: 		my $dfh;
                    246: 		if (open($dfh,">$dfilename")) {
                    247: 		    print $dfh "$cmd\n"; 
                    248: 		    close($dfh);
                    249: 		}
1.1       albertel  250:             }
                    251:             sleep 2;
                    252:             my $wcmd='';
                    253:             {
1.448     albertel  254: 		my $dfh;
                    255: 		if (open($dfh,"<$dfilename")) {
                    256: 		    $wcmd=<$dfh>; 
                    257: 		    close($dfh);
                    258: 		}
1.1       albertel  259:             }
                    260:             chomp($wcmd);
1.7       www       261:             if ($wcmd eq $cmd) {
1.672     albertel  262: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       263:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  264:                 &logperm("D:$server:$cmd");
                    265: 	        return 'con_delayed';
                    266:             } else {
1.672     albertel  267:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       268:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  269:                 &logperm("F:$server:$cmd");
                    270:                 return 'con_failed';
                    271:             }
                    272:         }
                    273:     }
                    274:     return $answer;
1.405     albertel  275: }
                    276: 
1.755     albertel  277: # ------------------------------------------- check if return value is an error
                    278: 
                    279: sub error {
                    280:     my ($result) = @_;
1.756     albertel  281:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  282: 	if ($2 == 2) { return undef; }
                    283: 	return $1;
                    284:     }
                    285:     return undef;
                    286: }
                    287: 
1.783     albertel  288: sub convert_and_load_session_env {
                    289:     my ($lonidsdir,$handle)=@_;
                    290:     my @profile;
                    291:     {
                    292: 	open(my $idf,"$lonidsdir/$handle.id");
                    293: 	flock($idf,LOCK_SH);
                    294: 	@profile=<$idf>;
                    295: 	close($idf);
                    296:     }
                    297:     my %temp_env;
                    298:     foreach my $line (@profile) {
1.786     albertel  299: 	if ($line !~ m/=/) {
                    300: 	    return 0;
                    301: 	}
1.783     albertel  302: 	chomp($line);
                    303: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    304: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    305:     }
                    306:     unlink("$lonidsdir/$handle.id");
                    307:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    308: 	    0640)) {
                    309: 	%disk_env = %temp_env;
                    310: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    311: 	untie(%disk_env);
                    312:     }
1.786     albertel  313:     return 1;
1.783     albertel  314: }
                    315: 
1.374     www       316: # ------------------------------------------- Transfer profile into environment
1.780     albertel  317: my $env_loaded;
                    318: sub transfer_profile_to_env {
1.788     albertel  319:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    320:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       321: 
1.720     albertel  322:     if (!defined($lonidsdir)) {
                    323: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    324:     }
                    325:     if (!defined($handle)) {
                    326:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    327:     }
                    328: 
1.786     albertel  329:     my $convert;
                    330:     {
                    331:     	open(my $idf,"$lonidsdir/$handle.id");
                    332: 	flock($idf,LOCK_SH);
                    333: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    334: 		&GDBM_READER(),0640)) {
                    335: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    336: 	    untie(%disk_env);
                    337: 	} else {
                    338: 	    $convert = 1;
                    339: 	}
                    340:     }
                    341:     if ($convert) {
                    342: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    343: 	    &logthis("Failed to load session, or convert session.");
                    344: 	}
1.374     www       345:     }
1.783     albertel  346: 
1.786     albertel  347:     my %remove;
1.783     albertel  348:     while ( my $envname = each(%env) ) {
1.433     matthew   349:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    350:             if ($time < time-300) {
1.783     albertel  351:                 $remove{$key}++;
1.433     matthew   352:             }
                    353:         }
                    354:     }
1.783     albertel  355: 
1.619     albertel  356:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  357:     $env_loaded=1;
1.783     albertel  358:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   359:         &delenv($expired_key);
1.374     www       360:     }
1.1       albertel  361: }
                    362: 
1.830     albertel  363: sub timed_flock {
                    364:     my ($file,$lock_type) = @_;
                    365:     my $failed=0;
                    366:     eval {
                    367: 	local $SIG{__DIE__}='DEFAULT';
                    368: 	local $SIG{ALRM}=sub {
                    369: 	    $failed=1;
                    370: 	    die("failed lock");
                    371: 	};
                    372: 	alarm(13);
                    373: 	flock($file,$lock_type);
                    374: 	alarm(0);
                    375:     };
                    376:     if ($failed) {
                    377: 	return undef;
                    378:     } else {
                    379: 	return 1;
                    380:     }
                    381: }
                    382: 
1.5       www       383: # ---------------------------------------------------------- Append Environment
                    384: 
                    385: sub appenv {
1.6       www       386:     my %newenv=@_;
1.692     albertel  387:     foreach my $key (keys(%newenv)) {
                    388: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  389:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  390:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       391:                 .'</font>');
1.692     albertel  392: 	    delete($newenv{$key});
1.35      www       393:         } else {
1.692     albertel  394:             $env{$key}=$newenv{$key};
1.35      www       395:         }
1.191     harris41  396:     }
1.830     albertel  397:     open(my $env_file,$env{'user.environment'});
                    398:     if (&timed_flock($env_file,LOCK_EX)
                    399: 	&&
                    400: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    401: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  402: 	while (my ($key,$value) = each(%newenv)) {
                    403: 	    $disk_env{$key} = $value;
1.448     albertel  404: 	}
1.783     albertel  405: 	untie(%disk_env);
1.56      www       406:     }
                    407:     return 'ok';
                    408: }
                    409: # ----------------------------------------------------- Delete from Environment
                    410: 
                    411: sub delenv {
                    412:     my $delthis=shift;
                    413:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  414:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       415:                 "Attempt to delete from environment ".$delthis);
                    416:         return 'error';
                    417:     }
1.830     albertel  418:     open(my $env_file,$env{'user.environment'});
                    419:     if (&timed_flock($env_file,LOCK_EX)
                    420: 	&&
                    421: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    422: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  423: 	foreach my $key (keys(%disk_env)) {
                    424: 	    if ($key=~/^$delthis/) { 
1.619     albertel  425:                 delete($env{$key});
1.783     albertel  426:                 delete($disk_env{$key});
1.473     matthew   427:             }
1.448     albertel  428: 	}
1.783     albertel  429: 	untie(%disk_env);
1.5       www       430:     }
                    431:     return 'ok';
1.369     albertel  432: }
                    433: 
1.790     albertel  434: sub get_env_multiple {
                    435:     my ($name) = @_;
                    436:     my @values;
                    437:     if (defined($env{$name})) {
                    438:         # exists is it an array
                    439:         if (ref($env{$name})) {
                    440:             @values=@{ $env{$name} };
                    441:         } else {
                    442:             $values[0]=$env{$name};
                    443:         }
                    444:     }
                    445:     return(@values);
                    446: }
                    447: 
1.369     albertel  448: # ------------------------------------------ Find out current server userload
                    449: # there is a copy in lond
                    450: sub userload {
                    451:     my $numusers=0;
                    452:     {
                    453: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    454: 	my $filename;
                    455: 	my $curtime=time;
                    456: 	while ($filename=readdir(LONIDS)) {
                    457: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  458: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  459: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  460: 	}
                    461: 	closedir(LONIDS);
                    462:     }
                    463:     my $userloadpercent=0;
                    464:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    465:     if ($maxuserload) {
1.371     albertel  466: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  467:     }
1.372     albertel  468:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  469:     return $userloadpercent;
1.283     www       470: }
                    471: 
                    472: # ------------------------------------------ Fight off request when overloaded
                    473: 
                    474: sub overloaderror {
                    475:     my ($r,$checkserver)=@_;
                    476:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    477:     my $loadavg;
                    478:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  479:        open(my $loadfile,'/proc/loadavg');
1.283     www       480:        $loadavg=<$loadfile>;
                    481:        $loadavg =~ s/\s.*//g;
1.285     matthew   482:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  483:        close($loadfile);
1.283     www       484:     } else {
                    485:        $loadavg=&reply('load',$checkserver);
                    486:     }
1.285     matthew   487:     my $overload=$loadavg-100;
1.283     www       488:     if ($overload>0) {
1.285     matthew   489: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       490:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       491:         return 413;
1.283     www       492:     }    
                    493:     return '';
1.5       www       494: }
1.1       albertel  495: 
                    496: # ------------------------------ Find server with least workload from spare.tab
1.11      www       497: 
1.1       albertel  498: sub spareserver {
1.670     albertel  499:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  500:     my $spare_server;
1.370     albertel  501:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  502:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    503:                                                      :  $userloadpercent;
                    504:     
                    505:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    506: 	($spare_server, $lowest_load) =
                    507: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    508:     }
                    509: 
                    510:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    511: 
                    512:     if (!$found_server) {
                    513: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    514: 	    ($spare_server, $lowest_load) =
                    515: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    516: 	}
                    517:     }
                    518: 
                    519:     if (!$want_server_name) {
                    520: 	$spare_server="http://$hostname{$spare_server}";
                    521:     }
                    522:     return $spare_server;
                    523: }
                    524: 
                    525: sub compare_server_load {
                    526:     my ($try_server, $spare_server, $lowest_load) = @_;
                    527: 
                    528:     my $loadans     = &reply('load',    $try_server);
                    529:     my $userloadans = &reply('userload',$try_server);
                    530: 
                    531:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    532: 	next; #didn't get a number from the server
                    533:     }
                    534: 
                    535:     my $load;
                    536:     if ($loadans =~ /\d/) {
                    537: 	if ($userloadans =~ /\d/) {
                    538: 	    #both are numbers, pick the bigger one
                    539: 	    $load = ($loadans > $userloadans) ? $loadans 
                    540: 		                              : $userloadans;
1.411     albertel  541: 	} else {
1.784     albertel  542: 	    $load = $loadans;
1.411     albertel  543: 	}
1.784     albertel  544:     } else {
                    545: 	$load = $userloadans;
                    546:     }
                    547: 
                    548:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    549: 	$spare_server = $try_server;
                    550: 	$lowest_load  = $load;
1.370     albertel  551:     }
1.784     albertel  552:     return ($spare_server,$lowest_load);
1.202     matthew   553: }
                    554: # --------------------------------------------- Try to change a user's password
                    555: 
                    556: sub changepass {
1.799     raeburn   557:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   558:     $currentpass = &escape($currentpass);
                    559:     $newpass     = &escape($newpass);
1.799     raeburn   560:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   561: 		       $server);
                    562:     if (! $answer) {
                    563: 	&logthis("No reply on password change request to $server ".
                    564: 		 "by $uname in domain $udom.");
                    565:     } elsif ($answer =~ "^ok") {
                    566:         &logthis("$uname in $udom successfully changed their password ".
                    567: 		 "on $server.");
                    568:     } elsif ($answer =~ "^pwchange_failure") {
                    569: 	&logthis("$uname in $udom was unable to change their password ".
                    570: 		 "on $server.  The action was blocked by either lcpasswd ".
                    571: 		 "or pwchange");
                    572:     } elsif ($answer =~ "^non_authorized") {
                    573:         &logthis("$uname in $udom did not get their password correct when ".
                    574: 		 "attempting to change it on $server.");
                    575:     } elsif ($answer =~ "^auth_mode_error") {
                    576:         &logthis("$uname in $udom attempted to change their password despite ".
                    577: 		 "not being locally or internally authenticated on $server.");
                    578:     } elsif ($answer =~ "^unknown_user") {
                    579:         &logthis("$uname in $udom attempted to change their password ".
                    580: 		 "on $server but were unable to because $server is not ".
                    581: 		 "their home server.");
                    582:     } elsif ($answer =~ "^refused") {
                    583: 	&logthis("$server refused to change $uname in $udom password because ".
                    584: 		 "it was sent an unencrypted request to change the password.");
                    585:     }
                    586:     return $answer;
1.1       albertel  587: }
                    588: 
1.169     harris41  589: # ----------------------- Try to determine user's current authentication scheme
                    590: 
                    591: sub queryauthenticate {
                    592:     my ($uname,$udom)=@_;
1.456     albertel  593:     my $uhome=&homeserver($uname,$udom);
                    594:     if (!$uhome) {
                    595: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    596: 	return 'no_host';
                    597:     }
                    598:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    599:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    600: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  601:     }
1.456     albertel  602:     return $answer;
1.169     harris41  603: }
                    604: 
1.1       albertel  605: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       606: 
1.1       albertel  607: sub authenticate {
                    608:     my ($uname,$upass,$udom)=@_;
1.807     albertel  609:     $upass=&escape($upass);
                    610:     $uname= &LONCAPA::clean_username($uname);
1.836     www       611:     my $uhome=&homeserver($uname,$udom,1);
                    612:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    613: # Maybe the machine was offline and only re-appeared again recently?
                    614:         &reconlonc();
                    615: # One more
                    616: 	my $uhome=&homeserver($uname,$udom,1);
                    617: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    618: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    619: 	}
1.471     albertel  620: 	return 'no_host';
1.1       albertel  621:     }
1.471     albertel  622:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    623:     if ($answer eq 'authorized') {
                    624: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    625: 	return $uhome; 
                    626:     }
                    627:     if ($answer eq 'non_authorized') {
                    628: 	&logthis("User $uname at $udom rejected by $uhome");
                    629: 	return 'no_host'; 
1.9       www       630:     }
1.471     albertel  631:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  632:     return 'no_host';
                    633: }
                    634: 
                    635: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       636: 
1.599     albertel  637: my %homecache;
1.1       albertel  638: sub homeserver {
1.230     stredwic  639:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  640:     my $index="$uname:$udom";
1.426     albertel  641: 
1.599     albertel  642:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  643:     my $tryserver;
                    644:     foreach $tryserver (keys %libserv) {
1.230     stredwic  645:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  646: 		 exists($badServerCache{$tryserver}));
1.1       albertel  647: 	if ($hostdom{$tryserver} eq $udom) {
                    648:            my $answer=reply("home:$udom:$uname",$tryserver);
1.836     www       649:            if ($answer eq 'found') {
                    650:                delete($badServerCache{$tryserver}); 
1.599     albertel  651: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  652:            } elsif ($answer eq 'no_host') {
                    653: 	       $badServerCache{$tryserver}=1;
1.221     matthew   654:            }
1.1       albertel  655:        }
                    656:     }    
                    657:     return 'no_host';
1.70      www       658: }
                    659: 
                    660: # ------------------------------------- Find the usernames behind a list of IDs
                    661: 
                    662: sub idget {
                    663:     my ($udom,@ids)=@_;
                    664:     my %returnhash=();
                    665:     
                    666:     my $tryserver;
                    667:     foreach $tryserver (keys %libserv) {
                    668:        if ($hostdom{$tryserver} eq $udom) {
                    669: 	  my $idlist=join('&',@ids);
                    670:           $idlist=~tr/A-Z/a-z/; 
                    671: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    672:           my @answer=();
1.76      www       673:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       674: 	      @answer=split(/\&/,$reply);
                    675:           }                    ;
                    676:           my $i;
                    677:           for ($i=0;$i<=$#ids;$i++) {
                    678:               if ($answer[$i]) {
                    679: 		  $returnhash{$ids[$i]}=$answer[$i];
                    680:               } 
                    681:           }
                    682:        }
                    683:     }    
                    684:     return %returnhash;
                    685: }
                    686: 
                    687: # ------------------------------------- Find the IDs behind a list of usernames
                    688: 
                    689: sub idrget {
                    690:     my ($udom,@unames)=@_;
                    691:     my %returnhash=();
1.800     albertel  692:     foreach my $uname (@unames) {
                    693:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  694:     }
1.70      www       695:     return %returnhash;
                    696: }
                    697: 
                    698: # ------------------------------- Store away a list of names and associated IDs
                    699: 
                    700: sub idput {
                    701:     my ($udom,%ids)=@_;
                    702:     my %servers=();
1.800     albertel  703:     foreach my $uname (keys(%ids)) {
                    704: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    705:         my $uhom=&homeserver($uname,$udom);
1.70      www       706:         if ($uhom ne 'no_host') {
1.800     albertel  707:             my $id=&escape($ids{$uname});
1.70      www       708:             $id=~tr/A-Z/a-z/;
1.800     albertel  709:             my $esc_unam=&escape($uname);
1.70      www       710: 	    if ($servers{$uhom}) {
1.800     albertel  711: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       712:             } else {
1.800     albertel  713:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       714:             }
                    715:         }
1.191     harris41  716:     }
1.800     albertel  717:     foreach my $server (keys(%servers)) {
                    718:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  719:     }
1.344     www       720: }
                    721: 
1.806     raeburn   722: # ------------------------------------------- get items from domain db files   
                    723: 
                    724: sub get_dom {
                    725:     my ($namespace,$storearr,$udom)=@_;
                    726:     my $items='';
                    727:     foreach my $item (@$storearr) {
                    728:         $items.=&escape($item).'&';
                    729:     }
                    730:     $items=~s/\&$//;
                    731:     if (!$udom) { $udom=$env{'user.domain'}; }
                    732:     if (exists($domain_primary{$udom})) {
                    733:         my $uhome=$domain_primary{$udom};
                    734:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    735:         my @pairs=split(/\&/,$rep);
                    736:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    737:             return @pairs;
                    738:         }
                    739:         my %returnhash=();
                    740:         my $i=0;
                    741:         foreach my $item (@$storearr) {
                    742:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    743:             $i++;
                    744:         }
                    745:         return %returnhash;
                    746:     } else {
                    747:         &logthis("get_dom failed - no primary domain server for $udom");
                    748:     }
                    749: }
                    750: 
                    751: # -------------------------------------------- put items in domain db files 
                    752: 
                    753: sub put_dom {
                    754:     my ($namespace,$storehash,$udom)=@_;
                    755:     if (!$udom) { $udom=$env{'user.domain'}; }
                    756:     if (exists($domain_primary{$udom})) {
                    757:         my $uhome=$domain_primary{$udom};
                    758:         my $items='';
                    759:         foreach my $item (keys(%$storehash)) {
                    760:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    761:         }
                    762:         $items=~s/\&$//;
                    763:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    764:     } else {
                    765:         &logthis("put_dom failed - no primary domain server for $udom");
                    766:     }
                    767: }
                    768: 
1.837   ! raeburn   769: sub retrieve_inst_usertypes {
        !           770:     my ($udom) = @_;
        !           771:     my (%returnhash,@order);
        !           772:     if (exists($domain_primary{$udom})) {
        !           773:         my $uhome=$domain_primary{$udom};
        !           774:         my $rep=&reply("inst_usertypes:$udom",$uhome);
        !           775:         my ($hashitems,$orderitems) = split(/:/,$rep); 
        !           776:         my @pairs=split(/\&/,$hashitems);
        !           777:         foreach my $item (@pairs) {
        !           778:             my ($key,$value)=split(/=/,$item,2);
        !           779:             $key = &unescape($key);
        !           780:             next if ($key =~ /^error: 2 /);
        !           781:             $returnhash{$key}=&thaw_unescape($value);
        !           782:         }
        !           783:         my @esc_order = split(/\&/,$orderitems);
        !           784:         foreach my $item (@esc_order) {
        !           785:             push(@order,&unescape($item));
        !           786:         }
        !           787:     } else {
        !           788:         &logthis("get_dom failed - no primary domain server for $udom");
        !           789:     }
        !           790:     return (\%returnhash,\@order);
        !           791: }
        !           792: 
1.344     www       793: # --------------------------------------------------- Assign a key to a student
                    794: 
                    795: sub assign_access_key {
1.364     www       796: #
                    797: # a valid key looks like uname:udom#comments
                    798: # comments are being appended
                    799: #
1.498     www       800:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    801:     $kdom=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       803:     $knum=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       805:     $cdom=
1.620     albertel  806:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       807:     $cnum=
1.620     albertel  808:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    809:     $udom=$env{'user.name'} unless (defined($udom));
                    810:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       811:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       812:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  813:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       814:                                                   # assigned to this person
                    815:                                                   # - this should not happen,
1.345     www       816:                                                   # unless something went wrong
                    817:                                                   # the first time around
                    818: # ready to assign
1.364     www       819:         $logentry=$1.'; '.$logentry;
1.496     www       820:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       821:                                                  $kdom,$knum) eq 'ok') {
1.345     www       822: # key now belongs to user
1.346     www       823: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       824:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    825:                 &appenv('environment.'.$envkey => $ckey);
                    826:                 return 'ok';
                    827:             } else {
                    828:                 return 
                    829:   'error: Count not permanently assign key, will need to be re-entered later.';
                    830: 	    }
                    831:         } else {
                    832:             return 'error: Could not assign key, try again later.';
                    833:         }
1.364     www       834:     } elsif (!$existing{$ckey}) {
1.345     www       835: # the key does not exist
                    836: 	return 'error: The key does not exist';
                    837:     } else {
                    838: # the key is somebody else's
                    839: 	return 'error: The key is already in use';
                    840:     }
1.344     www       841: }
                    842: 
1.364     www       843: # ------------------------------------------ put an additional comment on a key
                    844: 
                    845: sub comment_access_key {
                    846: #
                    847: # a valid key looks like uname:udom#comments
                    848: # comments are being appended
                    849: #
                    850:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    851:     $cdom=
1.620     albertel  852:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       853:     $cnum=
1.620     albertel  854:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       855:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    856:     if ($existing{$ckey}) {
                    857:         $existing{$ckey}.='; '.$logentry;
                    858: # ready to assign
1.367     www       859:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       860:                                                  $cdom,$cnum) eq 'ok') {
                    861: 	    return 'ok';
                    862:         } else {
                    863: 	    return 'error: Count not store comment.';
                    864:         }
                    865:     } else {
                    866: # the key does not exist
                    867: 	return 'error: The key does not exist';
                    868:     }
                    869: }
                    870: 
1.344     www       871: # ------------------------------------------------------ Generate a set of keys
                    872: 
                    873: sub generate_access_keys {
1.364     www       874:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       875:     $cdom=
1.620     albertel  876:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       877:     $cnum=
1.620     albertel  878:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       879:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       880:     unless (($cdom) && ($cnum)) { return 0; }
                    881:     if ($number>10000) { return 0; }
                    882:     sleep(2); # make sure don't get same seed twice
                    883:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    884:     my $total=0;
                    885:     for (my $i=1;$i<=$number;$i++) {
                    886:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    887:                   sprintf("%lx",int(100000*rand)).'-'.
                    888:                   sprintf("%lx",int(100000*rand));
                    889:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    890:        $newkey=~s/0/h/g; # and also 0 and O
                    891:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    892:        if ($existing{$newkey}) {
                    893:            $i--;
                    894:        } else {
1.364     www       895: 	  if (&put('accesskeys',
                    896:               { $newkey => '# generated '.localtime().
1.620     albertel  897:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       898:                            '; '.$logentry },
                    899: 		   $cdom,$cnum) eq 'ok') {
1.344     www       900:               $total++;
                    901: 	  }
                    902:        }
                    903:     }
1.620     albertel  904:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       905:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    906:     return $total;
                    907: }
                    908: 
                    909: # ------------------------------------------------------- Validate an accesskey
                    910: 
                    911: sub validate_access_key {
                    912:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    913:     $cdom=
1.620     albertel  914:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       915:     $cnum=
1.620     albertel  916:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    917:     $udom=$env{'user.domain'} unless (defined($udom));
                    918:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       919:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  920:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       921: }
                    922: 
                    923: # ------------------------------------- Find the section of student in a course
1.652     albertel  924: sub devalidate_getsection_cache {
                    925:     my ($udom,$unam,$courseid)=@_;
                    926:     my $hashid="$udom:$unam:$courseid";
                    927:     &devalidate_cache_new('getsection',$hashid);
                    928: }
1.298     matthew   929: 
1.815     albertel  930: sub courseid_to_courseurl {
                    931:     my ($courseid) = @_;
                    932:     #already url style courseid
                    933:     return $courseid if ($courseid =~ m{^/});
                    934: 
                    935:     if (exists($env{'course.'.$courseid.'.num'})) {
                    936: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    937: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    938: 	return "/$cdom/$cnum";
                    939:     }
                    940: 
                    941:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    942:     if (exists($courseinfo{'num'})) {
                    943: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    944:     }
                    945: 
                    946:     return undef;
                    947: }
                    948: 
1.298     matthew   949: sub getsection {
                    950:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  951:     my $cachetime=1800;
1.551     albertel  952: 
                    953:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  954:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  955:     if (defined($cached)) { return $result; }
                    956: 
1.298     matthew   957:     my %Pending; 
                    958:     my %Expired;
                    959:     #
                    960:     # Each role can either have not started yet (pending), be active, 
                    961:     #    or have expired.
                    962:     #
                    963:     # If there is an active role, we are done.
                    964:     #
                    965:     # If there is more than one role which has not started yet, 
                    966:     #     choose the one which will start sooner
                    967:     # If there is one role which has not started yet, return it.
                    968:     #
                    969:     # If there is more than one expired role, choose the one which ended last.
                    970:     # If there is a role which has expired, return it.
                    971:     #
1.815     albertel  972:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   973:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    974:     foreach my $key (keys(%roleshash)) {
1.479     albertel  975:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   976:         my $section=$1;
                    977:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   978:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   979:         my $now=time;
1.548     albertel  980:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   981:             $Expired{$end}=$section;
                    982:             next;
                    983:         }
1.548     albertel  984:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   985:             $Pending{$start}=$section;
                    986:             next;
                    987:         }
1.599     albertel  988:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   989:     }
                    990:     #
                    991:     # Presumedly there will be few matching roles from the above
                    992:     # loop and the sorting time will be negligible.
                    993:     if (scalar(keys(%Pending))) {
                    994:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  995:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   996:     } 
                    997:     if (scalar(keys(%Expired))) {
                    998:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    999:         my $time = pop(@sorted);
1.599     albertel 1000:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1001:     }
1.599     albertel 1002:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1003: }
1.70      www      1004: 
1.599     albertel 1005: sub save_cache {
                   1006:     &purge_remembered();
1.722     albertel 1007:     #&Apache::loncommon::validate_page();
1.620     albertel 1008:     undef(%env);
1.780     albertel 1009:     undef($env_loaded);
1.599     albertel 1010: }
1.452     albertel 1011: 
1.599     albertel 1012: my $to_remember=-1;
                   1013: my %remembered;
                   1014: my %accessed;
                   1015: my $kicks=0;
                   1016: my $hits=0;
                   1017: sub devalidate_cache_new {
                   1018:     my ($name,$id,$debug) = @_;
                   1019:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                   1020:     $id=&escape($name.':'.$id);
                   1021:     $memcache->delete($id);
                   1022:     delete($remembered{$id});
                   1023:     delete($accessed{$id});
                   1024: }
                   1025: 
                   1026: sub is_cached_new {
                   1027:     my ($name,$id,$debug) = @_;
                   1028:     $id=&escape($name.':'.$id);
                   1029:     if (exists($remembered{$id})) {
                   1030: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1031: 	$accessed{$id}=[&gettimeofday()];
                   1032: 	$hits++;
                   1033: 	return ($remembered{$id},1);
                   1034:     }
                   1035:     my $value = $memcache->get($id);
                   1036:     if (!(defined($value))) {
                   1037: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1038: 	return (undef,undef);
1.416     albertel 1039:     }
1.599     albertel 1040:     if ($value eq '__undef__') {
                   1041: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1042: 	$value=undef;
                   1043:     }
                   1044:     &make_room($id,$value,$debug);
                   1045:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1046:     return ($value,1);
                   1047: }
                   1048: 
                   1049: sub do_cache_new {
                   1050:     my ($name,$id,$value,$time,$debug) = @_;
                   1051:     $id=&escape($name.':'.$id);
                   1052:     my $setvalue=$value;
                   1053:     if (!defined($setvalue)) {
                   1054: 	$setvalue='__undef__';
                   1055:     }
1.623     albertel 1056:     if (!defined($time) ) {
                   1057: 	$time=600;
                   1058:     }
1.599     albertel 1059:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1060:     $memcache->set($id,$setvalue,$time);
                   1061:     # need to make a copy of $value
                   1062:     #&make_room($id,$value,$debug);
1.599     albertel 1063:     return $value;
                   1064: }
                   1065: 
                   1066: sub make_room {
                   1067:     my ($id,$value,$debug)=@_;
                   1068:     $remembered{$id}=$value;
                   1069:     if ($to_remember<0) { return; }
                   1070:     $accessed{$id}=[&gettimeofday()];
                   1071:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1072:     my $to_kick;
                   1073:     my $max_time=0;
                   1074:     foreach my $other (keys(%accessed)) {
                   1075: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1076: 	    $to_kick=$other;
                   1077: 	    $max_time=&tv_interval($accessed{$other});
                   1078: 	}
                   1079:     }
                   1080:     delete($remembered{$to_kick});
                   1081:     delete($accessed{$to_kick});
                   1082:     $kicks++;
                   1083:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1084:     return;
                   1085: }
                   1086: 
1.599     albertel 1087: sub purge_remembered {
1.604     albertel 1088:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1089:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1090:     undef(%remembered);
                   1091:     undef(%accessed);
1.428     albertel 1092: }
1.70      www      1093: # ------------------------------------- Read an entry from a user's environment
                   1094: 
                   1095: sub userenvironment {
                   1096:     my ($udom,$unam,@what)=@_;
                   1097:     my %returnhash=();
                   1098:     my @answer=split(/\&/,
                   1099:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1100:                       &homeserver($unam,$udom)));
                   1101:     my $i;
                   1102:     for ($i=0;$i<=$#what;$i++) {
                   1103: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1104:     }
                   1105:     return %returnhash;
1.1       albertel 1106: }
                   1107: 
1.617     albertel 1108: # ---------------------------------------------------------- Get a studentphoto
                   1109: sub studentphoto {
                   1110:     my ($udom,$unam,$ext) = @_;
                   1111:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1112:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1113:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1114:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1115:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1116:             } else {
                   1117:                 my ($result,$perm_reqd)=
1.707     albertel 1118: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1119:                 if ($result eq 'ok') {
                   1120:                     if (!($perm_reqd eq 'yes')) {
                   1121:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1122:                     }
                   1123:                 }
                   1124:             }
                   1125:         }
                   1126:     } else {
                   1127:         my ($result,$perm_reqd) = 
1.707     albertel 1128: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1129:         if ($result eq 'ok') {
                   1130:             if (!($perm_reqd eq 'yes')) {
                   1131:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1132:             }
                   1133:         }
                   1134:     }
                   1135:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1136: }
                   1137: 
                   1138: sub retrievestudentphoto {
                   1139:     my ($udom,$unam,$ext,$type) = @_;
                   1140:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1141:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1142:     if ($ret eq 'ok') {
                   1143:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1144:         if ($type eq 'thumbnail') {
                   1145:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1146:         }
                   1147:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1148:         return $tokenurl;
                   1149:     } else {
                   1150:         if ($type eq 'thumbnail') {
                   1151:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1152:         } else { 
                   1153:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1154:         }
1.617     albertel 1155:     }
                   1156: }
                   1157: 
1.263     www      1158: # -------------------------------------------------------------------- New chat
                   1159: 
                   1160: sub chatsend {
1.724     raeburn  1161:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1162:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1163:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1164:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1165:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1166: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1167: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1168: }
                   1169: 
                   1170: # ------------------------------------------ Find current version of a resource
                   1171: 
                   1172: sub getversion {
                   1173:     my $fname=&clutter(shift);
                   1174:     unless ($fname=~/^\/res\//) { return -1; }
                   1175:     return &currentversion(&filelocation('',$fname));
                   1176: }
                   1177: 
                   1178: sub currentversion {
                   1179:     my $fname=shift;
1.599     albertel 1180:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1181:     if (defined($cached)) { return $result; }
1.292     www      1182:     my $author=$fname;
                   1183:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1184:     my ($udom,$uname)=split(/\//,$author);
                   1185:     my $home=homeserver($uname,$udom);
                   1186:     if ($home eq 'no_host') { 
                   1187:         return -1; 
                   1188:     }
                   1189:     my $answer=reply("currentversion:$fname",$home);
                   1190:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1191: 	return -1;
                   1192:     }
1.599     albertel 1193:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1194: }
                   1195: 
1.1       albertel 1196: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1197: 
1.1       albertel 1198: sub subscribe {
                   1199:     my $fname=shift;
1.761     raeburn  1200:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1201:     $fname=~s/[\n\r]//g;
1.1       albertel 1202:     my $author=$fname;
                   1203:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1204:     my ($udom,$uname)=split(/\//,$author);
                   1205:     my $home=homeserver($uname,$udom);
1.335     albertel 1206:     if ($home eq 'no_host') {
                   1207:         return 'not_found';
1.1       albertel 1208:     }
                   1209:     my $answer=reply("sub:$fname",$home);
1.64      www      1210:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1211: 	$answer.=' by '.$home;
                   1212:     }
1.1       albertel 1213:     return $answer;
                   1214: }
                   1215:     
1.8       www      1216: # -------------------------------------------------------------- Replicate file
                   1217: 
                   1218: sub repcopy {
                   1219:     my $filename=shift;
1.23      www      1220:     $filename=~s/\/+/\//g;
1.607     raeburn  1221:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1222:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1223:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1224: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1225: 	return &repcopy_userfile($filename);
                   1226:     }
1.532     albertel 1227:     $filename=~s/[\n\r]//g;
1.8       www      1228:     my $transname="$filename.in.transfer";
1.828     www      1229: # FIXME: this should flock
1.607     raeburn  1230:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1231:     my $remoteurl=subscribe($filename);
1.64      www      1232:     if ($remoteurl =~ /^con_lost by/) {
                   1233: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1234:            return 'unavailable';
1.8       www      1235:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1236: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1237: 	   return 'not_found';
1.64      www      1238:     } elsif ($remoteurl =~ /^rejected by/) {
                   1239: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1240:            return 'forbidden';
1.20      www      1241:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1242:            return 'ok';
1.8       www      1243:     } else {
1.290     www      1244:         my $author=$filename;
                   1245:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1246:         my ($udom,$uname)=split(/\//,$author);
                   1247:         my $home=homeserver($uname,$udom);
                   1248:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1249:            my @parts=split(/\//,$filename);
                   1250:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1251:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1252:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1253: 	       return 'bad_request';
1.8       www      1254:            }
                   1255:            my $count;
                   1256:            for ($count=5;$count<$#parts;$count++) {
                   1257:                $path.="/$parts[$count]";
                   1258:                if ((-e $path)!=1) {
                   1259: 		   mkdir($path,0777);
                   1260:                }
                   1261:            }
                   1262:            my $ua=new LWP::UserAgent;
                   1263:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1264:            my $response=$ua->request($request,$transname);
                   1265:            if ($response->is_error()) {
                   1266: 	       unlink($transname);
                   1267:                my $message=$response->status_line;
1.672     albertel 1268:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1269:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1270:                return 'unavailable';
1.8       www      1271:            } else {
1.16      www      1272: 	       if ($remoteurl!~/\.meta$/) {
                   1273:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1274:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1275:                   if ($mresponse->is_error()) {
                   1276: 		      unlink($filename.'.meta');
                   1277:                       &logthis(
1.672     albertel 1278:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1279:                   }
                   1280: 	       }
1.8       www      1281:                rename($transname,$filename);
1.607     raeburn  1282:                return 'ok';
1.8       www      1283:            }
1.290     www      1284:        }
1.8       www      1285:     }
1.330     www      1286: }
                   1287: 
                   1288: # ------------------------------------------------ Get server side include body
                   1289: sub ssi_body {
1.381     albertel 1290:     my ($filelink,%form)=@_;
1.606     matthew  1291:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1292:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1293:     }
1.330     www      1294:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1295:                                      &ssi($filelink,%form));
1.778     albertel 1296:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1297:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1298:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1299:     return $output;
1.8       www      1300: }
                   1301: 
1.15      www      1302: # --------------------------------------------------------- Server Side Include
                   1303: 
1.782     albertel 1304: sub absolute_url {
                   1305:     my ($host_name) = @_;
                   1306:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1307:     if ($host_name eq '') {
                   1308: 	$host_name = $ENV{'SERVER_NAME'};
                   1309:     }
                   1310:     return $protocol.$host_name;
                   1311: }
                   1312: 
1.15      www      1313: sub ssi {
                   1314: 
1.23      www      1315:     my ($fn,%form)=@_;
1.15      www      1316: 
                   1317:     my $ua=new LWP::UserAgent;
1.23      www      1318:     
                   1319:     my $request;
1.711     albertel 1320: 
                   1321:     $form{'no_update_last_known'}=1;
                   1322: 
1.23      www      1323:     if (%form) {
1.782     albertel 1324:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1325:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1326:     } else {
1.782     albertel 1327:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1328:     }
                   1329: 
1.15      www      1330:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1331:     my $response=$ua->request($request);
                   1332: 
1.324     www      1333:     return $response->content;
                   1334: }
                   1335: 
                   1336: sub externalssi {
                   1337:     my ($url)=@_;
                   1338:     my $ua=new LWP::UserAgent;
                   1339:     my $request=new HTTP::Request('GET',$url);
                   1340:     my $response=$ua->request($request);
1.15      www      1341:     return $response->content;
                   1342: }
1.254     www      1343: 
1.492     albertel 1344: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1345: 
                   1346: sub allowuploaded {
                   1347:     my ($srcurl,$url)=@_;
                   1348:     $url=&clutter(&declutter($url));
                   1349:     my $dir=$url;
                   1350:     $dir=~s/\/[^\/]+$//;
                   1351:     my %httpref=();
                   1352:     my $httpurl=&hreflocation('',$url);
                   1353:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1354:     &Apache::lonnet::appenv(%httpref);
1.254     www      1355: }
1.477     raeburn  1356: 
1.478     albertel 1357: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1358: # input: action, courseID, current domain, intended
1.637     raeburn  1359: #        path to file, source of file, instruction to parse file for objects,
                   1360: #        ref to hash for embedded objects,
                   1361: #        ref to hash for codebase of java objects.
                   1362: #
1.485     raeburn  1363: # output: url to file (if action was uploaddoc), 
                   1364: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1365: #
1.478     albertel 1366: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1367: # course.
1.477     raeburn  1368: #
1.478     albertel 1369: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1370: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1371: #          course's home server.
1.477     raeburn  1372: #
1.478     albertel 1373: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1374: #          be copied from $source (current location) to 
                   1375: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1376: #         and will then be copied to
                   1377: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1378: #         course's home server.
1.485     raeburn  1379: #
1.481     raeburn  1380: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1381: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1382: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1383: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1384: #         in course's home server.
1.637     raeburn  1385: #
1.477     raeburn  1386: 
                   1387: sub process_coursefile {
1.638     albertel 1388:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1389:     my $fetchresult;
1.638     albertel 1390:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1391:     if ($action eq 'propagate') {
1.638     albertel 1392:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1393: 			     $home);
1.481     raeburn  1394:     } else {
1.477     raeburn  1395:         my $fpath = '';
                   1396:         my $fname = $file;
1.478     albertel 1397:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1398:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1399:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1400:         if ($action eq 'copy') {
                   1401:             if ($source eq '') {
                   1402:                 $fetchresult = 'no source file';
                   1403:                 return $fetchresult;
                   1404:             } else {
                   1405:                 my $destination = $filepath.'/'.$fname;
                   1406:                 rename($source,$destination);
                   1407:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1408:                                  $home);
1.481     raeburn  1409:             }
                   1410:         } elsif ($action eq 'uploaddoc') {
                   1411:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1412:             print $fh $env{'form.'.$source};
1.481     raeburn  1413:             close($fh);
1.637     raeburn  1414:             if ($parser eq 'parse') {
                   1415:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1416:                 unless ($parse_result eq 'ok') {
                   1417:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1418:                 }
                   1419:             }
1.477     raeburn  1420:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1421:                                  $home);
1.481     raeburn  1422:             if ($fetchresult eq 'ok') {
                   1423:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1424:             } else {
                   1425:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1426:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1427:                 return '/adm/notfound.html';
                   1428:             }
1.477     raeburn  1429:         }
                   1430:     }
1.485     raeburn  1431:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1432:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1433:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1434:     }
                   1435:     return $fetchresult;
                   1436: }
                   1437: 
1.637     raeburn  1438: sub build_filepath {
                   1439:     my ($fpath) = @_;
                   1440:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1441:     unless ($fpath eq '') {
                   1442:         my @parts=split('/',$fpath);
                   1443:         foreach my $part (@parts) {
                   1444:             $filepath.= '/'.$part;
                   1445:             if ((-e $filepath)!=1) {
                   1446:                 mkdir($filepath,0777);
                   1447:             }
                   1448:         }
                   1449:     }
                   1450:     return $filepath;
                   1451: }
                   1452: 
                   1453: sub store_edited_file {
1.638     albertel 1454:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1455:     my $file = $primary_url;
                   1456:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1457:     my $fpath = '';
                   1458:     my $fname = $file;
                   1459:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1460:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1461:     my $filepath = &build_filepath($fpath);
                   1462:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1463:     print $fh $content;
                   1464:     close($fh);
1.638     albertel 1465:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1466:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1467: 			  $home);
1.637     raeburn  1468:     if ($$fetchresult eq 'ok') {
                   1469:         return '/uploaded/'.$fpath.'/'.$fname;
                   1470:     } else {
1.638     albertel 1471:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1472: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1473:         return '/adm/notfound.html';
                   1474:     }
                   1475: }
                   1476: 
1.531     albertel 1477: sub clean_filename {
1.831     albertel 1478:     my ($fname,$args)=@_;
1.315     www      1479: # Replace Windows backslashes by forward slashes
1.257     www      1480:     $fname=~s/\\/\//g;
1.831     albertel 1481:     if (!$args->{'keep_path'}) {
                   1482:         # Get rid of everything but the actual filename
                   1483: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1484:     }
1.315     www      1485: # Replace spaces by underscores
                   1486:     $fname=~s/\s+/\_/g;
                   1487: # Replace all other weird characters by nothing
1.831     albertel 1488:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1489: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1490: # numbers
                   1491:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1492:     return $fname;
                   1493: }
                   1494: 
1.608     albertel 1495: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1496: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1497: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1498: #        $coursedoc - if true up to the current course
                   1499: #                     if false
                   1500: #        $subdir - directory in userfile to store the file into
                   1501: #        $parser, $allfiles, $codebase - unknown
                   1502: #
                   1503: # output: url of file in userspace, or error: <message> 
                   1504: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1505: 
                   1506: 
1.531     albertel 1507: sub userfileupload {
1.719     banghart 1508:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1509:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1510:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1511:     $fname=&clean_filename($fname);
1.315     www      1512: # See if there is anything left
1.257     www      1513:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1514:     chop($env{'form.'.$formname});
1.523     raeburn  1515:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1516:         my $now = time;
                   1517:         my $filepath = 'tmp/helprequests/'.$now;
                   1518:         my @parts=split(/\//,$filepath);
                   1519:         my $fullpath = $perlvar{'lonDaemons'};
                   1520:         for (my $i=0;$i<@parts;$i++) {
                   1521:             $fullpath .= '/'.$parts[$i];
                   1522:             if ((-e $fullpath)!=1) {
                   1523:                 mkdir($fullpath,0777);
                   1524:             }
                   1525:         }
                   1526:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1527:         print $fh $env{'form.'.$formname};
1.523     raeburn  1528:         close($fh);
1.741     raeburn  1529:         return $fullpath.'/'.$fname;
                   1530:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1531:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1532:                        '_'.$env{'user.domain'}.'/pending';
                   1533:         my @parts=split(/\//,$filepath);
                   1534:         my $fullpath = $perlvar{'lonDaemons'};
                   1535:         for (my $i=0;$i<@parts;$i++) {
                   1536:             $fullpath .= '/'.$parts[$i];
                   1537:             if ((-e $fullpath)!=1) {
                   1538:                 mkdir($fullpath,0777);
                   1539:             }
                   1540:         }
                   1541:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1542:         print $fh $env{'form.'.$formname};
                   1543:         close($fh);
                   1544:         return $fullpath.'/'.$fname;
1.523     raeburn  1545:     }
1.719     banghart 1546:     
1.258     www      1547: # Create the directory if not present
1.493     albertel 1548:     $fname="$subdir/$fname";
1.259     www      1549:     if ($coursedoc) {
1.638     albertel 1550: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1551: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1552:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1553:             return &finishuserfileupload($docuname,$docudom,
                   1554: 					 $formname,$fname,$parser,$allfiles,
                   1555: 					 $codebase);
1.481     raeburn  1556:         } else {
1.620     albertel 1557:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1558:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1559: 				       $fname,$formname,$parser,
                   1560: 				       $allfiles,$codebase);
1.481     raeburn  1561:         }
1.719     banghart 1562:     } elsif (defined($destuname)) {
                   1563:         my $docuname=$destuname;
                   1564:         my $docudom=$destudom;
                   1565: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1566: 				     $fname,$parser,$allfiles,$codebase);
                   1567:         
1.259     www      1568:     } else {
1.638     albertel 1569:         my $docuname=$env{'user.name'};
                   1570:         my $docudom=$env{'user.domain'};
1.714     raeburn  1571:         if (exists($env{'form.group'})) {
                   1572:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1573:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1574:         }
1.638     albertel 1575: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1576: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1577:     }
1.271     www      1578: }
                   1579: 
                   1580: sub finishuserfileupload {
1.638     albertel 1581:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1582:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1583:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1584:     my ($fnamepath,$file);
                   1585:     $file=$fname;
                   1586:     if ($fname=~m|/|) {
                   1587:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1588: 	$path.=$fnamepath.'/';
                   1589:     }
1.259     www      1590:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1591:     my $count;
                   1592:     for ($count=4;$count<=$#parts;$count++) {
                   1593:         $filepath.="/$parts[$count]";
                   1594:         if ((-e $filepath)!=1) {
                   1595: 	    mkdir($filepath,0777);
                   1596:         }
                   1597:     }
                   1598: # Save the file
                   1599:     {
1.701     albertel 1600: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1601: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1602: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1603: 	    return '/adm/notfound.html';
                   1604: 	}
                   1605: 	if (!print FH ($env{'form.'.$formname})) {
                   1606: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1607: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1608: 	    return '/adm/notfound.html';
                   1609: 	}
1.570     albertel 1610: 	close(FH);
1.258     www      1611:     }
1.637     raeburn  1612:     if ($parser eq 'parse') {
1.638     albertel 1613:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1614: 						   $codebase);
1.637     raeburn  1615:         unless ($parse_result eq 'ok') {
1.638     albertel 1616:             &logthis('Failed to parse '.$filepath.$file.
                   1617: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1618:         }
                   1619:     }
1.259     www      1620: # Notify homeserver to grep it
                   1621: #
1.638     albertel 1622:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1623:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1624:     if ($fetchresult eq 'ok') {
1.259     www      1625: #
1.258     www      1626: # Return the URL to it
1.494     albertel 1627:         return '/uploaded/'.$path.$file;
1.263     www      1628:     } else {
1.494     albertel 1629:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1630: 		 ': '.$fetchresult);
1.263     www      1631:         return '/adm/notfound.html';
                   1632:     }    
1.493     albertel 1633: }
                   1634: 
1.637     raeburn  1635: sub extract_embedded_items {
1.648     raeburn  1636:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1637:     my @state = ();
                   1638:     my %javafiles = (
                   1639:                       codebase => '',
                   1640:                       code => '',
                   1641:                       archive => ''
                   1642:                     );
                   1643:     my %mediafiles = (
                   1644:                       src => '',
                   1645:                       movie => '',
                   1646:                      );
1.648     raeburn  1647:     my $p;
                   1648:     if ($content) {
                   1649:         $p = HTML::LCParser->new($content);
                   1650:     } else {
                   1651:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1652:     }
1.641     albertel 1653:     while (my $t=$p->get_token()) {
1.640     albertel 1654: 	if ($t->[0] eq 'S') {
                   1655: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1656: 	    push (@state, $tagname);
1.648     raeburn  1657:             if (lc($tagname) eq 'allow') {
                   1658:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1659:             }
1.640     albertel 1660: 	    if (lc($tagname) eq 'img') {
                   1661: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1662: 	    }
1.645     raeburn  1663:             if (lc($tagname) eq 'script') {
                   1664:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1665:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1666:                 } else {
                   1667:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1668:                 }
                   1669:             }
                   1670:             if (lc($tagname) eq 'link') {
                   1671:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1672:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1673:                 }
                   1674:             }
1.640     albertel 1675: 	    if (lc($tagname) eq 'object' ||
                   1676: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1677: 		foreach my $item (keys(%javafiles)) {
                   1678: 		    $javafiles{$item} = '';
                   1679: 		}
                   1680: 	    }
                   1681: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1682: 		my $name = lc($attr->{'name'});
                   1683: 		foreach my $item (keys(%javafiles)) {
                   1684: 		    if ($name eq $item) {
                   1685: 			$javafiles{$item} = $attr->{'value'};
                   1686: 			last;
                   1687: 		    }
                   1688: 		}
                   1689: 		foreach my $item (keys(%mediafiles)) {
                   1690: 		    if ($name eq $item) {
                   1691: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1692: 			last;
                   1693: 		    }
                   1694: 		}
                   1695: 	    }
                   1696: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1697: 		foreach my $item (keys(%javafiles)) {
                   1698: 		    if ($attr->{$item}) {
                   1699: 			$javafiles{$item} = $attr->{$item};
                   1700: 			last;
                   1701: 		    }
                   1702: 		}
                   1703: 		foreach my $item (keys(%mediafiles)) {
                   1704: 		    if ($attr->{$item}) {
                   1705: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1706: 			last;
                   1707: 		    }
                   1708: 		}
                   1709: 	    }
                   1710: 	} elsif ($t->[0] eq 'E') {
                   1711: 	    my ($tagname) = ($t->[1]);
                   1712: 	    if ($javafiles{'codebase'} ne '') {
                   1713: 		$javafiles{'codebase'} .= '/';
                   1714: 	    }  
                   1715: 	    if (lc($tagname) eq 'applet' ||
                   1716: 		lc($tagname) eq 'object' ||
                   1717: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1718: 		) {
                   1719: 		foreach my $item (keys(%javafiles)) {
                   1720: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1721: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1722: 			&add_filetype($allfiles,$file,$item);
                   1723: 		    }
                   1724: 		}
                   1725: 	    } 
                   1726: 	    pop @state;
                   1727: 	}
                   1728:     }
1.637     raeburn  1729:     return 'ok';
                   1730: }
                   1731: 
1.639     albertel 1732: sub add_filetype {
                   1733:     my ($allfiles,$file,$type)=@_;
                   1734:     if (exists($allfiles->{$file})) {
                   1735: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1736: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1737: 	}
                   1738:     } else {
                   1739: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1740:     }
                   1741: }
                   1742: 
1.493     albertel 1743: sub removeuploadedurl {
                   1744:     my ($url)=@_;
                   1745:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1746:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1747: }
                   1748: 
                   1749: sub removeuserfile {
                   1750:     my ($docuname,$docudom,$fname)=@_;
                   1751:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1752:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1753:     if ($result eq 'ok') {
                   1754:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1755:             my $metafile = $fname.'.meta';
                   1756:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1757: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1758:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1759:             my $sqlresult = 
1.823     albertel 1760:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1761:                                         'portfolio_metadata',$group,
                   1762:                                         'delete');
1.798     raeburn  1763:         }
                   1764:     }
                   1765:     return $result;
1.257     www      1766: }
1.15      www      1767: 
1.530     albertel 1768: sub mkdiruserfile {
                   1769:     my ($docuname,$docudom,$dir)=@_;
                   1770:     my $home=&homeserver($docuname,$docudom);
                   1771:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1772: }
                   1773: 
1.531     albertel 1774: sub renameuserfile {
                   1775:     my ($docuname,$docudom,$old,$new)=@_;
                   1776:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1777:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1778:                         &escape("$old").':'.&escape("$new"),$home);
                   1779:     if ($result eq 'ok') {
                   1780:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1781:             my $oldmeta = $old.'.meta';
                   1782:             my $newmeta = $new.'.meta';
                   1783:             my $metaresult = 
                   1784:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1785: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1786:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1787:             my $sqlresult = 
1.823     albertel 1788:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1789:                                         'portfolio_metadata',$group,
                   1790:                                         'delete');
1.798     raeburn  1791:         }
                   1792:     }
                   1793:     return $result;
1.531     albertel 1794: }
                   1795: 
1.14      www      1796: # ------------------------------------------------------------------------- Log
                   1797: 
                   1798: sub log {
                   1799:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1800:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1801: }
                   1802: 
                   1803: # ------------------------------------------------------------------ Course Log
1.352     www      1804: #
                   1805: # This routine flushes several buffers of non-mission-critical nature
                   1806: #
1.157     www      1807: 
                   1808: sub flushcourselogs {
1.352     www      1809:     &logthis('Flushing log buffers');
                   1810: #
                   1811: # course logs
                   1812: # This is a log of all transactions in a course, which can be used
                   1813: # for data mining purposes
                   1814: #
                   1815: # It also collects the courseid database, which lists last transaction
                   1816: # times and course titles for all courseids
                   1817: #
                   1818:     my %courseidbuffer=();
1.800     albertel 1819:     foreach my $crsid (keys %courselogs) {
1.352     www      1820:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1821: 		          &escape($courselogs{$crsid}),
                   1822: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1823: 	    delete $courselogs{$crsid};
                   1824:         } else {
                   1825:             &logthis('Failed to flush log buffer for '.$crsid);
                   1826:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1827:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1828:                         " exceeded maximum size, deleting.</font>");
                   1829:                delete $courselogs{$crsid};
                   1830:             }
1.352     www      1831:         }
                   1832:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1833:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1834: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1835:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1836:         } else {
                   1837:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1838: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1839:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1840:         }
1.191     harris41 1841:     }
1.352     www      1842: #
                   1843: # Write course id database (reverse lookup) to homeserver of courses 
                   1844: # Is used in pickcourse
                   1845: #
1.800     albertel 1846:     foreach my $crsid (keys(%courseidbuffer)) {
                   1847:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1848:     }
                   1849: #
                   1850: # File accesses
                   1851: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1852: #
1.449     matthew  1853:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1854:         if ($entry =~ /___count$/) {
                   1855:             my ($dom,$name);
1.807     albertel 1856:             ($dom,$name,undef)=
1.811     albertel 1857: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1858:             if (! defined($dom) || $dom eq '' || 
                   1859:                 ! defined($name) || $name eq '') {
1.620     albertel 1860:                 my $cid = $env{'request.course.id'};
                   1861:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1862:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1863:             }
1.450     matthew  1864:             my $value = $accesshash{$entry};
                   1865:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1866:             my %temphash=($url => $value);
1.449     matthew  1867:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1868:             if ($result eq 'ok') {
                   1869:                 delete $accesshash{$entry};
                   1870:             } elsif ($result eq 'unknown_cmd') {
                   1871:                 # Target server has old code running on it.
1.450     matthew  1872:                 my %temphash=($entry => $value);
1.449     matthew  1873:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1874:                     delete $accesshash{$entry};
                   1875:                 }
                   1876:             }
                   1877:         } else {
1.811     albertel 1878:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1879:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1880:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1881:                 delete $accesshash{$entry};
                   1882:             }
1.185     www      1883:         }
1.191     harris41 1884:     }
1.352     www      1885: #
                   1886: # Roles
                   1887: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1888: #
1.800     albertel 1889:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1890:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1891: 	    split(/\:/,$entry);
                   1892:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1893:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1894:                 $rudom,$runame) eq 'ok') {
                   1895: 	    delete $userrolehash{$entry};
                   1896:         }
                   1897:     }
1.662     raeburn  1898: #
                   1899: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1900: #
                   1901:     my %domrolebuffer = ();
                   1902:     foreach my $entry (keys %domainrolehash) {
                   1903:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1904:         if ($domrolebuffer{$rudom}) {
                   1905:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1906:                       '='.&escape($domainrolehash{$entry});
                   1907:         } else {
                   1908:             $domrolebuffer{$rudom}.=&escape($entry).
                   1909:                       '='.&escape($domainrolehash{$entry});
                   1910:         }
                   1911:         delete $domainrolehash{$entry};
                   1912:     }
                   1913:     foreach my $dom (keys(%domrolebuffer)) {
                   1914:         foreach my $tryserver (keys %libserv) {
                   1915:             if ($hostdom{$tryserver} eq $dom) {
                   1916:                 unless (&reply('domroleput:'.$dom.':'.
                   1917:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1918:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1919:                 }
                   1920:             }
                   1921:         }
                   1922:     }
1.186     www      1923:     $dumpcount++;
1.157     www      1924: }
                   1925: 
                   1926: sub courselog {
                   1927:     my $what=shift;
1.158     www      1928:     $what=time.':'.$what;
1.620     albertel 1929:     unless ($env{'request.course.id'}) { return ''; }
                   1930:     $coursedombuf{$env{'request.course.id'}}=
                   1931:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1932:     $coursenumbuf{$env{'request.course.id'}}=
                   1933:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1934:     $coursehombuf{$env{'request.course.id'}}=
                   1935:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1936:     $coursedescrbuf{$env{'request.course.id'}}=
                   1937:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1938:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1939:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1940:     $courseownerbuf{$env{'request.course.id'}}=
                   1941:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1942:     $coursetypebuf{$env{'request.course.id'}}=
                   1943:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1944:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1945: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1946:     } else {
1.620     albertel 1947: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1948:     }
1.620     albertel 1949:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1950: 	&flushcourselogs();
                   1951:     }
1.158     www      1952: }
                   1953: 
                   1954: sub courseacclog {
                   1955:     my $fnsymb=shift;
1.620     albertel 1956:     unless ($env{'request.course.id'}) { return ''; }
                   1957:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1958:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1959:         $what.=':POST';
1.583     matthew  1960:         # FIXME: Probably ought to escape things....
1.800     albertel 1961: 	foreach my $key (keys(%env)) {
                   1962:             if ($key=~/^form\.(.*)/) {
                   1963: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1964:             }
1.191     harris41 1965:         }
1.583     matthew  1966:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1967:         # FIXME: We should not be depending on a form parameter that someone
                   1968:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1969:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1970:             $what.= ':POST';
                   1971:             # FIXME: Probably ought to escape things....
                   1972:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1973:                                  'crsdiscuss') {
1.620     albertel 1974:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1975:             }
                   1976:         }
1.158     www      1977:     }
                   1978:     &courselog($what);
1.149     www      1979: }
                   1980: 
1.185     www      1981: sub countacc {
                   1982:     my $url=&declutter(shift);
1.458     matthew  1983:     return if (! defined($url) || $url eq '');
1.620     albertel 1984:     unless ($env{'request.course.id'}) { return ''; }
                   1985:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1986:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1987:     $accesshash{$key}++;
1.185     www      1988: }
1.349     www      1989: 
1.361     www      1990: sub linklog {
                   1991:     my ($from,$to)=@_;
                   1992:     $from=&declutter($from);
                   1993:     $to=&declutter($to);
                   1994:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1995:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1996: }
                   1997:   
1.349     www      1998: sub userrolelog {
                   1999:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2000:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2001:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2002:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2003:         ($trole=~/^ta/)) {
1.350     www      2004:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2005:        $userrolehash
                   2006:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2007:                     =$tend.':'.$tstart;
1.662     raeburn  2008:     }
                   2009:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2010:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2011:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2012:         ($trole=~/^sc/)) {
                   2013:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2014:        $domainrolehash
                   2015:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2016:                     = $tend.':'.$tstart;
                   2017:     }
1.351     www      2018: }
                   2019: 
                   2020: sub get_course_adv_roles {
                   2021:     my $cid=shift;
1.620     albertel 2022:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2023:     my %coursehash=&coursedescription($cid);
1.470     www      2024:     my %nothide=();
1.800     albertel 2025:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2026: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2027:     }
1.351     www      2028:     my %returnhash=();
                   2029:     my %dumphash=
                   2030:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2031:     my $now=time;
1.800     albertel 2032:     foreach my $entry (keys %dumphash) {
                   2033: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2034:         if (($tstart) && ($tstart<0)) { next; }
                   2035:         if (($tend) && ($tend<$now)) { next; }
                   2036:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2037:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2038: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2039: 	if ((&privileged($username,$domain)) && 
                   2040: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2041: 	if ($role eq 'cr') { next; }
1.351     www      2042:         my $key=&plaintext($role);
                   2043:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2044:         if ($returnhash{$key}) {
                   2045: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2046:         } else {
                   2047:             $returnhash{$key}=$username.':'.$domain;
                   2048:         }
1.400     www      2049:      }
                   2050:     return %returnhash;
                   2051: }
                   2052: 
                   2053: sub get_my_roles {
1.832     raeburn  2054:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
1.620     albertel 2055:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2056:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2057:     my %dumphash=
                   2058:             &dump('nohist_userroles',$udom,$uname);
                   2059:     my %returnhash=();
                   2060:     my $now=time;
1.800     albertel 2061:     foreach my $entry (keys(%dumphash)) {
                   2062: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2063:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2064:         my $status = 'active';
                   2065:         if (($tend) && ($tend<$now)) {
                   2066:             $status = 'previous';
                   2067:         } 
                   2068:         if (($tstart) && ($now<$tstart)) {
                   2069:             $status = 'future';
                   2070:         }
                   2071:         if (ref($types) eq 'ARRAY') {
                   2072:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2073:                 next;
                   2074:             } 
                   2075:         } else {
                   2076:             if ($status ne 'active') {
                   2077:                 next;
                   2078:             }
                   2079:         }
1.800     albertel 2080:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.832     raeburn  2081:         if (ref($roledoms) eq 'ARRAY') {
                   2082:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2083:                 next;
                   2084:             }
                   2085:         }
                   2086:         if (ref($roles) eq 'ARRAY') {
                   2087:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2088:                 next;
                   2089:             }
                   2090:         } 
1.400     www      2091: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2092:     }
1.373     www      2093:     return %returnhash;
1.399     www      2094: }
                   2095: 
                   2096: # ----------------------------------------------------- Frontpage Announcements
                   2097: #
                   2098: #
                   2099: 
                   2100: sub postannounce {
                   2101:     my ($server,$text)=@_;
                   2102:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2103:     unless ($text=~/\w/) { $text=''; }
                   2104:     return &reply('setannounce:'.&escape($text),$server);
                   2105: }
                   2106: 
                   2107: sub getannounce {
1.448     albertel 2108: 
                   2109:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2110: 	my $announcement='';
1.800     albertel 2111: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2112: 	close($fh);
1.399     www      2113: 	if ($announcement=~/\w/) { 
                   2114: 	    return 
                   2115:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2116:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2117: 	} else {
                   2118: 	    return '';
                   2119: 	}
                   2120:     } else {
                   2121: 	return '';
                   2122:     }
1.351     www      2123: }
1.353     www      2124: 
                   2125: # ---------------------------------------------------------- Course ID routines
                   2126: # Deal with domain's nohist_courseid.db files
                   2127: #
                   2128: 
                   2129: sub courseidput {
                   2130:     my ($domain,$what,$coursehome)=@_;
                   2131:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2132: }
                   2133: 
                   2134: sub courseiddump {
1.791     raeburn  2135:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2136:     my %returnhash=();
1.355     www      2137:     unless ($domfilter) { $domfilter=''; }
1.353     www      2138:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2139:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2140: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2141: 	        foreach my $line (
1.506     raeburn  2142:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2143: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2144:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2145:                                $tryserver))) {
1.800     albertel 2146: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2147:                     if (($key) && ($value)) {
1.516     raeburn  2148: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2149:                     }
1.353     www      2150:                 }
                   2151:             }
                   2152:         }
                   2153:     }
                   2154:     return %returnhash;
                   2155: }
                   2156: 
1.658     raeburn  2157: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2158: 
                   2159: sub dcmailput {
1.685     raeburn  2160:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2161:     my $status = &Apache::lonnet::critical(
1.740     www      2162:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2163:        &escape($message),$server);
1.662     raeburn  2164:     return $status;
                   2165: }
                   2166: 
1.658     raeburn  2167: sub dcmaildump {
                   2168:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2169:     my %returnhash=();
                   2170:     if (exists($domain_primary{$dom})) {
                   2171:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2172:                                                          &escape($enddate).':';
                   2173: 	my @esc_senders=map { &escape($_)} @$senders;
                   2174: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2175: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2176:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2177:             if (($key) && ($value)) {
                   2178:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2179:             }
                   2180:         }
                   2181:     }
                   2182:     return %returnhash;
                   2183: }
1.662     raeburn  2184: # ---------------------------------------------------------- Domain roles
                   2185: 
                   2186: sub get_domain_roles {
                   2187:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2188:     if (undef($startdate) || $startdate eq '') {
                   2189:         $startdate = '.';
                   2190:     }
                   2191:     if (undef($enddate) || $enddate eq '') {
                   2192:         $enddate = '.';
                   2193:     }
                   2194:     my $rolelist = join(':',@{$roles});
                   2195:     my %personnel = ();
                   2196:     foreach my $tryserver (keys(%libserv)) {
                   2197:         if ($hostdom{$tryserver} eq $dom) {
                   2198:             %{$personnel{$tryserver}}=();
1.800     albertel 2199:             foreach my $line (
1.662     raeburn  2200:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2201:                    &escape($startdate).':'.&escape($enddate).':'.
                   2202:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2203:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2204:                 if (($key) && ($value)) {
                   2205:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2206:                 }
                   2207:             }
                   2208:         }
                   2209:     }
                   2210:     return %personnel;
                   2211: }
1.658     raeburn  2212: 
1.149     www      2213: # ----------------------------------------------------------- Check out an item
                   2214: 
1.504     albertel 2215: sub get_first_access {
                   2216:     my ($type,$argsymb)=@_;
1.790     albertel 2217:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2218:     if ($argsymb) { $symb=$argsymb; }
                   2219:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2220:     if ($type eq 'map') {
                   2221: 	$res=&symbread($map);
                   2222:     } else {
                   2223: 	$res=$symb;
                   2224:     }
                   2225:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2226:     return $times{"$courseid\0$res"};
1.504     albertel 2227: }
                   2228: 
                   2229: sub set_first_access {
                   2230:     my ($type)=@_;
1.790     albertel 2231:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2232:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2233:     if ($type eq 'map') {
                   2234: 	$res=&symbread($map);
                   2235:     } else {
                   2236: 	$res=$symb;
                   2237:     }
                   2238:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2239:     if (!$firstaccess) {
1.588     albertel 2240: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2241:     }
                   2242:     return 'already_set';
1.504     albertel 2243: }
                   2244: 
1.149     www      2245: sub checkout {
                   2246:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2247:     my $now=time;
                   2248:     my $lonhost=$perlvar{'lonHostID'};
                   2249:     my $infostr=&escape(
1.234     www      2250:                  'CHECKOUTTOKEN&'.
1.149     www      2251:                  $tuname.'&'.
                   2252:                  $tudom.'&'.
                   2253:                  $tcrsid.'&'.
                   2254:                  $symb.'&'.
                   2255: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2256:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2257:     if ($token=~/^error\:/) { 
1.672     albertel 2258:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2259:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2260:                  "</font>");
                   2261:         return ''; 
                   2262:     }
                   2263: 
1.149     www      2264:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2265:     $token=~tr/a-z/A-Z/;
                   2266: 
1.153     www      2267:     my %infohash=('resource.0.outtoken' => $token,
                   2268:                   'resource.0.checkouttime' => $now,
                   2269:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2270: 
                   2271:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2272:        return '';
1.151     www      2273:     } else {
1.672     albertel 2274:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2275:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2276:                  "</font>");
1.149     www      2277:     }    
                   2278: 
                   2279:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2280:                          &escape('Checkout '.$infostr.' - '.
                   2281:                                                  $token)) ne 'ok') {
                   2282: 	return '';
1.151     www      2283:     } else {
1.672     albertel 2284:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2285:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2286:                  "</font>");
1.149     www      2287:     }
1.151     www      2288:     return $token;
1.149     www      2289: }
                   2290: 
                   2291: # ------------------------------------------------------------ Check in an item
                   2292: 
                   2293: sub checkin {
                   2294:     my $token=shift;
1.150     www      2295:     my $now=time;
                   2296:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2297:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2298:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2299:     $dtoken=~s/\W/\_/g;
1.234     www      2300:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2301:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2302: 
1.154     www      2303:     unless (($tuname) && ($tudom)) {
                   2304:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2305:         return '';
                   2306:     }
                   2307:     
                   2308:     unless (&allowed('mgr',$tcrsid)) {
                   2309:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2310:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2311:         return '';
                   2312:     }
                   2313: 
1.153     www      2314:     my %infohash=('resource.0.intoken' => $token,
                   2315:                   'resource.0.checkintime' => $now,
                   2316:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2317: 
                   2318:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2319:        return '';
                   2320:     }    
                   2321: 
                   2322:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2323:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2324: 	return '';
                   2325:     }
                   2326: 
                   2327:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2328: }
                   2329: 
                   2330: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2331: 
                   2332: sub expirespread {
                   2333:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2334:     my $cid=$env{'request.course.id'}; 
1.110     www      2335:     if ($cid) {
                   2336:        my $now=time;
                   2337:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2338:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2339:                             $env{'course.'.$cid.'.num'}.
1.110     www      2340: 	        	    ':nohist_expirationdates:'.
                   2341:                             &escape($key).'='.$now,
1.620     albertel 2342:                             $env{'course.'.$cid.'.home'})
1.110     www      2343:     }
                   2344:     return 'ok';
1.14      www      2345: }
                   2346: 
1.109     www      2347: # ----------------------------------------------------- Devalidate Spreadsheets
                   2348: 
                   2349: sub devalidate {
1.325     www      2350:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2351:     my $cid=$env{'request.course.id'}; 
1.109     www      2352:     if ($cid) {
1.391     matthew  2353:         # delete the stored spreadsheets for
                   2354:         # - the student level sheet of this user in course's homespace
                   2355:         # - the assessment level sheet for this resource 
                   2356:         #   for this user in user's homespace
1.553     albertel 2357: 	# - current conditional state info
1.325     www      2358: 	my $key=$uname.':'.$udom.':';
1.109     www      2359:         my $status=
1.299     matthew  2360: 	    &del('nohist_calculatedsheets',
1.391     matthew  2361: 		 [$key.'studentcalc:'],
1.620     albertel 2362: 		 $env{'course.'.$cid.'.domain'},
                   2363: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2364: 		.' '.
                   2365: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2366: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2367:         unless ($status eq 'ok ok') {
                   2368:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2369:                     $uname.' at '.$udom.' for '.
1.109     www      2370: 		    $symb.': '.$status);
1.133     albertel 2371:         }
1.553     albertel 2372: 	&delenv('user.state.'.$cid);
1.109     www      2373:     }
                   2374: }
                   2375: 
1.265     albertel 2376: sub get_scalar {
                   2377:     my ($string,$end) = @_;
                   2378:     my $value;
                   2379:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2380: 	$value = $1;
                   2381:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2382: 	$value = $1;
                   2383:     }
                   2384:     return &unescape($value);
                   2385: }
                   2386: 
                   2387: sub array2str {
                   2388:   my (@array) = @_;
                   2389:   my $result=&arrayref2str(\@array);
                   2390:   $result=~s/^__ARRAY_REF__//;
                   2391:   $result=~s/__END_ARRAY_REF__$//;
                   2392:   return $result;
                   2393: }
                   2394: 
1.204     albertel 2395: sub arrayref2str {
                   2396:   my ($arrayref) = @_;
1.265     albertel 2397:   my $result='__ARRAY_REF__';
1.204     albertel 2398:   foreach my $elem (@$arrayref) {
1.265     albertel 2399:     if(ref($elem) eq 'ARRAY') {
                   2400:       $result.=&arrayref2str($elem).'&';
                   2401:     } elsif(ref($elem) eq 'HASH') {
                   2402:       $result.=&hashref2str($elem).'&';
                   2403:     } elsif(ref($elem)) {
                   2404:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2405:     } else {
                   2406:       $result.=&escape($elem).'&';
                   2407:     }
                   2408:   }
                   2409:   $result=~s/\&$//;
1.265     albertel 2410:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2411:   return $result;
                   2412: }
                   2413: 
1.168     albertel 2414: sub hash2str {
1.204     albertel 2415:   my (%hash) = @_;
                   2416:   my $result=&hashref2str(\%hash);
1.265     albertel 2417:   $result=~s/^__HASH_REF__//;
                   2418:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2419:   return $result;
                   2420: }
                   2421: 
                   2422: sub hashref2str {
                   2423:   my ($hashref)=@_;
1.265     albertel 2424:   my $result='__HASH_REF__';
1.800     albertel 2425:   foreach my $key (sort(keys(%$hashref))) {
                   2426:     if (ref($key) eq 'ARRAY') {
                   2427:       $result.=&arrayref2str($key).'=';
                   2428:     } elsif (ref($key) eq 'HASH') {
                   2429:       $result.=&hashref2str($key).'=';
                   2430:     } elsif (ref($key)) {
1.265     albertel 2431:       $result.='=';
1.800     albertel 2432:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2433:     } else {
1.800     albertel 2434: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2435:     }
                   2436: 
1.800     albertel 2437:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2438:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2439:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2440:       $result.=&hashref2str($hashref->{$key}).'&';
                   2441:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2442:        $result.='&';
1.800     albertel 2443:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2444:     } else {
1.800     albertel 2445:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2446:     }
                   2447:   }
1.168     albertel 2448:   $result=~s/\&$//;
1.265     albertel 2449:   $result .= '__END_HASH_REF__';
1.168     albertel 2450:   return $result;
                   2451: }
                   2452: 
                   2453: sub str2hash {
1.265     albertel 2454:     my ($string)=@_;
                   2455:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2456:     return %$hash;
                   2457: }
                   2458: 
                   2459: sub str2hashref {
1.168     albertel 2460:   my ($string) = @_;
1.265     albertel 2461: 
                   2462:   my %hash;
                   2463: 
                   2464:   if($string !~ /^__HASH_REF__/) {
                   2465:       if (! ($string eq '' || !defined($string))) {
                   2466: 	  $hash{'error'}='Not hash reference';
                   2467:       }
                   2468:       return (\%hash, $string);
                   2469:   }
                   2470: 
                   2471:   $string =~ s/^__HASH_REF__//;
                   2472: 
                   2473:   while($string !~ /^__END_HASH_REF__/) {
                   2474:       #key
                   2475:       my $key='';
                   2476:       if($string =~ /^__HASH_REF__/) {
                   2477:           ($key, $string)=&str2hashref($string);
                   2478:           if(defined($key->{'error'})) {
                   2479:               $hash{'error'}='Bad data';
                   2480:               return (\%hash, $string);
                   2481:           }
                   2482:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2483:           ($key, $string)=&str2arrayref($string);
                   2484:           if($key->[0] eq 'Array reference error') {
                   2485:               $hash{'error'}='Bad data';
                   2486:               return (\%hash, $string);
                   2487:           }
                   2488:       } else {
                   2489:           $string =~ s/^(.*?)=//;
1.267     albertel 2490: 	  $key=&unescape($1);
1.265     albertel 2491:       }
                   2492:       $string =~ s/^=//;
                   2493: 
                   2494:       #value
                   2495:       my $value='';
                   2496:       if($string =~ /^__HASH_REF__/) {
                   2497:           ($value, $string)=&str2hashref($string);
                   2498:           if(defined($value->{'error'})) {
                   2499:               $hash{'error'}='Bad data';
                   2500:               return (\%hash, $string);
                   2501:           }
                   2502:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2503:           ($value, $string)=&str2arrayref($string);
                   2504:           if($value->[0] eq 'Array reference error') {
                   2505:               $hash{'error'}='Bad data';
                   2506:               return (\%hash, $string);
                   2507:           }
                   2508:       } else {
                   2509: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2510:       }
                   2511:       $string =~ s/^&//;
                   2512: 
                   2513:       $hash{$key}=$value;
1.204     albertel 2514:   }
1.265     albertel 2515: 
                   2516:   $string =~ s/^__END_HASH_REF__//;
                   2517: 
                   2518:   return (\%hash, $string);
1.204     albertel 2519: }
                   2520: 
                   2521: sub str2array {
1.265     albertel 2522:     my ($string)=@_;
                   2523:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2524:     return @$array;
                   2525: }
                   2526: 
                   2527: sub str2arrayref {
1.204     albertel 2528:   my ($string) = @_;
1.265     albertel 2529:   my @array;
                   2530: 
                   2531:   if($string !~ /^__ARRAY_REF__/) {
                   2532:       if (! ($string eq '' || !defined($string))) {
                   2533: 	  $array[0]='Array reference error';
                   2534:       }
                   2535:       return (\@array, $string);
                   2536:   }
                   2537: 
                   2538:   $string =~ s/^__ARRAY_REF__//;
                   2539: 
                   2540:   while($string !~ /^__END_ARRAY_REF__/) {
                   2541:       my $value='';
                   2542:       if($string =~ /^__HASH_REF__/) {
                   2543:           ($value, $string)=&str2hashref($string);
                   2544:           if(defined($value->{'error'})) {
                   2545:               $array[0] ='Array reference error';
                   2546:               return (\@array, $string);
                   2547:           }
                   2548:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2549:           ($value, $string)=&str2arrayref($string);
                   2550:           if($value->[0] eq 'Array reference error') {
                   2551:               $array[0] ='Array reference error';
                   2552:               return (\@array, $string);
                   2553:           }
                   2554:       } else {
                   2555: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2556:       }
                   2557:       $string =~ s/^&//;
                   2558: 
                   2559:       push(@array, $value);
1.191     harris41 2560:   }
1.265     albertel 2561: 
                   2562:   $string =~ s/^__END_ARRAY_REF__//;
                   2563: 
                   2564:   return (\@array, $string);
1.168     albertel 2565: }
                   2566: 
1.167     albertel 2567: # -------------------------------------------------------------------Temp Store
                   2568: 
1.168     albertel 2569: sub tmpreset {
                   2570:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2571:   if (!$symb) {
                   2572:     $symb=&symbread();
1.620     albertel 2573:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2574:   }
                   2575:   $symb=escape($symb);
                   2576: 
1.620     albertel 2577:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2578:   $namespace=~s/\//\_/g;
                   2579:   $namespace=~s/\W//g;
                   2580: 
1.620     albertel 2581:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2582:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2583:   if ($domain eq 'public' && $stuname eq 'public') {
                   2584:       $stuname=$ENV{'REMOTE_ADDR'};
                   2585:   }
1.168     albertel 2586:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2587:   my %hash;
                   2588:   if (tie(%hash,'GDBM_File',
                   2589: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2590: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2591:     foreach my $key (keys %hash) {
1.180     albertel 2592:       if ($key=~ /:$symb/) {
1.168     albertel 2593: 	delete($hash{$key});
                   2594:       }
                   2595:     }
                   2596:   }
                   2597: }
                   2598: 
1.167     albertel 2599: sub tmpstore {
1.168     albertel 2600:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2601: 
                   2602:   if (!$symb) {
                   2603:     $symb=&symbread();
1.620     albertel 2604:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2605:   }
                   2606:   $symb=escape($symb);
                   2607: 
                   2608:   if (!$namespace) {
                   2609:     # I don't think we would ever want to store this for a course.
                   2610:     # it seems this will only be used if we don't have a course.
1.620     albertel 2611:     #$namespace=$env{'request.course.id'};
1.168     albertel 2612:     #if (!$namespace) {
1.620     albertel 2613:       $namespace=$env{'request.state'};
1.168     albertel 2614:     #}
                   2615:   }
                   2616:   $namespace=~s/\//\_/g;
                   2617:   $namespace=~s/\W//g;
1.620     albertel 2618:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2619:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2620:   if ($domain eq 'public' && $stuname eq 'public') {
                   2621:       $stuname=$ENV{'REMOTE_ADDR'};
                   2622:   }
1.168     albertel 2623:   my $now=time;
                   2624:   my %hash;
                   2625:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2626:   if (tie(%hash,'GDBM_File',
                   2627: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2628: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2629:     $hash{"version:$symb"}++;
                   2630:     my $version=$hash{"version:$symb"};
                   2631:     my $allkeys=''; 
                   2632:     foreach my $key (keys(%$storehash)) {
                   2633:       $allkeys.=$key.':';
1.591     albertel 2634:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2635:     }
                   2636:     $hash{"$version:$symb:timestamp"}=$now;
                   2637:     $allkeys.='timestamp';
                   2638:     $hash{"$version:keys:$symb"}=$allkeys;
                   2639:     if (untie(%hash)) {
                   2640:       return 'ok';
                   2641:     } else {
                   2642:       return "error:$!";
                   2643:     }
                   2644:   } else {
                   2645:     return "error:$!";
                   2646:   }
                   2647: }
1.167     albertel 2648: 
1.168     albertel 2649: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2650: 
1.168     albertel 2651: sub tmprestore {
                   2652:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2653: 
1.168     albertel 2654:   if (!$symb) {
                   2655:     $symb=&symbread();
1.620     albertel 2656:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2657:   }
                   2658:   $symb=escape($symb);
                   2659: 
1.620     albertel 2660:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2661: 
1.620     albertel 2662:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2663:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2664:   if ($domain eq 'public' && $stuname eq 'public') {
                   2665:       $stuname=$ENV{'REMOTE_ADDR'};
                   2666:   }
1.168     albertel 2667:   my %returnhash;
                   2668:   $namespace=~s/\//\_/g;
                   2669:   $namespace=~s/\W//g;
                   2670:   my %hash;
                   2671:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2672:   if (tie(%hash,'GDBM_File',
                   2673: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2674: 	  &GDBM_READER(),0640)) {
1.168     albertel 2675:     my $version=$hash{"version:$symb"};
                   2676:     $returnhash{'version'}=$version;
                   2677:     my $scope;
                   2678:     for ($scope=1;$scope<=$version;$scope++) {
                   2679:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2680:       my @keys=split(/:/,$vkeys);
                   2681:       my $key;
                   2682:       $returnhash{"$scope:keys"}=$vkeys;
                   2683:       foreach $key (@keys) {
1.591     albertel 2684: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2685: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2686:       }
                   2687:     }
1.168     albertel 2688:     if (!(untie(%hash))) {
                   2689:       return "error:$!";
                   2690:     }
                   2691:   } else {
                   2692:     return "error:$!";
                   2693:   }
                   2694:   return %returnhash;
1.167     albertel 2695: }
                   2696: 
1.9       www      2697: # ----------------------------------------------------------------------- Store
                   2698: 
                   2699: sub store {
1.124     www      2700:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2701:     my $home='';
                   2702: 
1.168     albertel 2703:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2704: 
1.213     www      2705:     $symb=&symbclean($symb);
1.122     albertel 2706:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2707: 
1.620     albertel 2708:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2709:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2710: 
                   2711:     &devalidate($symb,$stuname,$domain);
1.109     www      2712: 
                   2713:     $symb=escape($symb);
1.187     www      2714:     if (!$namespace) { 
1.620     albertel 2715:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2716:           return ''; 
                   2717:        } 
                   2718:     }
1.620     albertel 2719:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2720: 
                   2721:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2722:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2723: 
1.12      www      2724:     my $namevalue='';
1.800     albertel 2725:     foreach my $key (keys(%$storehash)) {
                   2726:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2727:     }
1.12      www      2728:     $namevalue=~s/\&$//;
1.187     www      2729:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2730:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2731: }
                   2732: 
1.47      www      2733: # -------------------------------------------------------------- Critical Store
                   2734: 
                   2735: sub cstore {
1.124     www      2736:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2737:     my $home='';
                   2738: 
1.168     albertel 2739:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2740: 
1.213     www      2741:     $symb=&symbclean($symb);
1.122     albertel 2742:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2743: 
1.620     albertel 2744:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2745:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2746: 
                   2747:     &devalidate($symb,$stuname,$domain);
1.109     www      2748: 
                   2749:     $symb=escape($symb);
1.187     www      2750:     if (!$namespace) { 
1.620     albertel 2751:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2752:           return ''; 
                   2753:        } 
                   2754:     }
1.620     albertel 2755:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2756: 
                   2757:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2758:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2759: 
1.47      www      2760:     my $namevalue='';
1.800     albertel 2761:     foreach my $key (keys(%$storehash)) {
                   2762:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2763:     }
1.47      www      2764:     $namevalue=~s/\&$//;
1.187     www      2765:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2766:     return critical
                   2767:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2768: }
                   2769: 
1.9       www      2770: # --------------------------------------------------------------------- Restore
                   2771: 
                   2772: sub restore {
1.124     www      2773:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2774:     my $home='';
                   2775: 
1.168     albertel 2776:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2777: 
1.122     albertel 2778:     if (!$symb) {
                   2779:       unless ($symb=escape(&symbread())) { return ''; }
                   2780:     } else {
1.213     www      2781:       $symb=&escape(&symbclean($symb));
1.122     albertel 2782:     }
1.188     www      2783:     if (!$namespace) { 
1.620     albertel 2784:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2785:           return ''; 
                   2786:        } 
                   2787:     }
1.620     albertel 2788:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2789:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2790:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2791:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2792: 
1.12      www      2793:     my %returnhash=();
1.800     albertel 2794:     foreach my $line (split(/\&/,$answer)) {
                   2795: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2796:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2797:     }
1.75      www      2798:     my $version;
                   2799:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2800:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2801:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2802:        }
1.75      www      2803:     }
1.13      www      2804:     return %returnhash;
1.34      www      2805: }
                   2806: 
                   2807: # ---------------------------------------------------------- Course Description
                   2808: 
                   2809: sub coursedescription {
1.731     albertel 2810:     my ($courseid,$args)=@_;
1.34      www      2811:     $courseid=~s/^\///;
1.49      www      2812:     $courseid=~s/\_/\//g;
1.34      www      2813:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2814:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2815:     my $normalid=$cdomain.'_'.$cnum;
                   2816:     # need to always cache even if we get errors otherwise we keep 
                   2817:     # trying and trying and trying to get the course description.
                   2818:     my %envhash=();
                   2819:     my %returnhash=();
1.731     albertel 2820:     
                   2821:     my $expiretime=600;
                   2822:     if ($env{'request.course.id'} eq $normalid) {
                   2823: 	$expiretime=120;
                   2824:     }
                   2825: 
                   2826:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2827:     if (!$args->{'freshen_cache'}
                   2828: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2829: 	foreach my $key (keys(%env)) {
                   2830: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2831: 	    my ($setting) = $1;
                   2832: 	    $returnhash{$setting} = $env{$key};
                   2833: 	}
                   2834: 	return %returnhash;
                   2835:     }
                   2836: 
                   2837:     # get the data agin
                   2838:     if (!$args->{'one_time'}) {
                   2839: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2840:     }
1.811     albertel 2841: 
1.34      www      2842:     if ($chome ne 'no_host') {
1.302     albertel 2843:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2844:        if (!exists($returnhash{'con_lost'})) {
                   2845:            $returnhash{'home'}= $chome;
                   2846: 	   $returnhash{'domain'} = $cdomain;
                   2847: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2848:            if (!defined($returnhash{'type'})) {
                   2849:                $returnhash{'type'} = 'Course';
                   2850:            }
1.130     albertel 2851:            while (my ($name,$value) = each %returnhash) {
1.53      www      2852:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2853:            }
1.270     www      2854:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2855:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2856: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2857:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2858:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2859:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2860:        }
                   2861:     }
1.731     albertel 2862:     if (!$args->{'one_time'}) {
                   2863: 	&appenv(%envhash);
                   2864:     }
1.302     albertel 2865:     return %returnhash;
1.461     www      2866: }
                   2867: 
                   2868: # -------------------------------------------------See if a user is privileged
                   2869: 
                   2870: sub privileged {
                   2871:     my ($username,$domain)=@_;
                   2872:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2873: 			&homeserver($username,$domain));
                   2874:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2875:     my $now=time;
                   2876:     if ($rolesdump ne '') {
1.800     albertel 2877:         foreach my $entry (split(/&/,$rolesdump)) {
                   2878: 	    if ($entry!~/^rolesdef_/) {
                   2879: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2880: 		$area=~s/\_\w\w$//;
                   2881: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2882: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2883: 		    my $active=1;
                   2884: 		    if ($tend) {
                   2885: 			if ($tend<$now) { $active=0; }
                   2886: 		    }
                   2887: 		    if ($tstart) {
                   2888: 			if ($tstart>$now) { $active=0; }
                   2889: 		    }
                   2890: 		    if ($active) { return 1; }
                   2891: 		}
                   2892: 	    }
                   2893: 	}
                   2894:     }
                   2895:     return 0;
1.9       www      2896: }
1.1       albertel 2897: 
1.103     harris41 2898: # -------------------------------------------------------- Get user privileges
1.11      www      2899: 
                   2900: sub rolesinit {
                   2901:     my ($domain,$username,$authhost)=@_;
                   2902:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2903:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2904:     my %allroles=();
1.678     raeburn  2905:     my %allgroups=();   
1.11      www      2906:     my $now=time;
1.743     albertel 2907:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2908:     my $group_privs;
1.11      www      2909: 
                   2910:     if ($rolesdump ne '') {
1.800     albertel 2911:         foreach my $entry (split(/&/,$rolesdump)) {
                   2912: 	  if ($entry!~/^rolesdef_/) {
                   2913:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2914: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2915:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2916: 	    if ($role=~/^cr/) { 
1.807     albertel 2917: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2918: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2919: 		    ($tend,$tstart)=split('_',$trest);
                   2920: 		} else {
                   2921: 		    $trole=$role;
                   2922: 		}
1.678     raeburn  2923:             } elsif ($role =~ m|^gr/|) {
                   2924:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2925:                 ($trole,$group_privs) = split(/\//,$trole);
                   2926:                 $group_privs = &unescape($group_privs);
1.587     albertel 2927: 	    } else {
                   2928: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2929: 	    }
1.743     albertel 2930: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2931: 					 $username);
                   2932: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2933:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2934:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2935:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2936: 		my $spec=$trole.'.'.$area;
                   2937: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2938: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2939:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2940:                 } elsif ($trole eq 'gr') {
                   2941:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2942: 		} else {
1.567     raeburn  2943:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2944: 		}
1.12      www      2945:             }
1.662     raeburn  2946:           }
1.191     harris41 2947:         }
1.743     albertel 2948:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2949:         $userroles{'user.adv'}    = $adv;
                   2950: 	$userroles{'user.author'} = $author;
1.620     albertel 2951:         $env{'user.adv'}=$adv;
1.11      www      2952:     }
1.743     albertel 2953:     return \%userroles;  
1.11      www      2954: }
                   2955: 
1.567     raeburn  2956: sub set_arearole {
                   2957:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2958: # log the associated role with the area
                   2959:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2960:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2961: }
                   2962: 
                   2963: sub custom_roleprivs {
                   2964:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2965:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2966:     my $homsvr=homeserver($rauthor,$rdomain);
                   2967:     if ($hostname{$homsvr} ne '') {
                   2968:         my ($rdummy,$roledef)=
                   2969:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2970:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2971:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2972:             if (defined($syspriv)) {
                   2973:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2974:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2975:             }
                   2976:             if ($tdomain ne '') {
                   2977:                 if (defined($dompriv)) {
                   2978:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2979:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2980:                 }
                   2981:                 if (($trest ne '') && (defined($coursepriv))) {
                   2982:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2983:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2984:                 }
                   2985:             }
                   2986:         }
                   2987:     }
                   2988: }
                   2989: 
1.678     raeburn  2990: sub group_roleprivs {
                   2991:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2992:     my $access = 1;
                   2993:     my $now = time;
                   2994:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2995:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2996:     if ($access) {
1.811     albertel 2997:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2998:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2999:     }
                   3000: }
1.567     raeburn  3001: 
                   3002: sub standard_roleprivs {
                   3003:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3004:     if (defined($pr{$trole.':s'})) {
                   3005:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3006:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3007:     }
                   3008:     if ($tdomain ne '') {
                   3009:         if (defined($pr{$trole.':d'})) {
                   3010:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3011:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3012:         }
                   3013:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3014:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3015:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3016:         }
                   3017:     }
                   3018: }
                   3019: 
                   3020: sub set_userprivs {
1.678     raeburn  3021:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3022:     my $author=0;
                   3023:     my $adv=0;
1.678     raeburn  3024:     my %grouproles = ();
                   3025:     if (keys(%{$allgroups}) > 0) {
                   3026:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3027:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3028:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3029:                 $trole = $1;
                   3030:                 $area = $2;
1.681     raeburn  3031:                 $sec = $3;
                   3032:                 $extendedarea = $area.$sec;
                   3033:                 if (exists($$allgroups{$area})) {
                   3034:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3035:                         my $spec = $trole.'.'.$extendedarea;
                   3036:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3037:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3038:                     }
                   3039:                 }
                   3040:             }
                   3041:         }
                   3042:     }
1.800     albertel 3043:     foreach my $group (keys(%grouproles)) {
                   3044:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3045:     }
1.800     albertel 3046:     foreach my $role (keys(%{$allroles})) {
                   3047:         my %thesepriv;
                   3048:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3049:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3050:             if ($item ne '') {
                   3051:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3052:                 if ($restrictions eq '') {
                   3053:                     $thesepriv{$privilege}='F';
                   3054:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3055:                     $thesepriv{$privilege}.=$restrictions;
                   3056:                 }
                   3057:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3058:             }
                   3059:         }
                   3060:         my $thesestr='';
1.800     albertel 3061:         foreach my $priv (keys(%thesepriv)) {
                   3062: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3063: 	}
                   3064:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3065:     }
                   3066:     return ($author,$adv);
                   3067: }
                   3068: 
1.12      www      3069: # --------------------------------------------------------------- get interface
                   3070: 
                   3071: sub get {
1.131     albertel 3072:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3073:    my $items='';
1.800     albertel 3074:    foreach my $item (@$storearr) {
                   3075:        $items.=&escape($item).'&';
1.191     harris41 3076:    }
1.12      www      3077:    $items=~s/\&$//;
1.620     albertel 3078:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3079:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3080:    my $uhome=&homeserver($uname,$udomain);
                   3081: 
1.133     albertel 3082:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3083:    my @pairs=split(/\&/,$rep);
1.273     albertel 3084:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3085:      return @pairs;
                   3086:    }
1.15      www      3087:    my %returnhash=();
1.42      www      3088:    my $i=0;
1.800     albertel 3089:    foreach my $item (@$storearr) {
                   3090:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3091:       $i++;
1.191     harris41 3092:    }
1.15      www      3093:    return %returnhash;
1.27      www      3094: }
                   3095: 
                   3096: # --------------------------------------------------------------- del interface
                   3097: 
                   3098: sub del {
1.133     albertel 3099:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3100:    my $items='';
1.800     albertel 3101:    foreach my $item (@$storearr) {
                   3102:        $items.=&escape($item).'&';
1.191     harris41 3103:    }
1.27      www      3104:    $items=~s/\&$//;
1.620     albertel 3105:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3106:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3107:    my $uhome=&homeserver($uname,$udomain);
                   3108: 
                   3109:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3110: }
                   3111: 
                   3112: # -------------------------------------------------------------- dump interface
                   3113: 
                   3114: sub dump {
1.755     albertel 3115:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3116:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3117:     if (!$uname) { $uname=$env{'user.name'}; }
                   3118:     my $uhome=&homeserver($uname,$udomain);
                   3119:     if ($regexp) {
                   3120: 	$regexp=&escape($regexp);
                   3121:     } else {
                   3122: 	$regexp='.';
                   3123:     }
                   3124:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3125:     my @pairs=split(/\&/,$rep);
                   3126:     my %returnhash=();
                   3127:     foreach my $item (@pairs) {
                   3128: 	my ($key,$value)=split(/=/,$item,2);
                   3129: 	$key = &unescape($key);
                   3130: 	next if ($key =~ /^error: 2 /);
                   3131: 	$returnhash{$key}=&thaw_unescape($value);
                   3132:     }
                   3133:     return %returnhash;
1.407     www      3134: }
                   3135: 
1.717     albertel 3136: # --------------------------------------------------------- dumpstore interface
                   3137: 
                   3138: sub dumpstore {
                   3139:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3140:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3141:    if (!$uname) { $uname=$env{'user.name'}; }
                   3142:    my $uhome=&homeserver($uname,$udomain);
                   3143:    if ($regexp) {
                   3144:        $regexp=&escape($regexp);
                   3145:    } else {
                   3146:        $regexp='.';
                   3147:    }
                   3148:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3149:    my @pairs=split(/\&/,$rep);
                   3150:    my %returnhash=();
                   3151:    foreach my $item (@pairs) {
                   3152:        my ($key,$value)=split(/=/,$item,2);
                   3153:        next if ($key =~ /^error: 2 /);
                   3154:        $returnhash{$key}=&thaw_unescape($value);
                   3155:    }
                   3156:    return %returnhash;
1.717     albertel 3157: }
                   3158: 
1.407     www      3159: # -------------------------------------------------------------- keys interface
                   3160: 
                   3161: sub getkeys {
                   3162:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3163:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3164:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3165:    my $uhome=&homeserver($uname,$udomain);
                   3166:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3167:    my @keyarray=();
1.800     albertel 3168:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3169:       next if ($key =~ /^error: 2 /);
1.800     albertel 3170:       push(@keyarray,&unescape($key));
1.407     www      3171:    }
                   3172:    return @keyarray;
1.318     matthew  3173: }
                   3174: 
1.319     matthew  3175: # --------------------------------------------------------------- currentdump
                   3176: sub currentdump {
1.328     matthew  3177:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3178:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3179:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3180:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3181:    my $uhome = &homeserver($sname,$sdom);
                   3182:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3183:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3184:    #
1.318     matthew  3185:    my %returnhash=();
1.319     matthew  3186:    #
                   3187:    if ($rep eq "unknown_cmd") { 
                   3188:        # an old lond will not know currentdump
                   3189:        # Do a dump and make it look like a currentdump
1.822     albertel 3190:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3191:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3192:        my %hash = @tmp;
                   3193:        @tmp=();
1.424     matthew  3194:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3195:    } else {
                   3196:        my @pairs=split(/\&/,$rep);
1.800     albertel 3197:        foreach my $pair (@pairs) {
                   3198:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3199:            my ($symb,$param) = split(/:/,$key);
                   3200:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3201:                                                         &thaw_unescape($value);
1.319     matthew  3202:        }
1.191     harris41 3203:    }
1.12      www      3204:    return %returnhash;
1.424     matthew  3205: }
                   3206: 
                   3207: sub convert_dump_to_currentdump{
                   3208:     my %hash = %{shift()};
                   3209:     my %returnhash;
                   3210:     # Code ripped from lond, essentially.  The only difference
                   3211:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3212:     # we might run in to problems with parameter names =~ /^v\./
                   3213:     while (my ($key,$value) = each(%hash)) {
                   3214:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3215: 	$symb  = &unescape($symb);
                   3216: 	$param = &unescape($param);
1.424     matthew  3217:         next if ($v eq 'version' || $symb eq 'keys');
                   3218:         next if (exists($returnhash{$symb}) &&
                   3219:                  exists($returnhash{$symb}->{$param}) &&
                   3220:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3221:         $returnhash{$symb}->{$param}=$value;
                   3222:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3223:     }
                   3224:     #
                   3225:     # Remove all of the keys in the hashes which keep track of
                   3226:     # the version of the parameter.
                   3227:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3228:         # use a foreach because we are going to delete from the hash.
                   3229:         foreach my $key (keys(%$param_hash)) {
                   3230:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3231:         }
                   3232:     }
                   3233:     return \%returnhash;
1.12      www      3234: }
                   3235: 
1.627     albertel 3236: # ------------------------------------------------------ critical inc interface
                   3237: 
                   3238: sub cinc {
                   3239:     return &inc(@_,'critical');
                   3240: }
                   3241: 
1.449     matthew  3242: # --------------------------------------------------------------- inc interface
                   3243: 
                   3244: sub inc {
1.627     albertel 3245:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3246:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3247:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3248:     my $uhome=&homeserver($uname,$udomain);
                   3249:     my $items='';
                   3250:     if (! ref($store)) {
                   3251:         # got a single value, so use that instead
                   3252:         $items = &escape($store).'=&';
                   3253:     } elsif (ref($store) eq 'SCALAR') {
                   3254:         $items = &escape($$store).'=&';        
                   3255:     } elsif (ref($store) eq 'ARRAY') {
                   3256:         $items = join('=&',map {&escape($_);} @{$store});
                   3257:     } elsif (ref($store) eq 'HASH') {
                   3258:         while (my($key,$value) = each(%{$store})) {
                   3259:             $items.= &escape($key).'='.&escape($value).'&';
                   3260:         }
                   3261:     }
                   3262:     $items=~s/\&$//;
1.627     albertel 3263:     if ($critical) {
                   3264: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3265:     } else {
                   3266: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3267:     }
1.449     matthew  3268: }
                   3269: 
1.12      www      3270: # --------------------------------------------------------------- put interface
                   3271: 
                   3272: sub put {
1.134     albertel 3273:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3274:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3275:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3276:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3277:    my $items='';
1.800     albertel 3278:    foreach my $item (keys(%$storehash)) {
                   3279:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3280:    }
1.12      www      3281:    $items=~s/\&$//;
1.134     albertel 3282:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3283: }
                   3284: 
1.631     albertel 3285: # ------------------------------------------------------------ newput interface
                   3286: 
                   3287: sub newput {
                   3288:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3289:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3290:    if (!$uname) { $uname=$env{'user.name'}; }
                   3291:    my $uhome=&homeserver($uname,$udomain);
                   3292:    my $items='';
                   3293:    foreach my $key (keys(%$storehash)) {
                   3294:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3295:    }
                   3296:    $items=~s/\&$//;
                   3297:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3298: }
                   3299: 
                   3300: # ---------------------------------------------------------  putstore interface
                   3301: 
1.524     raeburn  3302: sub putstore {
1.715     albertel 3303:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3304:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3305:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3306:    my $uhome=&homeserver($uname,$udomain);
                   3307:    my $items='';
1.715     albertel 3308:    foreach my $key (keys(%$storehash)) {
                   3309:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3310:    }
1.715     albertel 3311:    $items=~s/\&$//;
1.716     albertel 3312:    my $esc_symb=&escape($symb);
                   3313:    my $esc_v=&escape($version);
1.715     albertel 3314:    my $reply =
1.716     albertel 3315:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3316: 	      $uhome);
                   3317:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3318:        # gfall back to way things use to be done
1.715     albertel 3319:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3320: 			    $uname);
1.524     raeburn  3321:    }
1.715     albertel 3322:    return $reply;
                   3323: }
                   3324: 
                   3325: sub old_putstore {
1.716     albertel 3326:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3327:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3328:     if (!$uname) { $uname=$env{'user.name'}; }
                   3329:     my $uhome=&homeserver($uname,$udomain);
                   3330:     my %newstorehash;
1.800     albertel 3331:     foreach my $item (keys(%$storehash)) {
                   3332: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3333: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3334:     }
                   3335:     my $items='';
                   3336:     my %allitems = ();
1.800     albertel 3337:     foreach my $item (keys(%newstorehash)) {
                   3338: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3339: 	    my $key = $1.':keys:'.$2;
                   3340: 	    $allitems{$key} .= $3.':';
                   3341: 	}
1.800     albertel 3342: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3343:     }
1.800     albertel 3344:     foreach my $item (keys(%allitems)) {
                   3345: 	$allitems{$item} =~ s/\:$//;
                   3346: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3347:     }
                   3348:     $items=~s/\&$//;
                   3349:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3350: }
                   3351: 
1.47      www      3352: # ------------------------------------------------------ critical put interface
                   3353: 
                   3354: sub cput {
1.134     albertel 3355:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3356:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3357:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3358:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3359:    my $items='';
1.800     albertel 3360:    foreach my $item (keys(%$storehash)) {
                   3361:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3362:    }
1.47      www      3363:    $items=~s/\&$//;
1.134     albertel 3364:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3365: }
                   3366: 
                   3367: # -------------------------------------------------------------- eget interface
                   3368: 
                   3369: sub eget {
1.133     albertel 3370:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3371:    my $items='';
1.800     albertel 3372:    foreach my $item (@$storearr) {
                   3373:        $items.=&escape($item).'&';
1.191     harris41 3374:    }
1.12      www      3375:    $items=~s/\&$//;
1.620     albertel 3376:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3377:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3378:    my $uhome=&homeserver($uname,$udomain);
                   3379:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3380:    my @pairs=split(/\&/,$rep);
                   3381:    my %returnhash=();
1.42      www      3382:    my $i=0;
1.800     albertel 3383:    foreach my $item (@$storearr) {
                   3384:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3385:       $i++;
1.191     harris41 3386:    }
1.12      www      3387:    return %returnhash;
                   3388: }
                   3389: 
1.667     albertel 3390: # ------------------------------------------------------------ tmpput interface
                   3391: sub tmpput {
1.802     raeburn  3392:     my ($storehash,$server,$context)=@_;
1.667     albertel 3393:     my $items='';
1.800     albertel 3394:     foreach my $item (keys(%$storehash)) {
                   3395: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3396:     }
                   3397:     $items=~s/\&$//;
1.802     raeburn  3398:     if (defined($context)) {
                   3399:         $items .= ':'.&escape($context);
                   3400:     }
1.667     albertel 3401:     return &reply("tmpput:$items",$server);
                   3402: }
                   3403: 
                   3404: # ------------------------------------------------------------ tmpget interface
                   3405: sub tmpget {
1.688     albertel 3406:     my ($token,$server)=@_;
                   3407:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3408:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3409:     my %returnhash;
                   3410:     foreach my $item (split(/\&/,$rep)) {
                   3411: 	my ($key,$value)=split(/=/,$item);
                   3412: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3413:     }
                   3414:     return %returnhash;
                   3415: }
                   3416: 
1.688     albertel 3417: # ------------------------------------------------------------ tmpget interface
                   3418: sub tmpdel {
                   3419:     my ($token,$server)=@_;
                   3420:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3421:     return &reply("tmpdel:$token",$server);
                   3422: }
                   3423: 
1.765     albertel 3424: # -------------------------------------------------- portfolio access checking
                   3425: 
                   3426: sub portfolio_access {
1.766     albertel 3427:     my ($requrl) = @_;
1.765     albertel 3428:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3429:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3430:     if ($result) {
                   3431:         my %setters;
                   3432:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3433:             my ($startblock,$endblock) =
                   3434:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3435:             if ($startblock && $endblock) {
                   3436:                 return 'B';
                   3437:             }
                   3438:         } else {
                   3439:             my ($startblock,$endblock) =
                   3440:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3441:             if ($startblock && $endblock) {
                   3442:                 return 'B';
                   3443:             }
                   3444:         }
                   3445:     }
1.765     albertel 3446:     if ($result eq 'ok') {
1.766     albertel 3447:        return 'F';
1.765     albertel 3448:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3449:        return 'A';
1.765     albertel 3450:     }
1.766     albertel 3451:     return '';
1.765     albertel 3452: }
                   3453: 
                   3454: sub get_portfolio_access {
1.767     albertel 3455:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3456: 
                   3457:     if (!ref($access_hash)) {
                   3458: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3459: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3460: 						   $file_name);
                   3461: 	$access_hash = $access_controls{$file_name};
                   3462:     }
                   3463: 
1.765     albertel 3464:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3465:     my $now = time;
                   3466:     if (ref($access_hash) eq 'HASH') {
                   3467:         foreach my $key (keys(%{$access_hash})) {
                   3468:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3469:             if ($start > $now) {
                   3470:                 next;
                   3471:             }
                   3472:             if ($end && $end<$now) {
                   3473:                 next;
                   3474:             }
                   3475:             if ($scope eq 'public') {
                   3476:                 $public = $key;
                   3477:                 last;
                   3478:             } elsif ($scope eq 'guest') {
                   3479:                 $guest = $key;
                   3480:             } elsif ($scope eq 'domains') {
                   3481:                 push(@domains,$key);
                   3482:             } elsif ($scope eq 'users') {
                   3483:                 push(@users,$key);
                   3484:             } elsif ($scope eq 'course') {
                   3485:                 push(@courses,$key);
                   3486:             } elsif ($scope eq 'group') {
                   3487:                 push(@groups,$key);
                   3488:             }
                   3489:         }
                   3490:         if ($public) {
                   3491:             return 'ok';
                   3492:         }
                   3493:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3494:             if ($guest) {
                   3495:                 return $guest;
                   3496:             }
                   3497:         } else {
                   3498:             if (@domains > 0) {
                   3499:                 foreach my $domkey (@domains) {
                   3500:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3501:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3502:                             return 'ok';
                   3503:                         }
                   3504:                     }
                   3505:                 }
                   3506:             }
                   3507:             if (@users > 0) {
                   3508:                 foreach my $userkey (@users) {
                   3509:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3510:                         return 'ok';
                   3511:                     }
                   3512:                 }
                   3513:             }
                   3514:             my %roleshash;
                   3515:             my @courses_and_groups = @courses;
                   3516:             push(@courses_and_groups,@groups); 
                   3517:             if (@courses_and_groups > 0) {
                   3518:                 my (%allgroups,%allroles); 
                   3519:                 my ($start,$end,$role,$sec,$group);
                   3520:                 foreach my $envkey (%env) {
1.811     albertel 3521:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3522:                         my $cid = $2.'_'.$3; 
                   3523:                         if ($1 eq 'gr') {
                   3524:                             $group = $4;
                   3525:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3526:                         } else {
                   3527:                             if ($4 eq '') {
                   3528:                                 $sec = 'none';
                   3529:                             } else {
                   3530:                                 $sec = $4;
                   3531:                             }
                   3532:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3533:                         }
1.811     albertel 3534:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3535:                         my $cid = $2.'_'.$3;
                   3536:                         if ($4 eq '') {
                   3537:                             $sec = 'none';
                   3538:                         } else {
                   3539:                             $sec = $4;
                   3540:                         }
                   3541:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3542:                     }
                   3543:                 }
                   3544:                 if (keys(%allroles) == 0) {
                   3545:                     return;
                   3546:                 }
                   3547:                 foreach my $key (@courses_and_groups) {
                   3548:                     my %content = %{$$access_hash{$key}};
                   3549:                     my $cnum = $content{'number'};
                   3550:                     my $cdom = $content{'domain'};
                   3551:                     my $cid = $cdom.'_'.$cnum;
                   3552:                     if (!exists($allroles{$cid})) {
                   3553:                         next;
                   3554:                     }    
                   3555:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3556:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3557:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3558:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3559:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3560:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3561:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3562:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3563:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3564:                                         if (grep/^all$/,@sections) {
                   3565:                                             return 'ok';
                   3566:                                         } else {
                   3567:                                             if (grep/^$sec$/,@sections) {
                   3568:                                                 return 'ok';
                   3569:                                             }
                   3570:                                         }
                   3571:                                     }
                   3572:                                 }
                   3573:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3574:                                     if (grep/^none$/,@groups) {
                   3575:                                         return 'ok';
                   3576:                                     }
                   3577:                                 } else {
                   3578:                                     if (grep/^all$/,@groups) {
                   3579:                                         return 'ok';
                   3580:                                     } 
                   3581:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3582:                                         if (grep/^$group$/,@groups) {
                   3583:                                             return 'ok';
                   3584:                                         }
                   3585:                                     }
                   3586:                                 } 
                   3587:                             }
                   3588:                         }
                   3589:                     }
                   3590:                 }
                   3591:             }
                   3592:             if ($guest) {
                   3593:                 return $guest;
                   3594:             }
                   3595:         }
                   3596:     }
                   3597:     return;
                   3598: }
                   3599: 
                   3600: sub course_group_datechecker {
                   3601:     my ($dates,$now,$status) = @_;
                   3602:     my ($start,$end) = split(/\./,$dates);
                   3603:     if (!$start && !$end) {
                   3604:         return 'ok';
                   3605:     }
                   3606:     if (grep/^active$/,@{$status}) {
                   3607:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3608:             return 'ok';
                   3609:         }
                   3610:     }
                   3611:     if (grep/^previous$/,@{$status}) {
                   3612:         if ($end > $now ) {
                   3613:             return 'ok';
                   3614:         }
                   3615:     }
                   3616:     if (grep/^future$/,@{$status}) {
                   3617:         if ($start > $now) {
                   3618:             return 'ok';
                   3619:         }
                   3620:     }
                   3621:     return; 
                   3622: }
                   3623: 
                   3624: sub parse_portfolio_url {
                   3625:     my ($url) = @_;
                   3626: 
                   3627:     my ($type,$udom,$unum,$group,$file_name);
                   3628:     
1.823     albertel 3629:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3630: 	$type = 1;
                   3631:         $udom = $1;
                   3632:         $unum = $2;
                   3633:         $file_name = $3;
1.823     albertel 3634:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3635: 	$type = 2;
                   3636:         $udom = $1;
                   3637:         $unum = $2;
                   3638:         $group = $3;
                   3639:         $file_name = $3.'/'.$4;
                   3640:     }
                   3641:     if (wantarray) {
                   3642: 	return ($type,$udom,$unum,$file_name,$group);
                   3643:     }
                   3644:     return $type;
                   3645: }
                   3646: 
                   3647: sub is_portfolio_url {
                   3648:     my ($url) = @_;
                   3649:     return scalar(&parse_portfolio_url($url));
                   3650: }
                   3651: 
1.798     raeburn  3652: sub is_portfolio_file {
                   3653:     my ($file) = @_;
1.820     raeburn  3654:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3655:         return 1;
                   3656:     }
                   3657:     return;
                   3658: }
                   3659: 
                   3660: 
1.341     www      3661: # ---------------------------------------------- Custom access rule evaluation
                   3662: 
                   3663: sub customaccess {
                   3664:     my ($priv,$uri)=@_;
1.807     albertel 3665:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3666:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3667:     $udom = &LONCAPA::clean_domain($udom);
                   3668:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3669:     my $access=0;
1.800     albertel 3670:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3671: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3672:         if ($role) {
                   3673: 	   if ($role ne $urole) { next; }
                   3674:         }
1.800     albertel 3675:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3676:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3677:             if ($tdom) {
                   3678: 		if ($tdom ne $udom) { next; }
                   3679:             }
                   3680:             if ($tcrs) {
                   3681: 		if ($tcrs ne $ucrs) { next; }
                   3682:             }
                   3683:             if ($tsec) {
                   3684: 		if ($tsec ne $usec) { next; }
                   3685:             }
                   3686:             $access=($effect eq 'allow');
                   3687:             last;
1.342     www      3688:         }
1.402     bowersj2 3689: 	if ($realm eq '' && $role eq '') {
                   3690:             $access=($effect eq 'allow');
                   3691: 	}
1.341     www      3692:     }
                   3693:     return $access;
                   3694: }
                   3695: 
1.103     harris41 3696: # ------------------------------------------------- Check for a user privilege
1.12      www      3697: 
                   3698: sub allowed {
1.810     raeburn  3699:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3700:     my $ver_orguri=$uri;
1.439     www      3701:     $uri=&deversion($uri);
1.152     www      3702:     my $orguri=$uri;
1.52      www      3703:     $uri=&declutter($uri);
1.809     raeburn  3704: 
1.810     raeburn  3705:     if ($priv eq 'evb') {
                   3706: # Evade communication block restrictions for specified role in a course
                   3707:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3708:             return $1;
                   3709:         } else {
                   3710:             return;
                   3711:         }
                   3712:     }
                   3713: 
1.620     albertel 3714:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3715: # Free bre access to adm and meta resources
1.775     albertel 3716:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3717: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3718: 	&& ($priv eq 'bre')) {
1.14      www      3719: 	return 'F';
1.159     www      3720:     }
                   3721: 
1.545     banghart 3722: # Free bre access to user's own portfolio contents
1.714     raeburn  3723:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3724:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3725: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3726:         my %setters;
                   3727:         my ($startblock,$endblock) = 
                   3728:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3729:         if ($startblock && $endblock) {
                   3730:             return 'B';
                   3731:         } else {
                   3732:             return 'F';
                   3733:         }
1.545     banghart 3734:     }
                   3735: 
1.762     raeburn  3736: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3737:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3738:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3739:         if (exists($env{'request.course.id'})) {
                   3740:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3741:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3742:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3743:                 my $courseprivid=$env{'request.course.id'};
                   3744:                 $courseprivid=~s/\_/\//;
                   3745:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3746:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3747:                     return $1; 
1.762     raeburn  3748:                 } else {
                   3749:                     if ($env{'request.course.sec'}) {
                   3750:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3751:                     }
                   3752:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3753:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3754:                         return $2;
                   3755:                     }
1.714     raeburn  3756:                 }
                   3757:             }
                   3758:         }
                   3759:     }
                   3760: 
1.159     www      3761: # Free bre to public access
                   3762: 
                   3763:     if ($priv eq 'bre') {
1.238     www      3764:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3765: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3766:            return 'F'; 
                   3767:         }
1.238     www      3768:         if ($copyright eq 'priv') {
                   3769:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3770: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3771: 		return '';
                   3772:             }
                   3773:         }
                   3774:         if ($copyright eq 'domain') {
                   3775:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3776: 	    unless (($env{'user.domain'} eq $1) ||
                   3777:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3778: 		return '';
                   3779:             }
1.262     matthew  3780:         }
1.620     albertel 3781:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3782:             # Library role, so allow browsing of resources in this domain.
                   3783:             return 'F';
1.238     www      3784:         }
1.341     www      3785:         if ($copyright eq 'custom') {
                   3786: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3787:         }
1.14      www      3788:     }
1.264     matthew  3789:     # Domain coordinator is trying to create a course
1.620     albertel 3790:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3791:         # uri is the requested domain in this case.
                   3792:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3793:         # a role of dc for the domain in question.
1.620     albertel 3794:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3795:     }
1.29      www      3796: 
1.52      www      3797:     my $thisallowed='';
                   3798:     my $statecond=0;
                   3799:     my $courseprivid='';
                   3800: 
                   3801: # Course
                   3802: 
1.620     albertel 3803:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3804:        $thisallowed.=$1;
                   3805:     }
1.29      www      3806: 
1.52      www      3807: # Domain
                   3808: 
1.620     albertel 3809:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3810:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3811:        $thisallowed.=$1;
                   3812:     }
1.52      www      3813: 
                   3814: # Course: uri itself is a course
1.66      www      3815:     my $courseuri=$uri;
                   3816:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3817:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3818: 
1.620     albertel 3819:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3820:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3821:        $thisallowed.=$1;
                   3822:     }
1.29      www      3823: 
1.665     albertel 3824: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3825: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3826:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3827: 	$thisallowed='';
1.671     raeburn  3828:         my ($match)=&is_on_map($uri);
                   3829:         if ($match) {
                   3830:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3831:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3832:                 $thisallowed.=$1;
                   3833:             }
                   3834:         } else {
1.705     albertel 3835:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3836:             if ($refuri) {
                   3837:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3838:                     $thisallowed='F';
1.671     raeburn  3839:                 } else {
                   3840:                     $refuri=&declutter($refuri);
                   3841:                     my ($match) = &is_on_map($refuri);
                   3842:                     if ($match) {
                   3843:                         $thisallowed='F';
                   3844:                     }
1.669     raeburn  3845:                 }
1.671     raeburn  3846:             }
                   3847:         }
1.314     www      3848:     }
1.492     albertel 3849: 
1.766     albertel 3850:     if ($priv eq 'bre'
                   3851: 	&& $thisallowed ne 'F' 
                   3852: 	&& $thisallowed ne '2'
                   3853: 	&& &is_portfolio_url($uri)) {
                   3854: 	$thisallowed = &portfolio_access($uri);
                   3855:     }
                   3856:     
1.52      www      3857: # Full access at system, domain or course-wide level? Exit.
1.29      www      3858: 
                   3859:     if ($thisallowed=~/F/) {
                   3860: 	return 'F';
                   3861:     }
                   3862: 
1.52      www      3863: # If this is generating or modifying users, exit with special codes
1.29      www      3864: 
1.643     www      3865:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3866: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3867: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3868: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3869: 	    unless ($auname) { return $thisallowed; }
                   3870: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3871: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3872: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3873: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3874: 	}
1.52      www      3875: 	return $thisallowed;
                   3876:     }
                   3877: #
1.103     harris41 3878: # Gathered so far: system, domain and course wide privileges
1.52      www      3879: #
                   3880: # Course: See if uri or referer is an individual resource that is part of 
                   3881: # the course
                   3882: 
1.620     albertel 3883:     if ($env{'request.course.id'}) {
1.232     www      3884: 
1.620     albertel 3885:        $courseprivid=$env{'request.course.id'};
                   3886:        if ($env{'request.course.sec'}) {
                   3887:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3888:        }
                   3889:        $courseprivid=~s/\_/\//;
                   3890:        my $checkreferer=1;
1.232     www      3891:        my ($match,$cond)=&is_on_map($uri);
                   3892:        if ($match) {
                   3893:            $statecond=$cond;
1.620     albertel 3894:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3895:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3896:                $thisallowed.=$1;
                   3897:                $checkreferer=0;
                   3898:            }
1.29      www      3899:        }
1.83      www      3900:        
1.148     www      3901:        if ($checkreferer) {
1.620     albertel 3902: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3903:             unless ($refuri) {
1.800     albertel 3904:                 foreach my $key (keys(%env)) {
                   3905: 		    if ($key=~/^httpref\..*\*/) {
                   3906: 			my $pattern=$key;
1.156     www      3907:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3908:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3909:                         $pattern=~s/\//\\\//g;
1.152     www      3910:                         if ($orguri=~/$pattern/) {
1.800     albertel 3911: 			    $refuri=$env{$key};
1.148     www      3912:                         }
                   3913:                     }
1.191     harris41 3914:                 }
1.148     www      3915:             }
1.232     www      3916: 
1.148     www      3917:          if ($refuri) { 
1.152     www      3918: 	  $refuri=&declutter($refuri);
1.232     www      3919:           my ($match,$cond)=&is_on_map($refuri);
                   3920:             if ($match) {
                   3921:               my $refstatecond=$cond;
1.620     albertel 3922:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3923:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3924:                   $thisallowed.=$1;
1.53      www      3925:                   $uri=$refuri;
                   3926:                   $statecond=$refstatecond;
1.52      www      3927:               }
                   3928:           }
1.148     www      3929:         }
1.29      www      3930:        }
1.52      www      3931:    }
1.29      www      3932: 
1.52      www      3933: #
1.103     harris41 3934: # Gathered now: all privileges that could apply, and condition number
1.52      www      3935: # 
                   3936: #
                   3937: # Full or no access?
                   3938: #
1.29      www      3939: 
1.52      www      3940:     if ($thisallowed=~/F/) {
                   3941: 	return 'F';
                   3942:     }
1.29      www      3943: 
1.52      www      3944:     unless ($thisallowed) {
                   3945:         return '';
                   3946:     }
1.29      www      3947: 
1.52      www      3948: # Restrictions exist, deal with them
                   3949: #
                   3950: #   C:according to course preferences
                   3951: #   R:according to resource settings
                   3952: #   L:unless locked
                   3953: #   X:according to user session state
                   3954: #
                   3955: 
                   3956: # Possibly locked functionality, check all courses
1.54      www      3957: # Locks might take effect only after 10 minutes cache expiration for other
                   3958: # courses, and 2 minutes for current course
1.52      www      3959: 
                   3960:     my $envkey;
                   3961:     if ($thisallowed=~/L/) {
1.620     albertel 3962:         foreach $envkey (keys %env) {
1.54      www      3963:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3964:                my $courseid=$2;
                   3965:                my $roleid=$1.'.'.$2;
1.92      www      3966:                $courseid=~s/^\///;
1.54      www      3967:                my $expiretime=600;
1.620     albertel 3968:                if ($env{'request.role'} eq $roleid) {
1.54      www      3969: 		  $expiretime=120;
                   3970:                }
                   3971: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3972:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3973:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3974: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3975:                }
1.620     albertel 3976:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3977:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3978: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3979:                        &log($env{'user.domain'},$env{'user.name'},
                   3980:                             $env{'user.home'},
1.57      www      3981:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3982:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3983:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3984: 		       return '';
                   3985:                    }
                   3986:                }
1.620     albertel 3987:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3988:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3989: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3990:                        &log($env{'user.domain'},$env{'user.name'},
                   3991:                             $env{'user.home'},
1.57      www      3992:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3993:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3994:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3995: 		       return '';
                   3996:                    }
                   3997:                }
                   3998: 	   }
1.29      www      3999:        }
1.52      www      4000:     }
                   4001:    
                   4002: #
                   4003: # Rest of the restrictions depend on selected course
                   4004: #
                   4005: 
1.620     albertel 4006:     unless ($env{'request.course.id'}) {
1.766     albertel 4007: 	if ($thisallowed eq 'A') {
                   4008: 	    return 'A';
1.814     raeburn  4009:         } elsif ($thisallowed eq 'B') {
                   4010:             return 'B';
1.766     albertel 4011: 	} else {
                   4012: 	    return '1';
                   4013: 	}
1.52      www      4014:     }
1.29      www      4015: 
1.52      www      4016: #
                   4017: # Now user is definitely in a course
                   4018: #
1.53      www      4019: 
                   4020: 
                   4021: # Course preferences
                   4022: 
                   4023:    if ($thisallowed=~/C/) {
1.620     albertel 4024:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4025:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4026:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4027: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4028: 	   if ($priv ne 'pch') { 
                   4029: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4030: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4031: 			$env{'request.course.id'});
                   4032: 	   }
1.237     www      4033:            return '';
                   4034:        }
                   4035: 
1.620     albertel 4036:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4037: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4038: 	   if ($priv ne 'pch') { 
                   4039: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4040: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4041: 			$env{'request.course.id'});
                   4042: 	   }
1.54      www      4043:            return '';
                   4044:        }
1.53      www      4045:    }
                   4046: 
                   4047: # Resource preferences
                   4048: 
                   4049:    if ($thisallowed=~/R/) {
1.620     albertel 4050:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4051:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4052: 	   if ($priv ne 'pch') { 
                   4053: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4054: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4055: 	   }
                   4056: 	   return '';
1.54      www      4057:        }
1.53      www      4058:    }
1.30      www      4059: 
1.246     www      4060: # Restricted by state or randomout?
1.30      www      4061: 
1.52      www      4062:    if ($thisallowed=~/X/) {
1.620     albertel 4063:       if ($env{'acc.randomout'}) {
1.579     albertel 4064: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4065:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4066:             return ''; 
                   4067:          }
1.247     www      4068:       }
                   4069:       if (&condval($statecond)) {
1.52      www      4070: 	 return '2';
                   4071:       } else {
                   4072:          return '';
                   4073:       }
                   4074:    }
1.30      www      4075: 
1.766     albertel 4076:     if ($thisallowed eq 'A') {
                   4077: 	return 'A';
1.814     raeburn  4078:     } elsif ($thisallowed eq 'B') {
                   4079:         return 'B';
1.766     albertel 4080:     }
1.52      www      4081:    return 'F';
1.232     www      4082: }
                   4083: 
1.710     albertel 4084: sub split_uri_for_cond {
                   4085:     my $uri=&deversion(&declutter(shift));
                   4086:     my @uriparts=split(/\//,$uri);
                   4087:     my $filename=pop(@uriparts);
                   4088:     my $pathname=join('/',@uriparts);
                   4089:     return ($pathname,$filename);
                   4090: }
1.232     www      4091: # --------------------------------------------------- Is a resource on the map?
                   4092: 
                   4093: sub is_on_map {
1.710     albertel 4094:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4095:     #Trying to find the conditional for the file
1.620     albertel 4096:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4097: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4098:     if ($match) {
1.289     bowersj2 4099: 	return (1,$1);
                   4100:     } else {
1.434     www      4101: 	return (0,0);
1.289     bowersj2 4102:     }
1.12      www      4103: }
                   4104: 
1.427     www      4105: # --------------------------------------------------------- Get symb from alias
                   4106: 
                   4107: sub get_symb_from_alias {
                   4108:     my $symb=shift;
                   4109:     my ($map,$resid,$url)=&decode_symb($symb);
                   4110: # Already is a symb
                   4111:     if ($url) { return $symb; }
                   4112: # Must be an alias
                   4113:     my $aliassymb='';
                   4114:     my %bighash;
1.620     albertel 4115:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4116:                             &GDBM_READER(),0640)) {
                   4117:         my $rid=$bighash{'mapalias_'.$symb};
                   4118: 	if ($rid) {
                   4119: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4120: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4121: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4122: 	}
                   4123:         untie %bighash;
                   4124:     }
                   4125:     return $aliassymb;
                   4126: }
                   4127: 
1.12      www      4128: # ----------------------------------------------------------------- Define Role
                   4129: 
                   4130: sub definerole {
                   4131:   if (allowed('mcr','/')) {
                   4132:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4133:     foreach my $role (split(':',$sysrole)) {
                   4134: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4135:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4136:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4137: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4138:                return "refused:s:$crole&$cqual"; 
                   4139:             }
                   4140:         }
1.191     harris41 4141:     }
1.800     albertel 4142:     foreach my $role (split(':',$domrole)) {
                   4143: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4144:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4145:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4146: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4147:                return "refused:d:$crole&$cqual"; 
                   4148:             }
                   4149:         }
1.191     harris41 4150:     }
1.800     albertel 4151:     foreach my $role (split(':',$courole)) {
                   4152: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4153:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4154:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4155: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4156:                return "refused:c:$crole&$cqual"; 
                   4157:             }
                   4158:         }
1.191     harris41 4159:     }
1.620     albertel 4160:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4161:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4162: 	        "rolesdef_$rolename=".
                   4163:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4164:     return reply($command,$env{'user.home'});
1.12      www      4165:   } else {
                   4166:     return 'refused';
                   4167:   }
1.105     harris41 4168: }
                   4169: 
                   4170: # ---------------- Make a metadata query against the network of library servers
                   4171: 
                   4172: sub metadata_query {
1.244     matthew  4173:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4174:     my %rhash;
1.244     matthew  4175:     my @server_list = (defined($server_array) ? @$server_array
                   4176:                                               : keys(%libserv) );
                   4177:     for my $server (@server_list) {
1.118     harris41 4178: 	unless ($custom or $customshow) {
                   4179: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4180: 	    $rhash{$server}=$reply;
                   4181: 	}
                   4182: 	else {
                   4183: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4184: 			     &escape($custom).':'.&escape($customshow),
                   4185: 			     $server);
                   4186: 	    $rhash{$server}=$reply;
                   4187: 	}
1.112     harris41 4188:     }
1.118     harris41 4189:     return \%rhash;
1.240     www      4190: }
                   4191: 
                   4192: # ----------------------------------------- Send log queries and wait for reply
                   4193: 
                   4194: sub log_query {
                   4195:     my ($uname,$udom,$query,%filters)=@_;
                   4196:     my $uhome=&homeserver($uname,$udom);
                   4197:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4198:     my $uhost=$hostname{$uhome};
1.800     albertel 4199:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4200:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4201:                        $uhome);
1.479     albertel 4202:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4203:     return get_query_reply($queryid);
                   4204: }
                   4205: 
1.818     raeburn  4206: # -------------------------- Update MySQL table for portfolio file
                   4207: 
                   4208: sub update_portfolio_table {
1.821     raeburn  4209:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4210:     my $homeserver = &homeserver($uname,$udom);
                   4211:     my $queryid=
1.821     raeburn  4212:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4213:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4214:     my $reply = &get_query_reply($queryid);
                   4215:     return $reply;
                   4216: }
                   4217: 
1.508     raeburn  4218: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4219: 
                   4220: sub fetch_enrollment_query {
1.511     raeburn  4221:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4222:     my $homeserver;
1.547     raeburn  4223:     my $maxtries = 1;
1.508     raeburn  4224:     if ($context eq 'automated') {
                   4225:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4226:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4227:     } else {
                   4228:         $homeserver = &homeserver($cnum,$dom);
                   4229:     }
1.506     raeburn  4230:     my $host=$hostname{$homeserver};
                   4231:     my $cmd = '';
1.800     albertel 4232:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4233:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4234:     }
                   4235:     $cmd =~ s/%%$//;
                   4236:     $cmd = &escape($cmd);
                   4237:     my $query = 'fetchenrollment';
1.620     albertel 4238:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4239:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4240:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4241:         return 'error: '.$queryid;
                   4242:     }
1.506     raeburn  4243:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4244:     my $tries = 1;
                   4245:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4246:         $reply = &get_query_reply($queryid);
                   4247:         $tries ++;
                   4248:     }
1.526     raeburn  4249:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4250:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4251:     } else {
1.515     raeburn  4252:         my @responses = split/:/,$reply;
                   4253:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4254:             foreach my $line (@responses) {
                   4255:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4256:                 $$replyref{$key} = $value;
                   4257:             }
                   4258:         } else {
1.506     raeburn  4259:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4260:             foreach my $line (@responses) {
                   4261:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4262:                 $$replyref{$key} = $value;
                   4263:                 if ($value > 0) {
1.800     albertel 4264:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4265:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4266:                         my $destname = $pathname.'/'.$filename;
                   4267:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4268:                         if ($xml_classlist =~ /^error/) {
                   4269:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4270:                         } else {
1.506     raeburn  4271:                             if ( open(FILE,">$destname") ) {
                   4272:                                 print FILE &unescape($xml_classlist);
                   4273:                                 close(FILE);
1.526     raeburn  4274:                             } else {
                   4275:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4276:                             }
                   4277:                         }
                   4278:                     }
                   4279:                 }
                   4280:             }
                   4281:         }
                   4282:         return 'ok';
                   4283:     }
                   4284:     return 'error';
                   4285: }
                   4286: 
1.242     www      4287: sub get_query_reply {
                   4288:     my $queryid=shift;
1.240     www      4289:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4290:     my $reply='';
                   4291:     for (1..100) {
                   4292: 	sleep 2;
                   4293:         if (-e $replyfile.'.end') {
1.448     albertel 4294: 	    if (open(my $fh,$replyfile)) {
1.240     www      4295:                $reply.=<$fh>;
1.448     albertel 4296:                close($fh);
1.240     www      4297: 	   } else { return 'error: reply_file_error'; }
1.242     www      4298:            return &unescape($reply);
                   4299: 	}
1.240     www      4300:     }
1.242     www      4301:     return 'timeout:'.$queryid;
1.240     www      4302: }
                   4303: 
                   4304: sub courselog_query {
1.241     www      4305: #
                   4306: # possible filters:
                   4307: # url: url or symb
                   4308: # username
                   4309: # domain
                   4310: # action: view, submit, grade
                   4311: # start: timestamp
                   4312: # end: timestamp
                   4313: #
1.240     www      4314:     my (%filters)=@_;
1.620     albertel 4315:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4316:     if ($filters{'url'}) {
                   4317: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4318:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4319:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4320:     }
1.620     albertel 4321:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4322:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4323:     return &log_query($cname,$cdom,'courselog',%filters);
                   4324: }
                   4325: 
                   4326: sub userlog_query {
                   4327:     my ($uname,$udom,%filters)=@_;
                   4328:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4329: }
                   4330: 
1.506     raeburn  4331: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4332: 
                   4333: sub auto_run {
1.508     raeburn  4334:     my ($cnum,$cdom) = @_;
                   4335:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4336:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4337:     return $response;
                   4338: }
1.776     albertel 4339: 
1.506     raeburn  4340: sub auto_get_sections {
1.508     raeburn  4341:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4342:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4343:     my @secs = ();
1.511     raeburn  4344:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4345:     unless ($response eq 'refused') {
                   4346:         @secs = split/:/,$response;
                   4347:     }
                   4348:     return @secs;
                   4349: }
1.776     albertel 4350: 
1.506     raeburn  4351: sub auto_new_course {
1.508     raeburn  4352:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4353:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4354:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4355:     return $response;
                   4356: }
1.776     albertel 4357: 
1.506     raeburn  4358: sub auto_validate_courseID {
1.508     raeburn  4359:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4360:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4361:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4362:     return $response;
                   4363: }
1.776     albertel 4364: 
1.506     raeburn  4365: sub auto_create_password {
1.508     raeburn  4366:     my ($cnum,$cdom,$authparam) = @_;
                   4367:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4368:     my $create_passwd = 0;
                   4369:     my $authchk = '';
1.511     raeburn  4370:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4371:     if ($response eq 'refused') {
                   4372:         $authchk = 'refused';
                   4373:     } else {
                   4374:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4375:     }
                   4376:     return ($authparam,$create_passwd,$authchk);
                   4377: }
                   4378: 
1.706     raeburn  4379: sub auto_photo_permission {
                   4380:     my ($cnum,$cdom,$students) = @_;
                   4381:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4382:     my ($outcome,$perm_reqd,$conditions) = 
                   4383: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4384:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4385: 	return (undef,undef);
                   4386:     }
1.706     raeburn  4387:     return ($outcome,$perm_reqd,$conditions);
                   4388: }
                   4389: 
                   4390: sub auto_checkphotos {
                   4391:     my ($uname,$udom,$pid) = @_;
                   4392:     my $homeserver = &homeserver($uname,$udom);
                   4393:     my ($result,$resulttype);
                   4394:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4395: 				   &escape($uname).':'.&escape($pid),
                   4396: 				   $homeserver));
1.709     albertel 4397:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4398: 	return (undef,undef);
                   4399:     }
1.706     raeburn  4400:     if ($outcome) {
                   4401:         ($result,$resulttype) = split(/:/,$outcome);
                   4402:     } 
                   4403:     return ($result,$resulttype);
                   4404: }
                   4405: 
                   4406: sub auto_photochoice {
                   4407:     my ($cnum,$cdom) = @_;
                   4408:     my $homeserver = &homeserver($cnum,$cdom);
                   4409:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4410: 						       &escape($cdom),
                   4411: 						       $homeserver)));
1.709     albertel 4412:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4413: 	return (undef,undef);
                   4414:     }
1.706     raeburn  4415:     return ($update,$comment);
                   4416: }
                   4417: 
                   4418: sub auto_photoupdate {
                   4419:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4420:     my $homeserver = &homeserver($cnum,$dom);
                   4421:     my $host=$hostname{$homeserver};
                   4422:     my $cmd = '';
                   4423:     my $maxtries = 1;
1.800     albertel 4424:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4425:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4426:     }
                   4427:     $cmd =~ s/%%$//;
                   4428:     $cmd = &escape($cmd);
                   4429:     my $query = 'institutionalphotos';
                   4430:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4431:     unless ($queryid=~/^\Q$host\E\_/) {
                   4432:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4433:         return 'error: '.$queryid;
                   4434:     }
                   4435:     my $reply = &get_query_reply($queryid);
                   4436:     my $tries = 1;
                   4437:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4438:         $reply = &get_query_reply($queryid);
                   4439:         $tries ++;
                   4440:     }
                   4441:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4442:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4443:     } else {
                   4444:         my @responses = split(/:/,$reply);
                   4445:         my $outcome = shift(@responses); 
                   4446:         foreach my $item (@responses) {
                   4447:             my ($key,$value) = split(/=/,$item);
                   4448:             $$photo{$key} = $value;
                   4449:         }
                   4450:         return $outcome;
                   4451:     }
                   4452:     return 'error';
                   4453: }
                   4454: 
1.521     raeburn  4455: sub auto_instcode_format {
1.793     albertel 4456:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4457: 	$cat_order) = @_;
1.521     raeburn  4458:     my $courses = '';
1.772     raeburn  4459:     my @homeservers;
1.521     raeburn  4460:     if ($caller eq 'global') {
1.793     albertel 4461:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4462:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4463:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4464:                     push(@homeservers,$tryserver);
                   4465:                 }
1.584     raeburn  4466:             }
                   4467:         }
1.521     raeburn  4468:     } else {
1.772     raeburn  4469:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4470:     }
1.793     albertel 4471:     foreach my $code (keys(%{$instcodes})) {
                   4472:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4473:     }
                   4474:     chop($courses);
1.772     raeburn  4475:     my $ok_response = 0;
                   4476:     my $response;
                   4477:     while (@homeservers > 0 && $ok_response == 0) {
                   4478:         my $server = shift(@homeservers); 
                   4479:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4480:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4481:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4482: 		split/:/,$response;
1.772     raeburn  4483:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4484:             push(@{$codetitles},&str2array($codetitles_str));
                   4485:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4486:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4487:             $ok_response = 1;
                   4488:         }
                   4489:     }
                   4490:     if ($ok_response) {
1.521     raeburn  4491:         return 'ok';
1.772     raeburn  4492:     } else {
                   4493:         return $response;
1.521     raeburn  4494:     }
                   4495: }
                   4496: 
1.792     raeburn  4497: sub auto_instcode_defaults {
                   4498:     my ($domain,$returnhash,$code_order) = @_;
                   4499:     my @homeservers;
1.793     albertel 4500:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4501:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4502:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4503:                 push(@homeservers,$tryserver);
                   4504:             }
                   4505:         }
                   4506:     }
                   4507:     my $ok_response = 0;
                   4508:     my $response;
                   4509:     while (@homeservers > 0 && $ok_response == 0) {
                   4510:         my $server = shift(@homeservers);
                   4511:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4512:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4513:             foreach my $pair (split(/\&/,$response)) {
                   4514:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4515:                 if ($name eq 'code_order') {
1.796     raeburn  4516:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4517:                 } else {
1.796     raeburn  4518:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4519:                 }
                   4520:             }
1.804     raeburn  4521:             $ok_response = 1;
1.792     raeburn  4522:         }
                   4523:     }
                   4524:     if ($ok_response) {
                   4525:         return 'ok';
                   4526:     } else {
                   4527:         return $response;
                   4528:     }
                   4529: } 
                   4530: 
1.777     albertel 4531: sub auto_validate_class_sec {
1.773     raeburn  4532:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4533:     my $homeserver = &homeserver($cnum,$cdom);
                   4534:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4535:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4536:     return $response;
                   4537: }
                   4538: 
1.679     raeburn  4539: # ------------------------------------------------------- Course Group routines
                   4540: 
                   4541: sub get_coursegroups {
1.809     raeburn  4542:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4543:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4544: }
                   4545: 
1.679     raeburn  4546: sub modify_coursegroup {
                   4547:     my ($cdom,$cnum,$groupsettings) = @_;
                   4548:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4549: }
                   4550: 
1.809     raeburn  4551: sub toggle_coursegroup_status {
                   4552:     my ($cdom,$cnum,$group,$action) = @_;
                   4553:     my ($from_namespace,$to_namespace);
                   4554:     if ($action eq 'delete') {
                   4555:         $from_namespace = 'coursegroups';
                   4556:         $to_namespace = 'deleted_groups';
                   4557:     } else {
                   4558:         $from_namespace = 'deleted_groups';
                   4559:         $to_namespace = 'coursegroups';
                   4560:     }
                   4561:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4562:     if (my $tmp = &error(%curr_group)) {
                   4563:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4564:         return ('read error',$tmp);
                   4565:     } else {
                   4566:         my %savedsettings = %curr_group; 
1.809     raeburn  4567:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4568:         my $deloutcome;
                   4569:         if ($result eq 'ok') {
1.809     raeburn  4570:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4571:         } else {
                   4572:             return ('write error',$result);
                   4573:         }
                   4574:         if ($deloutcome eq 'ok') {
                   4575:             return 'ok';
                   4576:         } else {
                   4577:             return ('delete error',$deloutcome);
                   4578:         }
                   4579:     }
                   4580: }
                   4581: 
1.679     raeburn  4582: sub modify_group_roles {
                   4583:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4584:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4585:     my $role = 'gr/'.&escape($userprivs);
                   4586:     my ($uname,$udom) = split(/:/,$user);
                   4587:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4588:     if ($result eq 'ok') {
                   4589:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4590:     }
1.679     raeburn  4591:     return $result;
                   4592: }
                   4593: 
                   4594: sub modify_coursegroup_membership {
                   4595:     my ($cdom,$cnum,$membership) = @_;
                   4596:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4597:     return $result;
                   4598: }
                   4599: 
1.682     raeburn  4600: sub get_active_groups {
                   4601:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4602:     my $now = time;
                   4603:     my %groups = ();
                   4604:     foreach my $key (keys(%env)) {
1.811     albertel 4605:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4606:             my ($start,$end) = split(/\./,$env{$key});
                   4607:             if (($end!=0) && ($end<$now)) { next; }
                   4608:             if (($start!=0) && ($start>$now)) { next; }
                   4609:             if ($1 eq $cdom && $2 eq $cnum) {
                   4610:                 $groups{$3} = $env{$key} ;
                   4611:             }
                   4612:         }
                   4613:     }
                   4614:     return %groups;
                   4615: }
                   4616: 
1.683     raeburn  4617: sub get_group_membership {
                   4618:     my ($cdom,$cnum,$group) = @_;
                   4619:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4620: }
                   4621: 
                   4622: sub get_users_groups {
                   4623:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4624:     my @usersgroups;
1.683     raeburn  4625:     my $cachetime=1800;
                   4626: 
                   4627:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4628:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4629:     if (defined($cached)) {
1.734     albertel 4630:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4631:     } else {  
                   4632:         $grouplist = '';
1.816     raeburn  4633:         my $courseurl = &courseid_to_courseurl($courseid);
                   4634:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4635:         my $access_end = $env{'course.'.$courseid.
                   4636:                               '.default_enrollment_end_date'};
                   4637:         my $now = time;
                   4638:         foreach my $key (keys(%roleshash)) {
                   4639:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4640:                 my $group = $1;
                   4641:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4642:                     my $start = $2;
                   4643:                     my $end = $1;
                   4644:                     if ($start == -1) { next; } # deleted from group
                   4645:                     if (($start!=0) && ($start>$now)) { next; }
                   4646:                     if (($end!=0) && ($end<$now)) {
                   4647:                         if ($access_end && $access_end < $now) {
                   4648:                             if ($access_end - $end < 86400) {
                   4649:                                 push(@usersgroups,$group);
1.733     raeburn  4650:                             }
                   4651:                         }
1.817     raeburn  4652:                         next;
1.733     raeburn  4653:                     }
1.817     raeburn  4654:                     push(@usersgroups,$group);
1.683     raeburn  4655:                 }
                   4656:             }
                   4657:         }
1.817     raeburn  4658:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4659:         $grouplist = join(':',@usersgroups);
                   4660:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4661:     }
1.733     raeburn  4662:     return @usersgroups;
1.683     raeburn  4663: }
                   4664: 
                   4665: sub devalidate_getgroups_cache {
                   4666:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4667:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4668: 
1.683     raeburn  4669:     my $hashid="$udom:$uname:$courseid";
                   4670:     &devalidate_cache_new('getgroups',$hashid);
                   4671: }
                   4672: 
1.12      www      4673: # ------------------------------------------------------------------ Plain Text
                   4674: 
                   4675: sub plaintext {
1.742     raeburn  4676:     my ($short,$type,$cid) = @_;
1.758     albertel 4677:     if ($short =~ /^cr/) {
                   4678: 	return (split('/',$short))[-1];
                   4679:     }
1.742     raeburn  4680:     if (!defined($cid)) {
                   4681:         $cid = $env{'request.course.id'};
                   4682:     }
                   4683:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4684:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4685:                                           '.plaintext'});
                   4686:     }
                   4687:     my %rolenames = (
                   4688:                       Course => 'std',
                   4689:                       Group => 'alt1',
                   4690:                     );
                   4691:     if (defined($type) && 
                   4692:          defined($rolenames{$type}) && 
                   4693:          defined($prp{$short}{$rolenames{$type}})) {
                   4694:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4695:     } else {
                   4696:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4697:     }
1.12      www      4698: }
                   4699: 
                   4700: # ----------------------------------------------------------------- Assign Role
                   4701: 
                   4702: sub assignrole {
1.357     www      4703:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4704:     my $mrole;
                   4705:     if ($role =~ /^cr\//) {
1.393     www      4706:         my $cwosec=$url;
1.811     albertel 4707:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4708: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4709:            &logthis('Refused custom assignrole: '.
                   4710:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4711: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4712:            return 'refused'; 
                   4713:         }
1.21      www      4714:         $mrole='cr';
1.678     raeburn  4715:     } elsif ($role =~ /^gr\//) {
                   4716:         my $cwogrp=$url;
1.811     albertel 4717:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4718:         unless (&allowed('mdg',$cwogrp)) {
                   4719:             &logthis('Refused group assignrole: '.
                   4720:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4721:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4722:             return 'refused';
                   4723:         }
                   4724:         $mrole='gr';
1.21      www      4725:     } else {
1.82      www      4726:         my $cwosec=$url;
1.811     albertel 4727:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4728:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4729:            &logthis('Refused assignrole: '.
                   4730:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4731: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4732:            return 'refused'; 
                   4733:         }
1.21      www      4734:         $mrole=$role;
                   4735:     }
1.620     albertel 4736:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4737:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4738:     if ($end) { $command.='_'.$end; }
1.21      www      4739:     if ($start) {
                   4740: 	if ($end) { 
1.81      www      4741:            $command.='_'.$start; 
1.21      www      4742:         } else {
1.81      www      4743:            $command.='_0_'.$start;
1.21      www      4744:         }
                   4745:     }
1.739     raeburn  4746:     my $origstart = $start;
                   4747:     my $origend = $end;
1.357     www      4748: # actually delete
                   4749:     if ($deleteflag) {
1.373     www      4750: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4751: # modify command to delete the role
1.620     albertel 4752:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4753:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4754: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4755: # set start and finish to negative values for userrolelog
                   4756:            $start=-1;
                   4757:            $end=-1;
                   4758:         }
                   4759:     }
                   4760: # send command
1.349     www      4761:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4762: # log new user role if status is ok
1.349     www      4763:     if ($answer eq 'ok') {
1.663     raeburn  4764: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4765: # for course roles, perform group memberships changes triggered by role change.
                   4766:         unless ($role =~ /^gr/) {
                   4767:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4768:                                              $origstart);
                   4769:         }
1.349     www      4770:     }
                   4771:     return $answer;
1.169     harris41 4772: }
                   4773: 
                   4774: # -------------------------------------------------- Modify user authentication
1.197     www      4775: # Overrides without validation
                   4776: 
1.169     harris41 4777: sub modifyuserauth {
                   4778:     my ($udom,$uname,$umode,$upass)=@_;
                   4779:     my $uhome=&homeserver($uname,$udom);
1.197     www      4780:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4781:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4782:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4783:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4784:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4785: 		     &escape($upass),$uhome);
1.620     albertel 4786:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4787:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4788:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4789:     &log($udom,,$uname,$uhome,
1.620     albertel 4790:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4791:                                      $env{'user.name'}.', '.$umode.
1.197     www      4792:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4793:     unless ($reply eq 'ok') {
1.197     www      4794:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4795: 	return 'error: '.$reply;
                   4796:     }   
1.170     harris41 4797:     return 'ok';
1.80      www      4798: }
                   4799: 
1.81      www      4800: # --------------------------------------------------------------- Modify a user
1.80      www      4801: 
1.81      www      4802: sub modifyuser {
1.206     matthew  4803:     my ($udom,    $uname, $uid,
                   4804:         $umode,   $upass, $first,
                   4805:         $middle,  $last,  $gene,
1.387     www      4806:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4807:     $udom= &LONCAPA::clean_domain($udom);
                   4808:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4809:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4810:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4811: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4812:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4813:                                      ' desiredhome not specified'). 
1.620     albertel 4814:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4815:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4816:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4817: # ----------------------------------------------------------------- Create User
1.406     albertel 4818:     if (($uhome eq 'no_host') && 
                   4819: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4820:         my $unhome='';
1.209     matthew  4821:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4822:             $unhome = $desiredhome;
1.620     albertel 4823: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4824: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4825:         } else { # load balancing routine for determining $unhome
1.80      www      4826:             my $tryserver;
1.81      www      4827:             my $loadm=10000000;
1.80      www      4828:             foreach $tryserver (keys %libserv) {
                   4829: 	       if ($hostdom{$tryserver} eq $udom) {
                   4830:                   my $answer=reply('load',$tryserver);
                   4831:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4832: 		      $loadm=$answer;
                   4833:                       $unhome=$tryserver;
                   4834:                   }
                   4835: 	       }
                   4836: 	    }
                   4837:         }
                   4838:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4839: 	    return 'error: unable to find a home server for '.$uname.
                   4840:                    ' in domain '.$udom;
1.80      www      4841:         }
                   4842:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4843:                          &escape($upass),$unhome);
                   4844: 	unless ($reply eq 'ok') {
                   4845:             return 'error: '.$reply;
                   4846:         }   
1.230     stredwic 4847:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4848:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4849: 	    return 'error: unable verify users home machine.';
1.80      www      4850:         }
1.209     matthew  4851:     }   # End of creation of new user
1.80      www      4852: # ---------------------------------------------------------------------- Add ID
                   4853:     if ($uid) {
                   4854:        $uid=~tr/A-Z/a-z/;
                   4855:        my %uidhash=&idrget($udom,$uname);
1.196     www      4856:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4857:          && (!$forceid)) {
1.80      www      4858: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4859: 	      return 'error: user id "'.$uid.'" does not match '.
                   4860:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4861:           }
                   4862:        } else {
                   4863: 	  &idput($udom,($uname => $uid));
                   4864:        }
                   4865:     }
                   4866: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4867:     my @tmp=&get('environment',
1.134     albertel 4868: 		   ['firstname','middlename','lastname','generation'],
                   4869: 		   $udom,$uname);
1.313     matthew  4870:     my %names;
                   4871:     if ($tmp[0] =~ m/^error:.*/) { 
                   4872:         %names=(); 
                   4873:     } else {
                   4874:         %names = @tmp;
                   4875:     }
1.388     www      4876: #
                   4877: # Make sure to not trash student environment if instructor does not bother
                   4878: # to supply name and email information
                   4879: #
                   4880:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4881:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4882:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4883:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4884:     if ($email) {
                   4885:        $email=~s/[^\w\@\.\-\,]//gs;
                   4886:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4887: 			   $names{'critnotification'} = $email;
                   4888: 			   $names{'permanentemail'} = $email; }
                   4889:     }
1.134     albertel 4890:     my $reply = &put('environment', \%names, $udom,$uname);
                   4891:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4892:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4893:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4894:              $umode.', '.$first.', '.$middle.', '.
                   4895: 	     $last.', '.$gene.' by '.
1.620     albertel 4896:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4897:     return 'ok';
1.80      www      4898: }
                   4899: 
1.81      www      4900: # -------------------------------------------------------------- Modify student
1.80      www      4901: 
1.81      www      4902: sub modifystudent {
                   4903:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4904:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4905:     if (!$cid) {
1.620     albertel 4906: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4907: 	    return 'not_in_class';
                   4908: 	}
1.80      www      4909:     }
                   4910: # --------------------------------------------------------------- Make the user
1.81      www      4911:     my $reply=&modifyuser
1.209     matthew  4912: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4913:          $desiredhome,$email);
1.80      www      4914:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4915:     # This will cause &modify_student_enrollment to get the uid from the
                   4916:     # students environment
                   4917:     $uid = undef if (!$forceid);
1.455     albertel 4918:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4919: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4920:     return $reply;
                   4921: }
                   4922: 
                   4923: sub modify_student_enrollment {
1.515     raeburn  4924:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4925:     my ($cdom,$cnum,$chome);
                   4926:     if (!$cid) {
1.620     albertel 4927: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4928: 	    return 'not_in_class';
                   4929: 	}
1.620     albertel 4930: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4931: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4932:     } else {
                   4933: 	($cdom,$cnum)=split(/_/,$cid);
                   4934:     }
1.620     albertel 4935:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4936:     if (!$chome) {
1.457     raeburn  4937: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4938:     }
1.455     albertel 4939:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4940:     # Make sure the user exists
1.81      www      4941:     my $uhome=&homeserver($uname,$udom);
                   4942:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4943: 	return 'error: no such user';
                   4944:     }
1.297     matthew  4945:     # Get student data if we were not given enough information
                   4946:     if (!defined($first)  || $first  eq '' || 
                   4947:         !defined($last)   || $last   eq '' || 
                   4948:         !defined($uid)    || $uid    eq '' || 
                   4949:         !defined($middle) || $middle eq '' || 
                   4950:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4951:         # They did not supply us with enough data to enroll the student, so
                   4952:         # we need to pick up more information.
1.297     matthew  4953:         my %tmp = &get('environment',
1.294     matthew  4954:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4955:                        ,$udom,$uname);
                   4956: 
1.800     albertel 4957:         #foreach my $key (keys(%tmp)) {
                   4958:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4959:         #}
1.294     matthew  4960:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4961:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4962:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4963:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4964:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4965:     }
1.556     albertel 4966:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4967:     my $reply=cput('classlist',
                   4968: 		   {"$uname:$udom" => 
1.515     raeburn  4969: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4970: 		   $cdom,$cnum);
1.81      www      4971:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4972: 	return 'error: '.$reply;
1.652     albertel 4973:     } else {
                   4974: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4975:     }
1.297     matthew  4976:     # Add student role to user
1.83      www      4977:     my $uurl='/'.$cid;
1.81      www      4978:     $uurl=~s/\_/\//g;
                   4979:     if ($usec) {
                   4980: 	$uurl.='/'.$usec;
                   4981:     }
                   4982:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4983: }
                   4984: 
1.556     albertel 4985: sub format_name {
                   4986:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4987:     my $name;
                   4988:     if ($first ne 'lastname') {
                   4989: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4990:     } else {
                   4991: 	if ($lastname=~/\S/) {
                   4992: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4993: 	    $name=~s/\s+,/,/;
                   4994: 	} else {
                   4995: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4996: 	}
                   4997:     }
                   4998:     $name=~s/^\s+//;
                   4999:     $name=~s/\s+$//;
                   5000:     $name=~s/\s+/ /g;
                   5001:     return $name;
                   5002: }
                   5003: 
1.84      www      5004: # ------------------------------------------------- Write to course preferences
                   5005: 
                   5006: sub writecoursepref {
                   5007:     my ($courseid,%prefs)=@_;
                   5008:     $courseid=~s/^\///;
                   5009:     $courseid=~s/\_/\//g;
                   5010:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5011:     my $chome=homeserver($cnum,$cdomain);
                   5012:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5013: 	return 'error: no such course';
                   5014:     }
                   5015:     my $cstring='';
1.800     albertel 5016:     foreach my $pref (keys(%prefs)) {
                   5017: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5018:     }
1.84      www      5019:     $cstring=~s/\&$//;
                   5020:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5021: }
                   5022: 
                   5023: # ---------------------------------------------------------- Make/modify course
                   5024: 
                   5025: sub createcourse {
1.741     raeburn  5026:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5027:         $course_owner,$crstype)=@_;
1.84      www      5028:     $url=&declutter($url);
                   5029:     my $cid='';
1.264     matthew  5030:     unless (&allowed('ccc',$udom)) {
1.84      www      5031:         return 'refused';
                   5032:     }
                   5033: # ------------------------------------------------------------------- Create ID
1.674     www      5034:    my $uname=int(1+rand(9)).
                   5035:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5036:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5037:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5038: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5039:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5040:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5041:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5042:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5043:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5044:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5045:            return 'error: unable to generate unique course-ID';
                   5046:        } 
                   5047:    }
1.264     matthew  5048: # ------------------------------------------------ Check supplied server name
1.620     albertel 5049:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  5050:     if (! exists($libserv{$course_server})) {
                   5051:         return 'error:bad server name '.$course_server;
                   5052:     }
1.84      www      5053: # ------------------------------------------------------------- Make the course
                   5054:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5055:                       $course_server);
1.84      www      5056:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5057:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5058:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5059: 	return 'error: no such course';
                   5060:     }
1.271     www      5061: # ----------------------------------------------------------------- Course made
1.516     raeburn  5062: # log existence
                   5063:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5064:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5065:                   &escape($crstype),$uhome);
1.358     www      5066:     &flushcourselogs();
                   5067: # set toplevel url
1.271     www      5068:     my $topurl=$url;
                   5069:     unless ($nonstandard) {
                   5070: # ------------------------------------------ For standard courses, make top url
                   5071:         my $mapurl=&clutter($url);
1.278     www      5072:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5073:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5074: <map>
                   5075: <resource id="1" type="start"></resource>
                   5076: <resource id="2" src="$mapurl"></resource>
                   5077: <resource id="3" type="finish"></resource>
                   5078: <link index="1" from="1" to="2"></link>
                   5079: <link index="2" from="2" to="3"></link>
                   5080: </map>
                   5081: ENDINITMAP
                   5082:         $topurl=&declutter(
1.638     albertel 5083:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5084:                           );
                   5085:     }
                   5086: # ----------------------------------------------------------- Write preferences
1.84      www      5087:     &writecoursepref($udom.'_'.$uname,
                   5088:                      ('description' => $description,
1.271     www      5089:                       'url'         => $topurl));
1.84      www      5090:     return '/'.$udom.'/'.$uname;
                   5091: }
                   5092: 
1.813     albertel 5093: sub is_course {
                   5094:     my ($cdom,$cnum) = @_;
                   5095:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5096: 				undef,'.');
                   5097:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5098:         return 1;
                   5099:     }
                   5100:     return 0;
                   5101: }
                   5102: 
1.21      www      5103: # ---------------------------------------------------------- Assign Custom Role
                   5104: 
                   5105: sub assigncustomrole {
1.357     www      5106:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5107:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5108:                        $end,$start,$deleteflag);
1.21      www      5109: }
                   5110: 
                   5111: # ----------------------------------------------------------------- Revoke Role
                   5112: 
                   5113: sub revokerole {
1.357     www      5114:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5115:     my $now=time;
1.357     www      5116:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5117: }
                   5118: 
                   5119: # ---------------------------------------------------------- Revoke Custom Role
                   5120: 
                   5121: sub revokecustomrole {
1.357     www      5122:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5123:     my $now=time;
1.357     www      5124:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5125:            $deleteflag);
1.17      www      5126: }
                   5127: 
1.533     banghart 5128: # ------------------------------------------------------------ Disk usage
1.535     albertel 5129: sub diskusage {
1.533     banghart 5130:     my ($udom,$uname,$directoryRoot)=@_;
                   5131:     $directoryRoot =~ s/\/$//;
1.535     albertel 5132:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5133:     return $listing;
1.512     banghart 5134: }
                   5135: 
1.566     banghart 5136: sub is_locked {
                   5137:     my ($file_name, $domain, $user) = @_;
                   5138:     my @check;
                   5139:     my $is_locked;
                   5140:     push @check, $file_name;
1.613     albertel 5141:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5142: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5143:     my ($tmp)=keys(%locked);
                   5144:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5145:     
1.566     banghart 5146:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5147:         $is_locked = 'false';
                   5148:         foreach my $entry (@{$locked{$file_name}}) {
                   5149:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5150:                $is_locked = 'true';
                   5151:                last;
1.745     raeburn  5152:            }
                   5153:        }
1.566     banghart 5154:     } else {
                   5155:         $is_locked = 'false';
                   5156:     }
                   5157: }
                   5158: 
1.759     albertel 5159: sub declutter_portfile {
                   5160:     my ($file) = @_;
1.833     albertel 5161:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5162:     return $file;
                   5163: }
                   5164: 
1.559     banghart 5165: # ------------------------------------------------------------- Mark as Read Only
                   5166: 
                   5167: sub mark_as_readonly {
                   5168:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5169:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5170:     my ($tmp)=keys(%current_permissions);
                   5171:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5172:     foreach my $file (@{$files}) {
1.759     albertel 5173: 	$file = &declutter_portfile($file);
1.561     banghart 5174:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5175:     }
1.613     albertel 5176:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5177:     return;
                   5178: }
                   5179: 
1.572     banghart 5180: # ------------------------------------------------------------Save Selected Files
                   5181: 
                   5182: sub save_selected_files {
                   5183:     my ($user, $path, @files) = @_;
                   5184:     my $filename = $user."savedfiles";
1.573     banghart 5185:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5186:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5187:     foreach my $file (@files) {
1.620     albertel 5188:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5189:     }
                   5190:     foreach my $file (@other_files) {
1.574     banghart 5191:         print (OUT $file."\n");
1.572     banghart 5192:     }
1.574     banghart 5193:     close (OUT);
1.572     banghart 5194:     return 'ok';
                   5195: }
                   5196: 
1.574     banghart 5197: sub clear_selected_files {
                   5198:     my ($user) = @_;
                   5199:     my $filename = $user."savedfiles";
                   5200:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5201:     print (OUT undef);
                   5202:     close (OUT);
                   5203:     return ("ok");    
                   5204: }
                   5205: 
1.572     banghart 5206: sub files_in_path {
                   5207:     my ($user, $path) = @_;
                   5208:     my $filename = $user."savedfiles";
                   5209:     my %return_files;
1.574     banghart 5210:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5211:     while (my $line_in = <IN>) {
1.574     banghart 5212:         chomp ($line_in);
                   5213:         my @paths_and_file = split (m!/!, $line_in);
                   5214:         my $file_part = pop (@paths_and_file);
                   5215:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5216:         $path_part.='/';
                   5217:         my $path_and_file = $path_part.$file_part;
                   5218:         if ($path_part eq $path) {
                   5219:             $return_files{$file_part}= 'selected';
                   5220:         }
                   5221:     }
1.574     banghart 5222:     close (IN);
                   5223:     return (\%return_files);
1.572     banghart 5224: }
                   5225: 
                   5226: # called in portfolio select mode, to show files selected NOT in current directory
                   5227: sub files_not_in_path {
                   5228:     my ($user, $path) = @_;
                   5229:     my $filename = $user."savedfiles";
                   5230:     my @return_files;
                   5231:     my $path_part;
1.800     albertel 5232:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5233:     while (my $line = <IN>) {
1.572     banghart 5234:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5235:         my @paths_and_file = split(m|/|, $line);
                   5236:         my $file_part = pop(@paths_and_file);
                   5237:         chomp($file_part);
                   5238:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5239:         $path_part .= '/';
                   5240:         my $path_and_file = $path_part.$file_part;
                   5241:         if ($path_part ne $path) {
1.800     albertel 5242:             push(@return_files, ($path_and_file));
1.572     banghart 5243:         }
                   5244:     }
1.800     albertel 5245:     close(OUT);
1.574     banghart 5246:     return (@return_files);
1.572     banghart 5247: }
                   5248: 
1.745     raeburn  5249: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5250: 
1.745     raeburn  5251: sub get_portfile_permissions {
                   5252:     my ($domain,$user) = @_;
1.613     albertel 5253:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5254:     my ($tmp)=keys(%current_permissions);
                   5255:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5256:     return \%current_permissions;
                   5257: }
                   5258: 
                   5259: #---------------------------------------------Get portfolio file access controls
                   5260: 
1.749     raeburn  5261: sub get_access_controls {
1.745     raeburn  5262:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5263:     my %access;
                   5264:     my $real_file = $file;
                   5265:     $file =~ s/\.meta$//;
1.745     raeburn  5266:     if (defined($file)) {
1.749     raeburn  5267:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5268:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5269:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5270:             }
                   5271:         }
1.745     raeburn  5272:     } else {
1.749     raeburn  5273:         foreach my $key (keys(%{$current_permissions})) {
                   5274:             if ($key =~ /\0accesscontrol$/) {
                   5275:                 if (defined($group)) {
                   5276:                     if ($key !~ m-^\Q$group\E/-) {
                   5277:                         next;
                   5278:                     }
                   5279:                 }
                   5280:                 my ($fullpath) = split(/\0/,$key);
                   5281:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5282:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5283:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5284:                     }
                   5285:                 }
                   5286:             }
                   5287:         }
                   5288:     }
                   5289:     return %access;
                   5290: }
                   5291: 
                   5292: sub modify_access_controls {
                   5293:     my ($file_name,$changes,$domain,$user)=@_;
                   5294:     my ($outcome,$deloutcome);
                   5295:     my %store_permissions;
                   5296:     my %new_values;
                   5297:     my %new_control;
                   5298:     my %translation;
                   5299:     my @deletions = ();
                   5300:     my $now = time;
                   5301:     if (exists($$changes{'activate'})) {
                   5302:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5303:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5304:             my $numnew = scalar(@newitems);
                   5305:             for (my $i=0; $i<$numnew; $i++) {
                   5306:                 my $newkey = $newitems[$i];
                   5307:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5308:                 if ($newkey =~ /^\d+:/) { 
                   5309:                     $newkey =~ s/^(\d+)/$newid/;
                   5310:                     $translation{$1} = $newid;
                   5311:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5312:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5313:                     $translation{$1} = $newid;
                   5314:                 }
1.749     raeburn  5315:                 $new_values{$file_name."\0".$newkey} = 
                   5316:                                           $$changes{'activate'}{$newitems[$i]};
                   5317:                 $new_control{$newkey} = $now;
                   5318:             }
                   5319:         }
                   5320:     }
                   5321:     my %todelete;
                   5322:     my %changed_items;
                   5323:     foreach my $action ('delete','update') {
                   5324:         if (exists($$changes{$action})) {
                   5325:             if (ref($$changes{$action}) eq 'HASH') {
                   5326:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5327:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5328:                     if ($action eq 'delete') { 
                   5329:                         $todelete{$itemnum} = 1;
                   5330:                     } else {
                   5331:                         $changed_items{$itemnum} = $key;
                   5332:                     }
                   5333:                 }
1.745     raeburn  5334:             }
                   5335:         }
1.749     raeburn  5336:     }
                   5337:     # get lock on access controls for file.
                   5338:     my $lockhash = {
                   5339:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5340:                                                        ':'.$env{'user.domain'},
                   5341:                    }; 
                   5342:     my $tries = 0;
                   5343:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5344:    
                   5345:     while (($gotlock ne 'ok') && $tries <3) {
                   5346:         $tries ++;
                   5347:         sleep 1;
                   5348:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5349:     }
                   5350:     if ($gotlock eq 'ok') {
                   5351:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5352:         my ($tmp)=keys(%curr_permissions);
                   5353:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5354:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5355:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5356:             if (ref($curr_controls) eq 'HASH') {
                   5357:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5358:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5359:                     if (defined($todelete{$itemnum})) {
                   5360:                         push(@deletions,$file_name."\0".$control_item);
                   5361:                     } else {
                   5362:                         if (defined($changed_items{$itemnum})) {
                   5363:                             $new_control{$changed_items{$itemnum}} = $now;
                   5364:                             push(@deletions,$file_name."\0".$control_item);
                   5365:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5366:                         } else {
                   5367:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5368:                         }
                   5369:                     }
1.745     raeburn  5370:                 }
                   5371:             }
                   5372:         }
1.749     raeburn  5373:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5374:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5375:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5376:         #  remove lock
                   5377:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5378:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5379:         my ($file,$group);
                   5380:         if (&is_course($domain,$user)) {
                   5381:             ($group,$file) = split(/\//,$file_name,2);
                   5382:         } else {
                   5383:             $file = $file_name;
                   5384:         }
                   5385:         my $sqlresult =
                   5386:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5387:                                     $group);
1.749     raeburn  5388:     } else {
                   5389:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5390:     }
1.749     raeburn  5391:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5392: }
                   5393: 
1.827     raeburn  5394: sub make_public_indefinitely {
                   5395:     my ($requrl) = @_;
                   5396:     my $now = time;
                   5397:     my $action = 'activate';
                   5398:     my $aclnum = 0;
                   5399:     if (&is_portfolio_url($requrl)) {
                   5400:         my (undef,$udom,$unum,$file_name,$group) =
                   5401:             &parse_portfolio_url($requrl);
                   5402:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5403:         my %access_controls = &get_access_controls($current_perms,
                   5404:                                                    $group,$file_name);
                   5405:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5406:             my ($num,$scope,$end,$start) = 
                   5407:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5408:             if ($scope eq 'public') {
                   5409:                 if ($start <= $now && $end == 0) {
                   5410:                     $action = 'none';
                   5411:                 } else {
                   5412:                     $action = 'update';
                   5413:                     $aclnum = $num;
                   5414:                 }
                   5415:                 last;
                   5416:             }
                   5417:         }
                   5418:         if ($action eq 'none') {
                   5419:              return 'ok';
                   5420:         } else {
                   5421:             my %changes;
                   5422:             my $newend = 0;
                   5423:             my $newstart = $now;
                   5424:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5425:             $changes{$action}{$newkey} = {
                   5426:                 type => 'public',
                   5427:                 time => {
                   5428:                     start => $newstart,
                   5429:                     end   => $newend,
                   5430:                 },
                   5431:             };
                   5432:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5433:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5434:             return $outcome;
                   5435:         }
                   5436:     } else {
                   5437:         return 'invalid';
                   5438:     }
                   5439: }
                   5440: 
1.745     raeburn  5441: #------------------------------------------------------Get Marked as Read Only
                   5442: 
                   5443: sub get_marked_as_readonly {
                   5444:     my ($domain,$user,$what,$group) = @_;
                   5445:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5446:     my @readonly_files;
1.629     banghart 5447:     my $cmp1=$what;
                   5448:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5449:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5450:         if (defined($group)) {
                   5451:             if ($file_name !~ m-^\Q$group\E/-) {
                   5452:                 next;
                   5453:             }
                   5454:         }
1.561     banghart 5455:         if (ref($value) eq "ARRAY"){
                   5456:             foreach my $stored_what (@{$value}) {
1.629     banghart 5457:                 my $cmp2=$stored_what;
1.759     albertel 5458:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5459:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5460:                 }
1.629     banghart 5461:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5462:                     push(@readonly_files, $file_name);
1.745     raeburn  5463:                     last;
1.563     banghart 5464:                 } elsif (!defined($what)) {
                   5465:                     push(@readonly_files, $file_name);
1.745     raeburn  5466:                     last;
1.561     banghart 5467:                 }
                   5468:             }
1.745     raeburn  5469:         }
1.561     banghart 5470:     }
                   5471:     return @readonly_files;
                   5472: }
1.577     banghart 5473: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5474: 
1.577     banghart 5475: sub get_marked_as_readonly_hash {
1.745     raeburn  5476:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5477:     my %readonly_files;
1.745     raeburn  5478:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5479:         if (defined($group)) {
                   5480:             if ($file_name !~ m-^\Q$group\E/-) {
                   5481:                 next;
                   5482:             }
                   5483:         }
1.577     banghart 5484:         if (ref($value) eq "ARRAY"){
                   5485:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5486:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5487:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5488:                         if ($lock_descriptor eq 'graded') {
                   5489:                             $readonly_files{$file_name} = 'graded';
                   5490:                         } elsif ($lock_descriptor eq 'handback') {
                   5491:                             $readonly_files{$file_name} = 'handback';
                   5492:                         } else {
                   5493:                             if (!exists($readonly_files{$file_name})) {
                   5494:                                 $readonly_files{$file_name} = 'locked';
                   5495:                             }
                   5496:                         }
1.745     raeburn  5497:                     }
1.750     banghart 5498:                 } 
1.577     banghart 5499:             }
                   5500:         } 
                   5501:     }
                   5502:     return %readonly_files;
                   5503: }
1.559     banghart 5504: # ------------------------------------------------------------ Unmark as Read Only
                   5505: 
                   5506: sub unmark_as_readonly {
1.629     banghart 5507:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5508:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5509:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5510:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5511:     my $symb_crs = $what;
                   5512:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5513:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5514:     my ($tmp)=keys(%current_permissions);
                   5515:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5516:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5517:     foreach my $file (@readonly_files) {
1.759     albertel 5518: 	my $clean_file = &declutter_portfile($file);
                   5519: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5520: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5521:         my @new_locks;
                   5522:         my @del_keys;
                   5523:         if (ref($current_locks) eq "ARRAY"){
                   5524:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5525:                 my $compare=$locker;
1.749     raeburn  5526:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5527:                     $compare=join('',@{$locker});
1.746     raeburn  5528:                     if ($compare ne $symb_crs) {
                   5529:                         push(@new_locks, $locker);
                   5530:                     }
1.563     banghart 5531:                 }
                   5532:             }
1.650     albertel 5533:             if (scalar(@new_locks) > 0) {
1.563     banghart 5534:                 $current_permissions{$file} = \@new_locks;
                   5535:             } else {
                   5536:                 push(@del_keys, $file);
1.613     albertel 5537:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5538:                 delete($current_permissions{$file});
1.563     banghart 5539:             }
                   5540:         }
1.561     banghart 5541:     }
1.613     albertel 5542:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5543:     return;
                   5544: }
1.512     banghart 5545: 
1.17      www      5546: # ------------------------------------------------------------ Directory lister
                   5547: 
                   5548: sub dirlist {
1.253     stredwic 5549:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5550: 
1.18      www      5551:     $uri=~s/^\///;
                   5552:     $uri=~s/\/$//;
1.253     stredwic 5553:     my ($udom, $uname);
                   5554:     (undef,$udom,$uname)=split(/\//,$uri);
                   5555:     if(defined($userdomain)) {
                   5556:         $udom = $userdomain;
                   5557:     }
                   5558:     if(defined($username)) {
                   5559:         $uname = $username;
                   5560:     }
                   5561: 
                   5562:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5563:     if(defined($alternateDirectoryRoot)) {
                   5564:         $dirRoot = $alternateDirectoryRoot;
                   5565:         $dirRoot =~ s/\/$//;
1.751     banghart 5566:     }
1.253     stredwic 5567: 
                   5568:     if($udom) {
                   5569:         if($uname) {
1.800     albertel 5570:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5571: 				 &homeserver($uname,$udom));
1.605     matthew  5572:             my @listing_results;
                   5573:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5574:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5575: 				  &homeserver($uname,$udom));
1.605     matthew  5576:                 @listing_results = split(/:/,$listing);
                   5577:             } else {
                   5578:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5579:             }
                   5580:             return @listing_results;
1.253     stredwic 5581:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5582:             my %allusers;
                   5583:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5584:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5585:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5586: 					 $udom, $tryserver);
1.605     matthew  5587:                     my @listing_results;
                   5588:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5589:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5590: 					  $udom, $tryserver);
1.605     matthew  5591:                         @listing_results = split(/:/,$listing);
                   5592:                     } else {
                   5593:                         @listing_results =
                   5594:                             map { &unescape($_); } split(/:/,$listing);
                   5595:                     }
                   5596:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5597:                         $listing_results[0] ne 'empty'       &&
                   5598:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5599:                         foreach my $line (@listing_results) {
                   5600:                             my ($entry) = split(/&/,$line,2);
                   5601:                             $allusers{$entry} = 1;
1.253     stredwic 5602:                         }
                   5603:                     }
1.191     harris41 5604:                 }
1.253     stredwic 5605:             }
                   5606:             my $alluserstr='';
1.800     albertel 5607:             foreach my $user (sort(keys(%allusers))) {
                   5608:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5609:             }
                   5610:             $alluserstr=~s/:$//;
                   5611:             return split(/:/,$alluserstr);
                   5612:         } else {
1.800     albertel 5613:             return ('missing user name');
1.253     stredwic 5614:         }
                   5615:     } elsif(!defined($alternateDirectoryRoot)) {
                   5616:         my $tryserver;
                   5617:         my %alldom=();
1.800     albertel 5618:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5619:             $alldom{$hostdom{$tryserver}}=1;
                   5620:         }
                   5621:         my $alldomstr='';
1.800     albertel 5622:         foreach my $domain (sort(keys(%alldom))) {
                   5623:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5624:         }
                   5625:         $alldomstr=~s/:$//;
                   5626:         return split(/:/,$alldomstr);       
                   5627:     } else {
1.800     albertel 5628:         return ('missing domain');
1.275     stredwic 5629:     }
                   5630: }
                   5631: 
                   5632: # --------------------------------------------- GetFileTimestamp
                   5633: # This function utilizes dirlist and returns the date stamp for
                   5634: # when it was last modified.  It will also return an error of -1
                   5635: # if an error occurs
                   5636: 
1.410     matthew  5637: ##
                   5638: ## FIXME: This subroutine assumes its caller knows something about the
                   5639: ## directory structure of the home server for the student ($root).
                   5640: ## Not a good assumption to make.  Since this is for looking up files
                   5641: ## in user directories, the full path should be constructed by lond, not
                   5642: ## whatever machine we request data from.
                   5643: ##
1.275     stredwic 5644: sub GetFileTimestamp {
                   5645:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5646:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5647:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5648:     my $subdir=$studentName.'__';
                   5649:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5650:     my $proname="$studentDomain/$subdir/$studentName";
                   5651:     $proname .= '/'.$filename;
1.375     matthew  5652:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5653:                                               $studentName, $root);
1.275     stredwic 5654:     my @stats = split('&', $fileStat);
                   5655:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5656:         # @stats contains first the filename, then the stat output
                   5657:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5658:     } else {
                   5659:         return -1;
1.253     stredwic 5660:     }
1.26      www      5661: }
                   5662: 
1.712     albertel 5663: sub stat_file {
                   5664:     my ($uri) = @_;
1.787     albertel 5665:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5666: 
1.712     albertel 5667:     my ($udom,$uname,$file,$dir);
                   5668:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5669: 	($udom,$uname,$file) =
1.811     albertel 5670: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5671: 	$file = 'userfiles/'.$file;
1.740     www      5672: 	$dir = &propath($udom,$uname);
1.712     albertel 5673:     }
                   5674:     if ($uri =~ m-^/res/-) {
                   5675: 	($udom,$uname) = 
1.807     albertel 5676: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5677: 	$file = $uri;
                   5678:     }
                   5679: 
                   5680:     if (!$udom || !$uname || !$file) {
                   5681: 	# unable to handle the uri
                   5682: 	return ();
                   5683:     }
                   5684: 
                   5685:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5686:     my @stats = split('&', $result);
1.721     banghart 5687:     
1.712     albertel 5688:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5689: 	shift(@stats); #filename is first
                   5690: 	return @stats;
                   5691:     }
                   5692:     return ();
                   5693: }
                   5694: 
1.26      www      5695: # -------------------------------------------------------- Value of a Condition
                   5696: 
1.713     albertel 5697: # gets the value of a specific preevaluated condition
                   5698: #    stored in the string  $env{user.state.<cid>}
                   5699: # or looks up a condition reference in the bighash and if if hasn't
                   5700: # already been evaluated recurses into docondval to get the value of
                   5701: # the condition, then memoizing it to 
                   5702: #   $env{user.state.<cid>.<condition>}
1.40      www      5703: sub directcondval {
                   5704:     my $number=shift;
1.620     albertel 5705:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5706: 	&Apache::lonuserstate::evalstate();
                   5707:     }
1.713     albertel 5708:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5709: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5710:     } elsif ($number =~ /^_/) {
                   5711: 	my $sub_condition;
                   5712: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5713: 		&GDBM_READER(),0640)) {
                   5714: 	    $sub_condition=$bighash{'conditions'.$number};
                   5715: 	    untie(%bighash);
                   5716: 	}
                   5717: 	my $value = &docondval($sub_condition);
                   5718: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5719: 	return $value;
                   5720:     }
1.620     albertel 5721:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5722:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5723:     } else {
                   5724:        return 2;
                   5725:     }
                   5726: }
                   5727: 
1.713     albertel 5728: # get the collection of conditions for this resource
1.26      www      5729: sub condval {
                   5730:     my $condidx=shift;
1.54      www      5731:     my $allpathcond='';
1.713     albertel 5732:     foreach my $cond (split(/\|/,$condidx)) {
                   5733: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5734: 	    $allpathcond.=
                   5735: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5736: 	}
1.191     harris41 5737:     }
1.54      www      5738:     $allpathcond=~s/\|$//;
1.713     albertel 5739:     return &docondval($allpathcond);
                   5740: }
                   5741: 
                   5742: #evaluates an expression of conditions
                   5743: sub docondval {
                   5744:     my ($allpathcond) = @_;
                   5745:     my $result=0;
                   5746:     if ($env{'request.course.id'}
                   5747: 	&& defined($allpathcond)) {
                   5748: 	my $operand='|';
                   5749: 	my @stack;
                   5750: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5751: 	    if ($chunk eq '(') {
                   5752: 		push @stack,($operand,$result);
                   5753: 	    } elsif ($chunk eq ')') {
                   5754: 		my $before=pop @stack;
                   5755: 		if (pop @stack eq '&') {
                   5756: 		    $result=$result>$before?$before:$result;
                   5757: 		} else {
                   5758: 		    $result=$result>$before?$result:$before;
                   5759: 		}
                   5760: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5761: 		$operand=$chunk;
                   5762: 	    } else {
                   5763: 		my $new=directcondval($chunk);
                   5764: 		if ($operand eq '&') {
                   5765: 		    $result=$result>$new?$new:$result;
                   5766: 		} else {
                   5767: 		    $result=$result>$new?$result:$new;
                   5768: 		}
                   5769: 	    }
                   5770: 	}
1.26      www      5771:     }
                   5772:     return $result;
1.421     albertel 5773: }
                   5774: 
                   5775: # ---------------------------------------------------- Devalidate courseresdata
                   5776: 
                   5777: sub devalidatecourseresdata {
                   5778:     my ($coursenum,$coursedomain)=@_;
                   5779:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5780:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5781: }
                   5782: 
1.763     www      5783: 
1.200     www      5784: # --------------------------------------------------- Course Resourcedata Query
                   5785: 
1.624     albertel 5786: sub get_courseresdata {
                   5787:     my ($coursenum,$coursedomain)=@_;
1.200     www      5788:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5789:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5790:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5791:     my %dumpreply;
1.417     albertel 5792:     unless (defined($cached)) {
1.624     albertel 5793: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5794: 	$result=\%dumpreply;
1.251     albertel 5795: 	my ($tmp) = keys(%dumpreply);
                   5796: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5797: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5798: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5799: 	    return $tmp;
1.416     albertel 5800: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5801: 	    $result=undef;
1.599     albertel 5802: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5803: 	}
                   5804:     }
1.624     albertel 5805:     return $result;
                   5806: }
                   5807: 
1.633     albertel 5808: sub devalidateuserresdata {
                   5809:     my ($uname,$udom)=@_;
                   5810:     my $hashid="$udom:$uname";
                   5811:     &devalidate_cache_new('userres',$hashid);
                   5812: }
                   5813: 
1.624     albertel 5814: sub get_userresdata {
                   5815:     my ($uname,$udom)=@_;
                   5816:     #most student don\'t have any data set, check if there is some data
                   5817:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5818: 
                   5819:     my $hashid="$udom:$uname";
                   5820:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5821:     if (!defined($cached)) {
                   5822: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5823: 	$result=\%resourcedata;
                   5824: 	&do_cache_new('userres',$hashid,$result,600);
                   5825:     }
                   5826:     my ($tmp)=keys(%$result);
                   5827:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5828: 	return $result;
                   5829:     }
                   5830:     #error 2 occurs when the .db doesn't exist
                   5831:     if ($tmp!~/error: 2 /) {
1.672     albertel 5832: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5833: 		 " Trying to get resource data for ".
                   5834: 		 $uname." at ".$udom.": ".
                   5835: 		 $tmp."</font>");
                   5836:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5837: 	#&EXT_cache_set($udom,$uname);
                   5838: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5839: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5840:     }
                   5841:     return $tmp;
                   5842: }
                   5843: 
                   5844: sub resdata {
                   5845:     my ($name,$domain,$type,@which)=@_;
                   5846:     my $result;
                   5847:     if ($type eq 'course') {
                   5848: 	$result=&get_courseresdata($name,$domain);
                   5849:     } elsif ($type eq 'user') {
                   5850: 	$result=&get_userresdata($name,$domain);
                   5851:     }
                   5852:     if (!ref($result)) { return $result; }    
1.251     albertel 5853:     foreach my $item (@which) {
1.417     albertel 5854: 	if (defined($result->{$item})) {
                   5855: 	    return $result->{$item};
1.251     albertel 5856: 	}
1.250     albertel 5857:     }
1.291     albertel 5858:     return undef;
1.200     www      5859: }
                   5860: 
1.379     matthew  5861: #
                   5862: # EXT resource caching routines
                   5863: #
                   5864: 
                   5865: sub clear_EXT_cache_status {
1.383     albertel 5866:     &delenv('cache.EXT.');
1.379     matthew  5867: }
                   5868: 
                   5869: sub EXT_cache_status {
                   5870:     my ($target_domain,$target_user) = @_;
1.383     albertel 5871:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5872:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5873:         # We know already the user has no data
                   5874:         return 1;
                   5875:     } else {
                   5876:         return 0;
                   5877:     }
                   5878: }
                   5879: 
                   5880: sub EXT_cache_set {
                   5881:     my ($target_domain,$target_user) = @_;
1.383     albertel 5882:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5883:     #&appenv($cachename => time);
1.379     matthew  5884: }
                   5885: 
1.28      www      5886: # --------------------------------------------------------- Value of a Variable
1.58      www      5887: sub EXT {
1.715     albertel 5888: 
1.395     albertel 5889:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5890:     unless ($varname) { return ''; }
1.218     albertel 5891:     #get real user name/domain, courseid and symb
                   5892:     my $courseid;
1.359     albertel 5893:     my $publicuser;
1.427     www      5894:     if ($symbparm) {
                   5895: 	$symbparm=&get_symb_from_alias($symbparm);
                   5896:     }
1.218     albertel 5897:     if (!($uname && $udom)) {
1.790     albertel 5898:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5899:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5900:     } else {
1.620     albertel 5901: 	$courseid=$env{'request.course.id'};
1.218     albertel 5902:     }
1.48      www      5903:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5904:     my $rest;
1.320     albertel 5905:     if (defined($therest[0])) {
1.48      www      5906:        $rest=join('.',@therest);
                   5907:     } else {
                   5908:        $rest='';
                   5909:     }
1.320     albertel 5910: 
1.57      www      5911:     my $qualifierrest=$qualifier;
                   5912:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5913:     my $spacequalifierrest=$space;
                   5914:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5915:     if ($realm eq 'user') {
1.48      www      5916: # --------------------------------------------------------------- user.resource
                   5917: 	if ($space eq 'resource') {
1.651     albertel 5918: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5919: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5920: 		 &&
1.744     albertel 5921: 		 ($symbparm eq &symbread()) ) {	
                   5922: 		# if we are in the middle of processing the resource the
                   5923: 		# get the value we are planning on committing
                   5924:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5925:                     return $Apache::lonhomework::results{$qualifierrest};
                   5926:                 } else {
                   5927:                     return $Apache::lonhomework::history{$qualifierrest};
                   5928:                 }
1.335     albertel 5929: 	    } else {
1.359     albertel 5930: 		my %restored;
1.620     albertel 5931: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5932: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5933: 		} else {
                   5934: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5935: 		}
1.335     albertel 5936: 		return $restored{$qualifierrest};
                   5937: 	    }
1.48      www      5938: # ----------------------------------------------------------------- user.access
                   5939:         } elsif ($space eq 'access') {
1.218     albertel 5940: 	    # FIXME - not supporting calls for a specific user
1.48      www      5941:             return &allowed($qualifier,$rest);
                   5942: # ------------------------------------------ user.preferences, user.environment
                   5943:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5944: 	    if (($uname eq $env{'user.name'}) &&
                   5945: 		($udom eq $env{'user.domain'})) {
                   5946: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5947: 	    } else {
1.359     albertel 5948: 		my %returnhash;
                   5949: 		if (!$publicuser) {
                   5950: 		    %returnhash=&userenvironment($udom,$uname,
                   5951: 						 $qualifierrest);
                   5952: 		}
1.218     albertel 5953: 		return $returnhash{$qualifierrest};
                   5954: 	    }
1.48      www      5955: # ----------------------------------------------------------------- user.course
                   5956:         } elsif ($space eq 'course') {
1.218     albertel 5957: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5958:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5959: # ------------------------------------------------------------------- user.role
                   5960:         } elsif ($space eq 'role') {
1.218     albertel 5961: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5962:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5963:             if ($qualifier eq 'value') {
                   5964: 		return $role;
                   5965:             } elsif ($qualifier eq 'extent') {
                   5966:                 return $where;
                   5967:             }
                   5968: # ----------------------------------------------------------------- user.domain
                   5969:         } elsif ($space eq 'domain') {
1.218     albertel 5970:             return $udom;
1.48      www      5971: # ------------------------------------------------------------------- user.name
                   5972:         } elsif ($space eq 'name') {
1.218     albertel 5973:             return $uname;
1.48      www      5974: # ---------------------------------------------------- Any other user namespace
1.29      www      5975:         } else {
1.359     albertel 5976: 	    my %reply;
                   5977: 	    if (!$publicuser) {
                   5978: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5979: 	    }
                   5980: 	    return $reply{$qualifierrest};
1.48      www      5981:         }
1.236     www      5982:     } elsif ($realm eq 'query') {
                   5983: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5984:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5985: 						[$spacequalifierrest]);
1.620     albertel 5986: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5987:    } elsif ($realm eq 'request') {
1.48      www      5988: # ------------------------------------------------------------- request.browser
                   5989:         if ($space eq 'browser') {
1.430     www      5990: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5991: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5992: 		    return 1;
                   5993: 		} else {
                   5994: 		    return 0;
                   5995: 		}
                   5996: 	    } else {
1.620     albertel 5997: 		return $env{'browser.'.$qualifier};
1.430     www      5998: 	    }
1.57      www      5999: # ------------------------------------------------------------ request.filename
                   6000:         } else {
1.620     albertel 6001:             return $env{'request.'.$spacequalifierrest};
1.29      www      6002:         }
1.28      www      6003:     } elsif ($realm eq 'course') {
1.48      www      6004: # ---------------------------------------------------------- course.description
1.620     albertel 6005:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6006:     } elsif ($realm eq 'resource') {
1.165     www      6007: 
1.620     albertel 6008: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6009: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6010: 	}
1.693     albertel 6011: 
                   6012: 	if ($space eq 'title') {
                   6013: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6014: 	    return &gettitle($symbparm);
                   6015: 	}
                   6016: 	
                   6017: 	if ($space eq 'map') {
                   6018: 	    my ($map) = &decode_symb($symbparm);
                   6019: 	    return &symbread($map);
                   6020: 	}
                   6021: 
                   6022: 	my ($section, $group, @groups);
1.593     albertel 6023: 	my ($courselevelm,$courselevel);
1.539     albertel 6024: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6025: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6026: 
1.218     albertel 6027: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6028: 
1.60      www      6029: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6030: 	    my $symbp=$symbparm;
1.735     albertel 6031: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6032: 
                   6033: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6034: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6035: 
1.620     albertel 6036: 	    if (($env{'user.name'} eq $uname) &&
                   6037: 		($env{'user.domain'} eq $udom)) {
                   6038: 		$section=$env{'request.course.sec'};
1.733     raeburn  6039:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6040:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6041: 	    } else {
1.539     albertel 6042: 		if (! defined($usection)) {
1.551     albertel 6043: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6044: 		} else {
                   6045: 		    $section = $usection;
                   6046: 		}
1.733     raeburn  6047:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6048: 	    }
                   6049: 
                   6050: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6051: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6052: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6053: 
1.593     albertel 6054: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6055: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6056: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6057: 
1.60      www      6058: # ----------------------------------------------------------- first, check user
1.624     albertel 6059: 
                   6060: 	    my $userreply=&resdata($uname,$udom,'user',
                   6061: 				       ($courselevelr,$courselevelm,
                   6062: 					$courselevel));
                   6063: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6064: 
1.594     albertel 6065: # ------------------------------------------------ second, check some of course
1.684     raeburn  6066:             my $coursereply;
1.691     raeburn  6067:             if (@groups > 0) {
                   6068:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6069:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6070:                 if (defined($coursereply)) { return $coursereply; }
                   6071:             }
1.96      www      6072: 
1.684     raeburn  6073: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6074: 				     $env{'course.'.$courseid.'.domain'},
                   6075: 				     'course',
                   6076: 				     ($seclevelr,$seclevelm,$seclevel,
                   6077: 				      $courselevelr));
1.287     albertel 6078: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6079: 
1.60      www      6080: # ------------------------------------------------------ third, check map parms
1.218     albertel 6081: 	    my %parmhash=();
                   6082: 	    my $thisparm='';
                   6083: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6084: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6085: 		    &GDBM_READER(),0640)) {
1.218     albertel 6086: 		$thisparm=$parmhash{$symbparm};
                   6087: 		untie(%parmhash);
                   6088: 	    }
                   6089: 	    if ($thisparm) { return $thisparm; }
                   6090: 	}
1.594     albertel 6091: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6092: 
1.218     albertel 6093: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6094: 	my $filename;
                   6095: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6096: 	if ($symbparm) {
1.409     www      6097: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6098: 	} else {
1.620     albertel 6099: 	    $filename=$env{'request.filename'};
1.282     albertel 6100: 	}
                   6101: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6102: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6103: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6104: 	if (defined($metadata)) { return $metadata; }
1.142     www      6105: 
1.594     albertel 6106: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6107: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6108: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6109: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6110: 				     $env{'course.'.$courseid.'.domain'},
                   6111: 				     'course',
                   6112: 				     ($courselevelm,$courselevel));
1.593     albertel 6113: 	    if (defined($coursereply)) { return $coursereply; }
                   6114: 	}
1.145     www      6115: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6116: 	unless ($space eq '0') {
1.336     albertel 6117: 	    my @parts=split(/_/,$space);
                   6118: 	    my $id=pop(@parts);
                   6119: 	    my $part=join('_',@parts);
                   6120: 	    if ($part eq '') { $part='0'; }
                   6121: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6122: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6123: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6124: 	}
1.395     albertel 6125: 	if ($recurse) { return undef; }
                   6126: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6127: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6128: 
1.48      www      6129: # ---------------------------------------------------- Any other user namespace
                   6130:     } elsif ($realm eq 'environment') {
                   6131: # ----------------------------------------------------------------- environment
1.620     albertel 6132: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6133: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6134: 	} else {
1.770     albertel 6135: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6136: 		return '';
                   6137: 	    }
1.219     albertel 6138: 	    my %returnhash=&userenvironment($udom,$uname,
                   6139: 					    $spacequalifierrest);
                   6140: 	    return $returnhash{$spacequalifierrest};
                   6141: 	}
1.28      www      6142:     } elsif ($realm eq 'system') {
1.48      www      6143: # ----------------------------------------------------------------- system.time
                   6144: 	if ($space eq 'time') {
                   6145: 	    return time;
                   6146:         }
1.696     albertel 6147:     } elsif ($realm eq 'server') {
                   6148: # ----------------------------------------------------------------- system.time
                   6149: 	if ($space eq 'name') {
                   6150: 	    return $ENV{'SERVER_NAME'};
                   6151:         }
1.28      www      6152:     }
1.48      www      6153:     return '';
1.61      www      6154: }
                   6155: 
1.691     raeburn  6156: sub check_group_parms {
                   6157:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6158:     my @groupitems = ();
                   6159:     my $resultitem;
                   6160:     my @levels = ($symbparm,$mapparm,$what);
                   6161:     foreach my $group (@{$groups}) {
                   6162:         foreach my $level (@levels) {
                   6163:              my $item = $courseid.'.['.$group.'].'.$level;
                   6164:              push(@groupitems,$item);
                   6165:         }
                   6166:     }
                   6167:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6168:                             $env{'course.'.$courseid.'.domain'},
                   6169:                                      'course',@groupitems);
                   6170:     return $coursereply;
                   6171: }
                   6172: 
                   6173: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6174:     my ($courseid,@groups) = @_;
                   6175:     @groups = sort(@groups);
1.691     raeburn  6176:     return @groups;
                   6177: }
                   6178: 
1.395     albertel 6179: sub packages_tab_default {
                   6180:     my ($uri,$varname)=@_;
                   6181:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6182: 
                   6183:     my (@extension,@specifics,$do_default);
                   6184:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6185: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6186: 	if ($pack_type eq 'default') {
                   6187: 	    $do_default=1;
                   6188: 	} elsif ($pack_type eq 'extension') {
                   6189: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6190: 	} else {
                   6191: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6192: 	}
                   6193:     }
                   6194:     # first look for a package that matches the requested part id
                   6195:     foreach my $package (@specifics) {
                   6196: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6197: 	next if ($pack_part ne $part);
                   6198: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6199: 	    return $packagetab{"$pack_type&$name&default"};
                   6200: 	}
                   6201:     }
                   6202:     # look for any possible matching non extension_ package
                   6203:     foreach my $package (@specifics) {
                   6204: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6205: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6206: 	    return $packagetab{"$pack_type&$name&default"};
                   6207: 	}
1.585     albertel 6208: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6209: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6210: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6211: 	}
                   6212:     }
1.738     albertel 6213:     # look for any posible extension_ match
                   6214:     foreach my $package (@extension) {
                   6215: 	my ($package,$pack_type)=@{$package};
                   6216: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6217: 	    return $packagetab{"$pack_type&$name&default"};
                   6218: 	}
                   6219: 	if (defined($packagetab{$package."&$name&default"})) {
                   6220: 	    return $packagetab{$package."&$name&default"};
                   6221: 	}
                   6222:     }
                   6223:     # look for a global default setting
                   6224:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6225: 	return $packagetab{"default&$name&default"};
                   6226:     }
1.395     albertel 6227:     return undef;
                   6228: }
                   6229: 
1.334     albertel 6230: sub add_prefix_and_part {
                   6231:     my ($prefix,$part)=@_;
                   6232:     my $keyroot;
                   6233:     if (defined($prefix) && $prefix !~ /^__/) {
                   6234: 	# prefix that has a part already
                   6235: 	$keyroot=$prefix;
                   6236:     } elsif (defined($prefix)) {
                   6237: 	# prefix that is missing a part
                   6238: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6239:     } else {
                   6240: 	# no prefix at all
                   6241: 	if (defined($part)) { $keyroot='_'.$part; }
                   6242:     }
                   6243:     return $keyroot;
                   6244: }
                   6245: 
1.71      www      6246: # ---------------------------------------------------------------- Get metadata
                   6247: 
1.599     albertel 6248: my %metaentry;
1.71      www      6249: sub metadata {
1.176     www      6250:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6251:     $uri=&declutter($uri);
1.288     albertel 6252:     # if it is a non metadata possible uri return quickly
1.529     albertel 6253:     if (($uri eq '') || 
                   6254: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6255: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6256:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6257: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6258: 	return undef;
1.288     albertel 6259:     }
1.73      www      6260:     my $filename=$uri;
                   6261:     $uri=~s/\.meta$//;
1.172     www      6262: #
                   6263: # Is the metadata already cached?
1.177     www      6264: # Look at timestamp of caching
1.172     www      6265: # Everything is cached by the main uri, libraries are never directly cached
                   6266: #
1.428     albertel 6267:     if (!defined($liburi)) {
1.599     albertel 6268: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6269: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6270:     }
                   6271:     {
1.172     www      6272: #
                   6273: # Is this a recursive call for a library?
                   6274: #
1.599     albertel 6275: #	if (! exists($metacache{$uri})) {
                   6276: #	    $metacache{$uri}={};
                   6277: #	}
1.171     www      6278:         if ($liburi) {
                   6279: 	    $liburi=&declutter($liburi);
                   6280:             $filename=$liburi;
1.401     bowersj2 6281:         } else {
1.599     albertel 6282: 	    &devalidate_cache_new('meta',$uri);
                   6283: 	    undef(%metaentry);
1.401     bowersj2 6284: 	}
1.140     www      6285:         my %metathesekeys=();
1.73      www      6286:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6287: 	my $metastring;
1.768     albertel 6288: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6289: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6290: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6291: 	    $metastring=&getfile($file);
1.489     albertel 6292: 	}
1.208     albertel 6293:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6294:         my $token;
1.140     www      6295:         undef %metathesekeys;
1.71      www      6296:         while ($token=$parser->get_token) {
1.339     albertel 6297: 	    if ($token->[0] eq 'S') {
                   6298: 		if (defined($token->[2]->{'package'})) {
1.172     www      6299: #
                   6300: # This is a package - get package info
                   6301: #
1.339     albertel 6302: 		    my $package=$token->[2]->{'package'};
                   6303: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6304: 		    if (defined($token->[2]->{'id'})) { 
                   6305: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6306: 		    }
1.599     albertel 6307: 		    if ($metaentry{':packages'}) {
                   6308: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6309: 		    } else {
1.599     albertel 6310: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6311: 		    }
1.736     albertel 6312: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6313: 			my $part=$keyroot;
                   6314: 			$part=~s/^\_//;
1.736     albertel 6315: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6316: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6317: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6318: 			    # ignore package.tab specified default values
                   6319:                             # here &package_tab_default() will fetch those
                   6320: 			    if ($subp eq 'default') { next; }
1.736     albertel 6321: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6322: 			    my $unikey;
                   6323: 			    if ($pack =~ /_0$/) {
                   6324: 				$unikey='parameter_0_'.$name;
                   6325: 				$part=0;
                   6326: 			    } else {
                   6327: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6328: 			    }
1.339     albertel 6329: 			    if ($subp eq 'display') {
                   6330: 				$value.=' [Part: '.$part.']';
                   6331: 			    }
1.599     albertel 6332: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6333: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6334: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6335: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6336: 			    }
1.599     albertel 6337: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6338: 				$metaentry{':'.$unikey}=
                   6339: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6340: 			    }
1.339     albertel 6341: 			}
                   6342: 		    }
                   6343: 		} else {
1.172     www      6344: #
                   6345: # This is not a package - some other kind of start tag
1.339     albertel 6346: #
                   6347: 		    my $entry=$token->[1];
                   6348: 		    my $unikey;
                   6349: 		    if ($entry eq 'import') {
                   6350: 			$unikey='';
                   6351: 		    } else {
                   6352: 			$unikey=$entry;
                   6353: 		    }
                   6354: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6355: 
                   6356: 		    if (defined($token->[2]->{'id'})) { 
                   6357: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6358: 		    }
1.175     www      6359: 
1.339     albertel 6360: 		    if ($entry eq 'import') {
1.175     www      6361: #
                   6362: # Importing a library here
1.339     albertel 6363: #
                   6364: 			if ($depthcount<20) {
                   6365: 			    my $location=$parser->get_text('/import');
                   6366: 			    my $dir=$filename;
                   6367: 			    $dir=~s|[^/]*$||;
                   6368: 			    $location=&filelocation($dir,$location);
1.736     albertel 6369: 			    my $metadata = 
                   6370: 				&metadata($uri,'keys', $location,$unikey,
                   6371: 					  $depthcount+1);
                   6372: 			    foreach my $meta (split(',',$metadata)) {
                   6373: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6374: 				$metathesekeys{$meta}=1;
1.339     albertel 6375: 			    }
                   6376: 			}
                   6377: 		    } else { 
                   6378: 			
                   6379: 			if (defined($token->[2]->{'name'})) { 
                   6380: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6381: 			}
                   6382: 			$metathesekeys{$unikey}=1;
1.736     albertel 6383: 			foreach my $param (@{$token->[3]}) {
                   6384: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6385: 				$token->[2]->{$param};
1.339     albertel 6386: 			}
                   6387: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6388: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6389: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6390: 		 # only ws inside the tag, and not in default, so use default
                   6391: 		 # as value
1.599     albertel 6392: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6393: 			} else {
1.321     albertel 6394: 		  # either something interesting inside the tag or default
                   6395:                   # uninteresting
1.599     albertel 6396: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6397: 			}
1.172     www      6398: # end of not-a-package not-a-library import
1.339     albertel 6399: 		    }
1.172     www      6400: # end of not-a-package start tag
1.339     albertel 6401: 		}
1.172     www      6402: # the next is the end of "start tag"
1.339     albertel 6403: 	    }
                   6404: 	}
1.483     albertel 6405: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6406: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6407: 	    #no specific packages #how's our extension
                   6408: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6409: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6410: 					 \%metathesekeys);
                   6411: 	}
1.599     albertel 6412: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6413: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6414: 		#no specific packages well let's get default then
                   6415: 		if ($key!~/^default&/) { next; }
1.488     albertel 6416: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6417: 					     \%metathesekeys);
                   6418: 	    }
                   6419: 	}
1.338     www      6420: # are there custom rights to evaluate
1.599     albertel 6421: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6422: 
1.338     www      6423:     #
                   6424:     # Importing a rights file here
1.339     albertel 6425:     #
                   6426: 	    unless ($depthcount) {
1.599     albertel 6427: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6428: 		my $dir=$filename;
                   6429: 		$dir=~s|[^/]*$||;
                   6430: 		$location=&filelocation($dir,$location);
1.736     albertel 6431: 		my $rights_metadata =
                   6432: 		    &metadata($uri,'keys',$location,'_rights',
                   6433: 			      $depthcount+1);
                   6434: 		foreach my $rights (split(',',$rights_metadata)) {
                   6435: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6436: 		    $metathesekeys{$rights}=1;
1.339     albertel 6437: 		}
                   6438: 	    }
                   6439: 	}
1.737     albertel 6440: 	# uniqifiy package listing
                   6441: 	my %seen;
                   6442: 	my @uniq_packages =
                   6443: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6444: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6445: 
                   6446: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6447: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6448: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6449: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6450: # this is the end of "was not already recently cached
1.71      www      6451:     }
1.599     albertel 6452:     return $metaentry{':'.$what};
1.261     albertel 6453: }
                   6454: 
1.488     albertel 6455: sub metadata_create_package_def {
1.483     albertel 6456:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6457:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6458:     if ($subp eq 'default') { next; }
                   6459:     
1.599     albertel 6460:     if (defined($metaentry{':packages'})) {
                   6461: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6462:     } else {
1.599     albertel 6463: 	$metaentry{':packages'}=$package;
1.483     albertel 6464:     }
                   6465:     my $value=$packagetab{$key};
                   6466:     my $unikey;
                   6467:     $unikey='parameter_0_'.$name;
1.599     albertel 6468:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6469:     $$metathesekeys{$unikey}=1;
1.599     albertel 6470:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6471: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6472:     }
1.599     albertel 6473:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6474: 	$metaentry{':'.$unikey}=
                   6475: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6476:     }
                   6477: }
                   6478: 
1.261     albertel 6479: sub metadata_generate_part0 {
                   6480:     my ($metadata,$metacache,$uri) = @_;
                   6481:     my %allnames;
1.737     albertel 6482:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6483: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6484: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6485: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6486: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6487: 	    $allnames{$name}=$part;
                   6488: 	  }
                   6489: 	}
                   6490:     }
                   6491:     foreach my $name (keys(%allnames)) {
                   6492:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6493:       my $key=":parameter_0_$name";
1.261     albertel 6494:       $$metacache{"$key.part"}='0';
                   6495:       $$metacache{"$key.name"}=$name;
1.428     albertel 6496:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6497: 					   $allnames{$name}.'_'.$name.
                   6498: 					   '.type'};
1.428     albertel 6499:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6500: 			     '.display'};
1.644     www      6501:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6502:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6503:       $$metacache{"$key.display"}=$olddis;
                   6504:     }
1.71      www      6505: }
                   6506: 
1.764     albertel 6507: # ------------------------------------------------------ Devalidate title cache
                   6508: 
                   6509: sub devalidate_title_cache {
                   6510:     my ($url)=@_;
                   6511:     if (!$env{'request.course.id'}) { return; }
                   6512:     my $symb=&symbread($url);
                   6513:     if (!$symb) { return; }
                   6514:     my $key=$env{'request.course.id'}."\0".$symb;
                   6515:     &devalidate_cache_new('title',$key);
                   6516: }
                   6517: 
1.301     www      6518: # ------------------------------------------------- Get the title of a resource
                   6519: 
                   6520: sub gettitle {
                   6521:     my $urlsymb=shift;
                   6522:     my $symb=&symbread($urlsymb);
1.534     albertel 6523:     if ($symb) {
1.620     albertel 6524: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6525: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6526: 	if (defined($cached)) { 
                   6527: 	    return $result;
                   6528: 	}
1.534     albertel 6529: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6530: 	my $title='';
                   6531: 	my %bighash;
1.620     albertel 6532: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6533: 		&GDBM_READER(),0640)) {
                   6534: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6535: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6536: 	    untie %bighash;
                   6537: 	}
                   6538: 	$title=~s/\&colon\;/\:/gs;
                   6539: 	if ($title) {
1.599     albertel 6540: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6541: 	}
                   6542: 	$urlsymb=$url;
                   6543:     }
                   6544:     my $title=&metadata($urlsymb,'title');
                   6545:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6546:     return $title;
1.301     www      6547: }
1.613     albertel 6548: 
1.614     albertel 6549: sub get_slot {
                   6550:     my ($which,$cnum,$cdom)=@_;
                   6551:     if (!$cnum || !$cdom) {
1.790     albertel 6552: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6553: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6554: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6555:     }
1.703     albertel 6556:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6557:     my %slotinfo;
                   6558:     if (exists($remembered{$key})) {
                   6559: 	$slotinfo{$which} = $remembered{$key};
                   6560:     } else {
                   6561: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6562: 	&Apache::lonhomework::showhash(%slotinfo);
                   6563: 	my ($tmp)=keys(%slotinfo);
                   6564: 	if ($tmp=~/^error:/) { return (); }
                   6565: 	$remembered{$key} = $slotinfo{$which};
                   6566:     }
1.616     albertel 6567:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6568: 	return %{$slotinfo{$which}};
                   6569:     }
                   6570:     return $slotinfo{$which};
1.614     albertel 6571: }
1.31      www      6572: # ------------------------------------------------- Update symbolic store links
                   6573: 
                   6574: sub symblist {
                   6575:     my ($mapname,%newhash)=@_;
1.438     www      6576:     $mapname=&deversion(&declutter($mapname));
1.31      www      6577:     my %hash;
1.620     albertel 6578:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6579:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6580:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6581: 	    foreach my $url (keys %newhash) {
                   6582: 		next if ($url eq 'last_known'
                   6583: 			 && $env{'form.no_update_last_known'});
                   6584: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6585: 						    $newhash{$url}->[1],
                   6586: 						    $newhash{$url}->[0]);
1.191     harris41 6587:             }
1.31      www      6588:             if (untie(%hash)) {
                   6589: 		return 'ok';
                   6590:             }
                   6591:         }
                   6592:     }
                   6593:     return 'error';
1.212     www      6594: }
                   6595: 
                   6596: # --------------------------------------------------------------- Verify a symb
                   6597: 
                   6598: sub symbverify {
1.510     www      6599:     my ($symb,$thisurl)=@_;
                   6600:     my $thisfn=$thisurl;
1.439     www      6601:     $thisfn=&declutter($thisfn);
1.215     www      6602: # direct jump to resource in page or to a sequence - will construct own symbs
                   6603:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6604: # check URL part
1.409     www      6605:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6606: 
1.431     www      6607:     unless ($url eq $thisfn) { return 0; }
1.213     www      6608: 
1.216     www      6609:     $symb=&symbclean($symb);
1.510     www      6610:     $thisurl=&deversion($thisurl);
1.439     www      6611:     $thisfn=&deversion($thisfn);
1.213     www      6612: 
                   6613:     my %bighash;
                   6614:     my $okay=0;
1.431     www      6615: 
1.620     albertel 6616:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6617:                             &GDBM_READER(),0640)) {
1.510     www      6618:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6619:         unless ($ids) { 
1.510     www      6620:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6621:         }
                   6622:         if ($ids) {
                   6623: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6624: 	    foreach my $id (split(/\,/,$ids)) {
                   6625: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6626:                if (
                   6627:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6628:    eq $symb) { 
1.620     albertel 6629: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6630: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6631: 		       $okay=1; 
                   6632: 		   }
                   6633: 	       }
1.216     www      6634: 	   }
                   6635:         }
1.213     www      6636: 	untie(%bighash);
                   6637:     }
                   6638:     return $okay;
1.31      www      6639: }
                   6640: 
1.210     www      6641: # --------------------------------------------------------------- Clean-up symb
                   6642: 
                   6643: sub symbclean {
                   6644:     my $symb=shift;
1.568     albertel 6645:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6646: # remove version from map
                   6647:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6648: 
1.210     www      6649: # remove version from URL
                   6650:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6651: 
1.507     www      6652: # remove wrapper
                   6653: 
1.510     www      6654:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6655:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6656:     return $symb;
1.409     www      6657: }
                   6658: 
                   6659: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6660: 
                   6661: sub encode_symb {
                   6662:     my ($map,$resid,$url)=@_;
                   6663:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6664: }
1.409     www      6665: 
                   6666: sub decode_symb {
1.568     albertel 6667:     my $symb=shift;
                   6668:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6669:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6670:     return (&fixversion($map),$resid,&fixversion($url));
                   6671: }
                   6672: 
                   6673: sub fixversion {
                   6674:     my $fn=shift;
1.609     banghart 6675:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6676:     my %bighash;
                   6677:     my $uri=&clutter($fn);
1.620     albertel 6678:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6679: # is this cached?
1.599     albertel 6680:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6681:     if (defined($cached)) { return $result; }
                   6682: # unfortunately not cached, or expired
1.620     albertel 6683:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6684: 	    &GDBM_READER(),0640)) {
                   6685:  	if ($bighash{'version_'.$uri}) {
                   6686:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6687:  	    unless (($version eq 'mostrecent') || 
                   6688: 		    ($version==&getversion($uri))) {
1.440     www      6689:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6690:  	    }
                   6691:  	}
                   6692:  	untie %bighash;
1.413     www      6693:     }
1.599     albertel 6694:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6695: }
                   6696: 
                   6697: sub deversion {
                   6698:     my $url=shift;
                   6699:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6700:     return $url;
1.210     www      6701: }
                   6702: 
1.31      www      6703: # ------------------------------------------------------ Return symb list entry
                   6704: 
                   6705: sub symbread {
1.249     www      6706:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6707:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6708:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6709: # no filename provided? try from environment
1.44      www      6710:     unless ($thisfn) {
1.620     albertel 6711:         if ($env{'request.symb'}) {
                   6712: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6713: 	}
1.620     albertel 6714: 	$thisfn=$env{'request.filename'};
1.44      www      6715:     }
1.569     albertel 6716:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6717: # is that filename actually a symb? Verify, clean, and return
                   6718:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6719: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6720: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6721: 	}
1.242     www      6722:     }
1.44      www      6723:     $thisfn=declutter($thisfn);
1.31      www      6724:     my %hash;
1.37      www      6725:     my %bighash;
                   6726:     my $syval='';
1.620     albertel 6727:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6728:         my $targetfn = $thisfn;
1.609     banghart 6729:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6730:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6731:         }
1.687     albertel 6732: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6733: 	    $targetfn=$1;
                   6734: 	}
1.620     albertel 6735:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6736:                       &GDBM_READER(),0640)) {
1.481     raeburn  6737: 	    $syval=$hash{$targetfn};
1.37      www      6738:             untie(%hash);
                   6739:         }
                   6740: # ---------------------------------------------------------- There was an entry
                   6741:         if ($syval) {
1.601     albertel 6742: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6743: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6744: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6745: 		    #return $env{$cache_str}='';
1.601     albertel 6746: 		#}    
                   6747: 		#$syval.=$1;
                   6748: 	    #}
1.37      www      6749:         } else {
                   6750: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6751:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6752:                             &GDBM_READER(),0640)) {
1.37      www      6753: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6754:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6755:               unless ($ids) { 
                   6756:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6757:               }
                   6758:               unless ($ids) {
                   6759: # alias?
                   6760: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6761:               }
1.37      www      6762:               if ($ids) {
                   6763: # ------------------------------------------------------------------- Has ID(s)
                   6764:                  my @possibilities=split(/\,/,$ids);
1.39      www      6765:                  if ($#possibilities==0) {
                   6766: # ----------------------------------------------- There is only one possibility
1.37      www      6767: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6768: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6769: 						    $resid,$thisfn);
1.249     www      6770:                  } elsif (!$donotrecurse) {
1.39      www      6771: # ------------------------------------------ There is more than one possibility
                   6772:                      my $realpossible=0;
1.800     albertel 6773:                      foreach my $id (@possibilities) {
                   6774: 			 my $file=$bighash{'src_'.$id};
1.39      www      6775:                          if (&allowed('bre',$file)) {
1.800     albertel 6776:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6777:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6778: 				$realpossible++;
1.626     albertel 6779:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6780: 						    $resid,$thisfn);
1.39      www      6781:                             }
                   6782: 			 }
1.191     harris41 6783:                      }
1.39      www      6784: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6785:                  } else {
                   6786:                      $syval='';
1.37      www      6787:                  }
                   6788: 	      }
                   6789:               untie(%bighash)
1.481     raeburn  6790:            }
1.31      www      6791:         }
1.62      www      6792:         if ($syval) {
1.620     albertel 6793: 	    return $env{$cache_str}=$syval;
1.62      www      6794:         }
1.31      www      6795:     }
1.44      www      6796:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6797:     return $env{$cache_str}='';
1.31      www      6798: }
                   6799: 
                   6800: # ---------------------------------------------------------- Return random seed
                   6801: 
1.32      www      6802: sub numval {
                   6803:     my $txt=shift;
                   6804:     $txt=~tr/A-J/0-9/;
                   6805:     $txt=~tr/a-j/0-9/;
                   6806:     $txt=~tr/K-T/0-9/;
                   6807:     $txt=~tr/k-t/0-9/;
                   6808:     $txt=~tr/U-Z/0-5/;
                   6809:     $txt=~tr/u-z/0-5/;
                   6810:     $txt=~s/\D//g;
1.564     albertel 6811:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6812:     return int($txt);
1.368     albertel 6813: }
                   6814: 
1.484     albertel 6815: sub numval2 {
                   6816:     my $txt=shift;
                   6817:     $txt=~tr/A-J/0-9/;
                   6818:     $txt=~tr/a-j/0-9/;
                   6819:     $txt=~tr/K-T/0-9/;
                   6820:     $txt=~tr/k-t/0-9/;
                   6821:     $txt=~tr/U-Z/0-5/;
                   6822:     $txt=~tr/u-z/0-5/;
                   6823:     $txt=~s/\D//g;
                   6824:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6825:     my $total;
                   6826:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6827:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6828:     return int($total);
                   6829: }
                   6830: 
1.575     albertel 6831: sub numval3 {
                   6832:     use integer;
                   6833:     my $txt=shift;
                   6834:     $txt=~tr/A-J/0-9/;
                   6835:     $txt=~tr/a-j/0-9/;
                   6836:     $txt=~tr/K-T/0-9/;
                   6837:     $txt=~tr/k-t/0-9/;
                   6838:     $txt=~tr/U-Z/0-5/;
                   6839:     $txt=~tr/u-z/0-5/;
                   6840:     $txt=~s/\D//g;
                   6841:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6842:     my $total;
                   6843:     foreach my $val (@txts) { $total+=$val; }
                   6844:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6845:     return $total;
                   6846: }
                   6847: 
1.675     albertel 6848: sub digest {
                   6849:     my ($data)=@_;
                   6850:     my $digest=&Digest::MD5::md5($data);
                   6851:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6852:     my ($e,$f);
                   6853:     {
                   6854:         use integer;
                   6855:         $e=($a+$b);
                   6856:         $f=($c+$d);
                   6857:         if ($_64bit) {
                   6858:             $e=(($e<<32)>>32);
                   6859:             $f=(($f<<32)>>32);
                   6860:         }
                   6861:     }
                   6862:     if (wantarray) {
                   6863: 	return ($e,$f);
                   6864:     } else {
                   6865: 	my $g;
                   6866: 	{
                   6867: 	    use integer;
                   6868: 	    $g=($e+$f);
                   6869: 	    if ($_64bit) {
                   6870: 		$g=(($g<<32)>>32);
                   6871: 	    }
                   6872: 	}
                   6873: 	return $g;
                   6874:     }
                   6875: }
                   6876: 
1.368     albertel 6877: sub latest_rnd_algorithm_id {
1.675     albertel 6878:     return '64bit5';
1.366     albertel 6879: }
1.32      www      6880: 
1.503     albertel 6881: sub get_rand_alg {
                   6882:     my ($courseid)=@_;
1.790     albertel 6883:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6884:     if ($courseid) {
1.620     albertel 6885: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6886:     }
                   6887:     return &latest_rnd_algorithm_id();
                   6888: }
                   6889: 
1.562     albertel 6890: sub validCODE {
                   6891:     my ($CODE)=@_;
                   6892:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6893:     return 0;
                   6894: }
                   6895: 
1.491     albertel 6896: sub getCODE {
1.620     albertel 6897:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6898:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6899: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6900: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6901: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6902:     }
                   6903:     return undef;
                   6904: }
                   6905: 
1.31      www      6906: sub rndseed {
1.155     albertel 6907:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6908: 
1.790     albertel 6909:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6910:     if (!$symb) {
1.366     albertel 6911: 	unless ($symb=$wsymb) { return time; }
                   6912:     }
                   6913:     if (!$courseid) { $courseid=$wcourseid; }
                   6914:     if (!$domain) { $domain=$wdomain; }
                   6915:     if (!$username) { $username=$wusername }
1.503     albertel 6916:     my $which=&get_rand_alg();
1.803     albertel 6917: 
1.491     albertel 6918:     if (defined(&getCODE())) {
1.675     albertel 6919: 	if ($which eq '64bit5') {
                   6920: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6921: 	} elsif ($which eq '64bit4') {
1.575     albertel 6922: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6923: 	} else {
                   6924: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6925: 	}
1.675     albertel 6926:     } elsif ($which eq '64bit5') {
                   6927: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6928:     } elsif ($which eq '64bit4') {
                   6929: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6930:     } elsif ($which eq '64bit3') {
                   6931: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6932:     } elsif ($which eq '64bit2') {
                   6933: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6934:     } elsif ($which eq '64bit') {
                   6935: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6936:     }
                   6937:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6938: }
                   6939: 
                   6940: sub rndseed_32bit {
                   6941:     my ($symb,$courseid,$domain,$username)=@_;
                   6942:     {
                   6943: 	use integer;
                   6944: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6945: 	my $symbseed=numval($symb) << 22;
                   6946: 	my $namechck=unpack("%32C*",$username) << 17;
                   6947: 	my $nameseed=numval($username) << 12;
                   6948: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6949: 	my $courseseed=unpack("%32C*",$courseid);
                   6950: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6951: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6952: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6953: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6954: 	return $num;
                   6955:     }
                   6956: }
                   6957: 
                   6958: sub rndseed_64bit {
                   6959:     my ($symb,$courseid,$domain,$username)=@_;
                   6960:     {
                   6961: 	use integer;
                   6962: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6963: 	my $symbseed=numval($symb) << 10;
                   6964: 	my $namechck=unpack("%32S*",$username);
                   6965: 	
                   6966: 	my $nameseed=numval($username) << 21;
                   6967: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6968: 	my $courseseed=unpack("%32S*",$courseid);
                   6969: 	
                   6970: 	my $num1=$symbchck+$symbseed+$namechck;
                   6971: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6972: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6973: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6974: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6975: 	return "$num1,$num2";
1.155     albertel 6976:     }
1.366     albertel 6977: }
                   6978: 
1.443     albertel 6979: sub rndseed_64bit2 {
                   6980:     my ($symb,$courseid,$domain,$username)=@_;
                   6981:     {
                   6982: 	use integer;
                   6983: 	# strings need to be an even # of cahracters long, it it is odd the
                   6984:         # last characters gets thrown away
                   6985: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6986: 	my $symbseed=numval($symb) << 10;
                   6987: 	my $namechck=unpack("%32S*",$username.' ');
                   6988: 	
                   6989: 	my $nameseed=numval($username) << 21;
1.501     albertel 6990: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6991: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6992: 	
                   6993: 	my $num1=$symbchck+$symbseed+$namechck;
                   6994: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6995: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6996: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6997: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6998: 	return "$num1,$num2";
                   6999:     }
                   7000: }
                   7001: 
                   7002: sub rndseed_64bit3 {
                   7003:     my ($symb,$courseid,$domain,$username)=@_;
                   7004:     {
                   7005: 	use integer;
                   7006: 	# strings need to be an even # of cahracters long, it it is odd the
                   7007:         # last characters gets thrown away
                   7008: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7009: 	my $symbseed=numval2($symb) << 10;
                   7010: 	my $namechck=unpack("%32S*",$username.' ');
                   7011: 	
                   7012: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7013: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7014: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7015: 	
                   7016: 	my $num1=$symbchck+$symbseed+$namechck;
                   7017: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7018: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7019: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7020: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7021: 	
1.503     albertel 7022: 	return "$num1:$num2";
1.443     albertel 7023:     }
                   7024: }
                   7025: 
1.575     albertel 7026: sub rndseed_64bit4 {
                   7027:     my ($symb,$courseid,$domain,$username)=@_;
                   7028:     {
                   7029: 	use integer;
                   7030: 	# strings need to be an even # of cahracters long, it it is odd the
                   7031:         # last characters gets thrown away
                   7032: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7033: 	my $symbseed=numval3($symb) << 10;
                   7034: 	my $namechck=unpack("%32S*",$username.' ');
                   7035: 	
                   7036: 	my $nameseed=numval3($username) << 21;
                   7037: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7038: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7039: 	
                   7040: 	my $num1=$symbchck+$symbseed+$namechck;
                   7041: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7042: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7043: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7044: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7045: 	
                   7046: 	return "$num1:$num2";
                   7047:     }
                   7048: }
                   7049: 
1.675     albertel 7050: sub rndseed_64bit5 {
                   7051:     my ($symb,$courseid,$domain,$username)=@_;
                   7052:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7053:     return "$num1:$num2";
                   7054: }
                   7055: 
1.366     albertel 7056: sub rndseed_CODE_64bit {
                   7057:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7058:     {
1.366     albertel 7059: 	use integer;
1.443     albertel 7060: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7061: 	my $symbseed=numval2($symb);
1.491     albertel 7062: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7063: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7064: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7065: 	my $num1=$symbseed+$CODEchck;
                   7066: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7067: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7068: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7069: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7070: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7071: 	return "$num1:$num2";
1.366     albertel 7072:     }
                   7073: }
                   7074: 
1.575     albertel 7075: sub rndseed_CODE_64bit4 {
                   7076:     my ($symb,$courseid,$domain,$username)=@_;
                   7077:     {
                   7078: 	use integer;
                   7079: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7080: 	my $symbseed=numval3($symb);
                   7081: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7082: 	my $CODEseed=numval3(&getCODE());
                   7083: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7084: 	my $num1=$symbseed+$CODEchck;
                   7085: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7086: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7087: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7088: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7089: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7090: 	return "$num1:$num2";
                   7091:     }
                   7092: }
                   7093: 
1.675     albertel 7094: sub rndseed_CODE_64bit5 {
                   7095:     my ($symb,$courseid,$domain,$username)=@_;
                   7096:     my $code = &getCODE();
                   7097:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7098:     return "$num1:$num2";
                   7099: }
                   7100: 
1.366     albertel 7101: sub setup_random_from_rndseed {
                   7102:     my ($rndseed)=@_;
1.503     albertel 7103:     if ($rndseed =~/([,:])/) {
                   7104: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7105: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7106:     } else {
                   7107: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7108:     }
1.36      albertel 7109: }
                   7110: 
1.474     albertel 7111: sub latest_receipt_algorithm_id {
1.835     albertel 7112:     return 'receipt3';
1.474     albertel 7113: }
                   7114: 
1.480     www      7115: sub recunique {
                   7116:     my $fucourseid=shift;
                   7117:     my $unique;
1.835     albertel 7118:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7119: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7120: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7121:     } else {
                   7122: 	$unique=$perlvar{'lonReceipt'};
                   7123:     }
                   7124:     return unpack("%32C*",$unique);
                   7125: }
                   7126: 
                   7127: sub recprefix {
                   7128:     my $fucourseid=shift;
                   7129:     my $prefix;
1.835     albertel 7130:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7131: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7132: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7133:     } else {
                   7134: 	$prefix=$perlvar{'lonHostID'};
                   7135:     }
                   7136:     return unpack("%32C*",$prefix);
                   7137: }
                   7138: 
1.76      www      7139: sub ireceipt {
1.474     albertel 7140:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7141: 
                   7142:     my $return =&recprefix($fucourseid).'-';
                   7143: 
                   7144:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7145: 	$env{'request.state'} eq 'construct') {
                   7146: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7147: 	return $return;
                   7148:     }
                   7149: 
1.76      www      7150:     my $cuname=unpack("%32C*",$funame);
                   7151:     my $cudom=unpack("%32C*",$fudom);
                   7152:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7153:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7154:     my $cunique=&recunique($fucourseid);
1.474     albertel 7155:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7156:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7157: 
1.790     albertel 7158: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7159: 			       
                   7160: 	$return.= ($cunique%$cuname+
                   7161: 		   $cunique%$cudom+
                   7162: 		   $cusymb%$cuname+
                   7163: 		   $cusymb%$cudom+
                   7164: 		   $cucourseid%$cuname+
                   7165: 		   $cucourseid%$cudom+
                   7166: 		   $cpart%$cuname+
                   7167: 		   $cpart%$cudom);
                   7168:     } else {
                   7169: 	$return.= ($cunique%$cuname+
                   7170: 		   $cunique%$cudom+
                   7171: 		   $cusymb%$cuname+
                   7172: 		   $cusymb%$cudom+
                   7173: 		   $cucourseid%$cuname+
                   7174: 		   $cucourseid%$cudom);
                   7175:     }
                   7176:     return $return;
1.76      www      7177: }
                   7178: 
                   7179: sub receipt {
1.474     albertel 7180:     my ($part)=@_;
1.790     albertel 7181:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7182:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7183: }
1.260     ng       7184: 
1.790     albertel 7185: sub whichuser {
                   7186:     my ($passedsymb)=@_;
                   7187:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7188:     if (defined($env{'form.grade_symb'})) {
                   7189: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7190: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7191: 	if (!$allowed &&
                   7192: 	    exists($env{'request.course.sec'}) &&
                   7193: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7194: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7195: 			      '/'.$env{'request.course.sec'});
                   7196: 	}
                   7197: 	if ($allowed) {
                   7198: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7199: 	    $courseid=$tmp_courseid;
                   7200: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7201: 	    ($name)=&get_env_multiple('form.grade_username');
                   7202: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7203: 	}
                   7204:     }
                   7205:     if (!$passedsymb) {
                   7206: 	$symb=&symbread();
                   7207:     } else {
                   7208: 	$symb=$passedsymb;
                   7209:     }
                   7210:     $courseid=$env{'request.course.id'};
                   7211:     $domain=$env{'user.domain'};
                   7212:     $name=$env{'user.name'};
                   7213:     if ($name eq 'public' && $domain eq 'public') {
                   7214: 	if (!defined($env{'form.username'})) {
                   7215: 	    $env{'form.username'}.=time.rand(10000000);
                   7216: 	}
                   7217: 	$name.=$env{'form.username'};
                   7218:     }
                   7219:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7220: 
                   7221: }
                   7222: 
1.36      albertel 7223: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7224: # returns either the contents of the file or 
                   7225: # -1 if the file doesn't exist
1.481     raeburn  7226: #
                   7227: # if the target is a file that was uploaded via DOCS, 
                   7228: # a check will be made to see if a current copy exists on the local server,
                   7229: # if it does this will be served, otherwise a copy will be retrieved from
                   7230: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7231: # the local server.   
1.472     albertel 7232: 
1.36      albertel 7233: sub getfile {
1.538     albertel 7234:     my ($file) = @_;
1.609     banghart 7235:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7236:     &repcopy($file);
                   7237:     return &readfile($file);
                   7238: }
                   7239: 
                   7240: sub repcopy_userfile {
                   7241:     my ($file)=@_;
1.609     banghart 7242:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7243:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7244:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7245: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7246:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7247:     if (-e "$file") {
1.828     www      7248: # we already have a local copy, check it out
1.538     albertel 7249: 	my @fileinfo = stat($file);
1.828     www      7250: 	my $rtncode;
                   7251: 	my $info;
1.538     albertel 7252: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7253: 	if ($lwpresp ne 'ok') {
1.828     www      7254: # there is no such file anymore, even though we had a local copy
1.482     albertel 7255: 	    if ($rtncode eq '404') {
1.538     albertel 7256: 		unlink($file);
1.482     albertel 7257: 	    }
                   7258: 	    return -1;
                   7259: 	}
                   7260: 	if ($info < $fileinfo[9]) {
1.828     www      7261: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7262: 	    return 'ok';
1.828     www      7263: 	} else {
                   7264: # the file is outdated, get rid of it
                   7265: 	    unlink($file);
1.482     albertel 7266: 	}
1.828     www      7267:     }
                   7268: # one way or the other, at this point, we don't have the file
                   7269: # construct the correct path for the file
                   7270:     my @parts = ($cdom,$cnum); 
                   7271:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7272: 	push @parts, split(/\//,$1);
                   7273:     }
                   7274:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7275:     foreach my $part (@parts) {
                   7276: 	$path .= '/'.$part;
                   7277: 	if (!-e $path) {
                   7278: 	    mkdir($path,0770);
1.482     albertel 7279: 	}
                   7280:     }
1.828     www      7281: # now the path exists for sure
                   7282: # get a user agent
                   7283:     my $ua=new LWP::UserAgent;
                   7284:     my $transferfile=$file.'.in.transfer';
                   7285: # FIXME: this should flock
                   7286:     if (-e $transferfile) { return 'ok'; }
                   7287:     my $request;
                   7288:     $uri=~s/^\///;
1.829     www      7289:     $request=new HTTP::Request('GET','http://'.$hostname{&homeserver($cnum,$cdom)}.'/raw/'.$uri);
1.828     www      7290:     my $response=$ua->request($request,$transferfile);
                   7291: # did it work?
                   7292:     if ($response->is_error()) {
                   7293: 	unlink($transferfile);
                   7294: 	&logthis("Userfile repcopy failed for $uri");
                   7295: 	return -1;
                   7296:     }
                   7297: # worked, rename the transfer file
                   7298:     rename($transferfile,$file);
1.607     raeburn  7299:     return 'ok';
1.481     raeburn  7300: }
                   7301: 
1.517     albertel 7302: sub tokenwrapper {
                   7303:     my $uri=shift;
1.552     albertel 7304:     $uri=~s|^http\://([^/]+)||;
                   7305:     $uri=~s|^/||;
1.620     albertel 7306:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7307:     my $token=$1;
1.552     albertel 7308:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7309:     if ($udom && $uname && $file) {
                   7310: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7311:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7312:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7313:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7314:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7315:     } else {
                   7316:         return '/adm/notfound.html';
                   7317:     }
                   7318: }
                   7319: 
1.828     www      7320: # call with reqtype HEAD: get last modification time
                   7321: # call with reqtype GET: get the file contents
                   7322: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7323: #
1.481     raeburn  7324: sub getuploaded {
                   7325:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7326:     $uri=~s/^\///;
                   7327:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7328:     my $ua=new LWP::UserAgent;
                   7329:     my $request=new HTTP::Request($reqtype,$uri);
                   7330:     my $response=$ua->request($request);
                   7331:     $$rtncode = $response->code;
1.482     albertel 7332:     if (! $response->is_success()) {
                   7333: 	return 'failed';
                   7334:     }      
                   7335:     if ($reqtype eq 'HEAD') {
1.486     www      7336: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7337:     } elsif ($reqtype eq 'GET') {
                   7338: 	$$info = $response->content;
1.472     albertel 7339:     }
1.482     albertel 7340:     return 'ok';
1.36      albertel 7341: }
                   7342: 
1.481     raeburn  7343: sub readfile {
                   7344:     my $file = shift;
                   7345:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7346:     my $fh;
                   7347:     open($fh,"<$file");
                   7348:     my $a='';
1.800     albertel 7349:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7350:     return $a;
                   7351: }
                   7352: 
1.36      albertel 7353: sub filelocation {
1.590     banghart 7354:     my ($dir,$file) = @_;
                   7355:     my $location;
                   7356:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7357: 
                   7358:     if ($file =~ m-^/adm/-) {
                   7359: 	$file=~s-^/adm/wrapper/-/-;
                   7360: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7361:     }
1.590     banghart 7362:     if ($file=~m:^/~:) { # is a contruction space reference
                   7363:         $location = $file;
                   7364:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7365:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7366: 	# is a correct contruction space reference
                   7367:         $location = $file;
1.609     banghart 7368:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7369:         my ($udom,$uname,$filename)=
1.811     albertel 7370:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7371:         my $home=&homeserver($uname,$udom);
                   7372:         my $is_me=0;
                   7373:         my @ids=&current_machine_ids();
                   7374:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7375:         if ($is_me) {
1.740     www      7376:   	    $location=&propath($udom,$uname).
1.590     banghart 7377:   	      '/userfiles/'.$filename;
                   7378:         } else {
                   7379:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7380:   	      $udom.'/'.$uname.'/'.$filename;
                   7381:         }
                   7382:     } else {
                   7383:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7384:         $file=~s:^/res/:/:;
                   7385:         if ( !( $file =~ m:^/:) ) {
                   7386:             $location = $dir. '/'.$file;
                   7387:         } else {
                   7388:             $location = '/home/httpd/html/res'.$file;
                   7389:         }
1.59      albertel 7390:     }
1.590     banghart 7391:     $location=~s://+:/:g; # remove duplicate /
                   7392:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7393:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7394:     return $location;
1.46      www      7395: }
1.36      albertel 7396: 
1.46      www      7397: sub hreflocation {
                   7398:     my ($dir,$file)=@_;
1.460     albertel 7399:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7400: 	$file=filelocation($dir,$file);
1.700     albertel 7401:     } elsif ($file=~m-^/adm/-) {
                   7402: 	$file=~s-^/adm/wrapper/-/-;
                   7403: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7404:     }
                   7405:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7406: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7407:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7408: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7409:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7410: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7411: 	    -/uploaded/$1/$2/-x;
1.46      www      7412:     }
1.462     albertel 7413:     return $file;
1.465     albertel 7414: }
                   7415: 
                   7416: sub current_machine_domains {
                   7417:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7418:     my @domains;
                   7419:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7420: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7421: 	if ($hostname eq $name) {
                   7422: 	    push(@domains,$hostdom{$id});
                   7423: 	}
                   7424:     }
                   7425:     return @domains;
                   7426: }
                   7427: 
                   7428: sub current_machine_ids {
                   7429:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7430:     my @ids;
                   7431:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7432: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7433: 	if ($hostname eq $name) {
                   7434: 	    push(@ids,$id);
                   7435: 	}
                   7436:     }
                   7437:     return @ids;
1.31      www      7438: }
                   7439: 
1.824     raeburn  7440: sub additional_machine_domains {
                   7441:     my @domains;
                   7442:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7443:     while( my $line = <$fh>) {
                   7444:         $line =~ s/\s//g;
                   7445:         push(@domains,$line);
                   7446:     }
                   7447:     return @domains;
                   7448: }
                   7449: 
                   7450: sub default_login_domain {
                   7451:     my $domain = $perlvar{'lonDefDomain'};
                   7452:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7453:     foreach my $posdom (&current_machine_domains(),
                   7454:                         &additional_machine_domains()) {
                   7455:         if (lc($posdom) eq lc($testdomain)) {
                   7456:             $domain=$posdom;
                   7457:             last;
                   7458:         }
                   7459:     }
                   7460:     return $domain;
                   7461: }
                   7462: 
1.31      www      7463: # ------------------------------------------------------------- Declutters URLs
                   7464: 
                   7465: sub declutter {
                   7466:     my $thisfn=shift;
1.569     albertel 7467:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7468:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7469:     $thisfn=~s/^\///;
1.697     albertel 7470:     $thisfn=~s|^adm/wrapper/||;
                   7471:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7472:     $thisfn=~s/^res\///;
1.235     www      7473:     $thisfn=~s/\?.+$//;
1.268     www      7474:     return $thisfn;
                   7475: }
                   7476: 
                   7477: # ------------------------------------------------------------- Clutter up URLs
                   7478: 
                   7479: sub clutter {
                   7480:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7481:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7482:        $thisfn='/res'.$thisfn; 
                   7483:     }
1.694     albertel 7484:     if ($thisfn !~m|/adm|) {
1.695     albertel 7485: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7486: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7487: 	} else {
                   7488: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7489: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7490: 	    if ($embstyle eq 'ssi'
                   7491: 		|| ($embstyle eq 'hdn')
                   7492: 		|| ($embstyle eq 'rat')
                   7493: 		|| ($embstyle eq 'prv')
                   7494: 		|| ($embstyle eq 'ign')) {
                   7495: 		#do nothing with these
                   7496: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7497: 		|| ($embstyle eq 'emb')
                   7498: 		|| ($embstyle eq 'wrp')) {
                   7499: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7500: 	    } elsif ($embstyle eq 'unk'
                   7501: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7502: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7503: 	    } else {
1.718     www      7504: #		&logthis("Got a blank emb style");
1.695     albertel 7505: 	    }
1.694     albertel 7506: 	}
                   7507:     }
1.31      www      7508:     return $thisfn;
1.12      www      7509: }
                   7510: 
1.787     albertel 7511: sub clutter_with_no_wrapper {
                   7512:     my $uri = &clutter(shift);
                   7513:     if ($uri =~ m-^/adm/-) {
                   7514: 	$uri =~ s-^/adm/wrapper/-/-;
                   7515: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7516:     }
                   7517:     return $uri;
                   7518: }
                   7519: 
1.557     albertel 7520: sub freeze_escape {
                   7521:     my ($value)=@_;
                   7522:     if (ref($value)) {
                   7523: 	$value=&nfreeze($value);
                   7524: 	return '__FROZEN__'.&escape($value);
                   7525:     }
                   7526:     return &escape($value);
                   7527: }
                   7528: 
1.11      www      7529: 
1.557     albertel 7530: sub thaw_unescape {
                   7531:     my ($value)=@_;
                   7532:     if ($value =~ /^__FROZEN__/) {
                   7533: 	substr($value,0,10,undef);
                   7534: 	$value=&unescape($value);
                   7535: 	return &thaw($value);
                   7536:     }
                   7537:     return &unescape($value);
                   7538: }
                   7539: 
1.436     albertel 7540: sub correct_line_ends {
                   7541:     my ($result)=@_;
                   7542:     $$result =~s/\r\n/\n/mg;
                   7543:     $$result =~s/\r/\n/mg;
1.415     albertel 7544: }
1.1       albertel 7545: # ================================================================ Main Program
                   7546: 
1.184     www      7547: sub goodbye {
1.204     albertel 7548:    &logthis("Starting Shut down");
1.443     albertel 7549: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7550:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7551: #converted
1.599     albertel 7552: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7553:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7554: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7555: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7556: #1.1 only
1.599     albertel 7557: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7558: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7559: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7560: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7561:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7562:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7563:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7564:    &flushcourselogs();
                   7565:    &logthis("Shutting down");
                   7566: }
                   7567: 
1.179     www      7568: BEGIN {
1.228     harris41 7569: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7570:     unless ($readit) {
1.217     harris41 7571: {
1.781     raeburn  7572:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7573:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7574: }
1.1       albertel 7575: 
1.327     albertel 7576: # ------------------------------------------------------------ Read domain file
                   7577: {
                   7578:     %domaindescription = ();
                   7579:     %domain_auth_def = ();
                   7580:     %domain_auth_arg_def = ();
1.448     albertel 7581:     my $fh;
                   7582:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7583: 	while (my $line = <$fh>) {
                   7584:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7585: #           next if /^\#/;
1.801     foxr     7586:            chomp $line;
1.403     www      7587:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7588: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7589: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7590:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7591: 	   $domaindescription{$domain}=$domain_description;
                   7592: 	   $domain_lang_def{$domain}=$def_lang;
                   7593: 	   $domain_city{$domain}=$city;
                   7594: 	   $domain_longi{$domain}=$longi;
                   7595: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7596:            $domain_primary{$domain}=$primary;
1.403     www      7597: 
1.448     albertel 7598:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7599: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7600: 	}
1.327     albertel 7601:     }
1.448     albertel 7602:     close ($fh);
1.327     albertel 7603: }
                   7604: 
                   7605: 
1.1       albertel 7606: # ------------------------------------------------------------- Read hosts file
                   7607: {
1.448     albertel 7608:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7609: 
                   7610:     while (my $configline=<$config>) {
1.303     matthew  7611:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7612:        chomp($configline);
1.595     albertel 7613:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7614:        $name=~s/\s//g;
1.595     albertel 7615:        if ($id && $domain && $role && $name) {
1.252     albertel 7616: 	 $hostname{$id}=$name;
                   7617: 	 $hostdom{$id}=$domain;
                   7618: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7619:        }
1.1       albertel 7620:     }
1.448     albertel 7621:     close($config);
1.619     albertel 7622:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7623:     #&get_iphost();
1.1       albertel 7624: }
                   7625: 
1.598     albertel 7626: sub get_iphost {
                   7627:     if (%iphost) { return %iphost; }
1.653     albertel 7628:     my %name_to_ip;
1.598     albertel 7629:     foreach my $id (keys(%hostname)) {
                   7630: 	my $name=$hostname{$id};
1.653     albertel 7631: 	my $ip;
                   7632: 	if (!exists($name_to_ip{$name})) {
                   7633: 	    $ip = gethostbyname($name);
                   7634: 	    if (!$ip || length($ip) ne 4) {
1.826     www      7635: 		&logthis("Skipping host $id name $name no IP found");
1.653     albertel 7636: 		next;
                   7637: 	    }
                   7638: 	    $ip=inet_ntoa($ip);
                   7639: 	    $name_to_ip{$name} = $ip;
                   7640: 	} else {
                   7641: 	    $ip = $name_to_ip{$name};
1.598     albertel 7642: 	}
                   7643: 	push(@{$iphost{$ip}},$id);
                   7644:     }
                   7645:     return %iphost;
                   7646: }
                   7647: 
1.1       albertel 7648: # ------------------------------------------------------ Read spare server file
                   7649: {
1.448     albertel 7650:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7651: 
                   7652:     while (my $configline=<$config>) {
                   7653:        chomp($configline);
1.284     matthew  7654:        if ($configline) {
1.784     albertel 7655: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7656: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7657: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7658:        }
                   7659:     }
1.448     albertel 7660:     close($config);
1.1       albertel 7661: }
1.11      www      7662: # ------------------------------------------------------------ Read permissions
                   7663: {
1.448     albertel 7664:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7665: 
                   7666:     while (my $configline=<$config>) {
1.448     albertel 7667: 	chomp($configline);
                   7668: 	if ($configline) {
                   7669: 	    my ($role,$perm)=split(/ /,$configline);
                   7670: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7671: 	}
1.11      www      7672:     }
1.448     albertel 7673:     close($config);
1.11      www      7674: }
                   7675: 
                   7676: # -------------------------------------------- Read plain texts for permissions
                   7677: {
1.448     albertel 7678:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7679: 
                   7680:     while (my $configline=<$config>) {
1.448     albertel 7681: 	chomp($configline);
                   7682: 	if ($configline) {
1.742     raeburn  7683: 	    my ($short,@plain)=split(/:/,$configline);
                   7684:             %{$prp{$short}} = ();
                   7685: 	    if (@plain > 0) {
                   7686:                 $prp{$short}{'std'} = $plain[0];
                   7687:                 for (my $i=1; $i<@plain; $i++) {
                   7688:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7689:                 }
                   7690:             }
1.448     albertel 7691: 	}
1.135     www      7692:     }
1.448     albertel 7693:     close($config);
1.135     www      7694: }
                   7695: 
                   7696: # ---------------------------------------------------------- Read package table
                   7697: {
1.448     albertel 7698:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7699: 
                   7700:     while (my $configline=<$config>) {
1.483     albertel 7701: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7702: 	chomp($configline);
                   7703: 	my ($short,$plain)=split(/:/,$configline);
                   7704: 	my ($pack,$name)=split(/\&/,$short);
                   7705: 	if ($plain ne '') {
                   7706: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7707: 	    $packagetab{$short}=$plain; 
                   7708: 	}
1.11      www      7709:     }
1.448     albertel 7710:     close($config);
1.329     matthew  7711: }
                   7712: 
                   7713: # ------------- set up temporary directory
                   7714: {
                   7715:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7716: 
1.11      www      7717: }
                   7718: 
1.794     albertel 7719: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7720: 				'compress_threshold'=> 20_000,
                   7721:  			        });
1.185     www      7722: 
1.281     www      7723: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7724: $dumpcount=0;
1.22      www      7725: 
1.163     harris41 7726: &logtouch();
1.672     albertel 7727: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7728: $readit=1;
1.564     albertel 7729:     {
                   7730: 	use integer;
                   7731: 	my $test=(2**32)+1;
1.568     albertel 7732: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7733: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7734:     }
1.195     www      7735: }
1.1       albertel 7736: }
1.179     www      7737: 
1.1       albertel 7738: 1;
1.191     harris41 7739: __END__
                   7740: 
1.243     albertel 7741: =pod
                   7742: 
1.191     harris41 7743: =head1 NAME
                   7744: 
1.243     albertel 7745: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7746: 
                   7747: =head1 SYNOPSIS
                   7748: 
1.243     albertel 7749: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7750: 
                   7751:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7752: 
1.243     albertel 7753: Common parameters:
                   7754: 
                   7755: =over 4
                   7756: 
                   7757: =item *
                   7758: 
                   7759: $uname : an internal username (if $cname expecting a course Id specifically)
                   7760: 
                   7761: =item *
                   7762: 
                   7763: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7764: 
                   7765: =item *
                   7766: 
                   7767: $symb : a resource instance identifier
                   7768: 
                   7769: =item *
                   7770: 
                   7771: $namespace : the name of a .db file that contains the data needed or
                   7772: being set.
                   7773: 
                   7774: =back
                   7775: 
1.394     bowersj2 7776: =head1 OVERVIEW
1.191     harris41 7777: 
1.394     bowersj2 7778: lonnet provides subroutines which interact with the
                   7779: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7780: about classes, users, and resources.
1.243     albertel 7781: 
                   7782: For many of these objects you can also use this to store data about
                   7783: them or modify them in various ways.
1.191     harris41 7784: 
1.394     bowersj2 7785: =head2 Symbs
1.191     harris41 7786: 
1.394     bowersj2 7787: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7788: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7789: map, the resource number of the resource in the map, and the URL of
                   7790: the resource itself. The latter is somewhat redundant, but might help
                   7791: if maps change.
                   7792: 
                   7793: An example is
                   7794: 
                   7795:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7796: 
                   7797: The respective map entry is
                   7798: 
                   7799:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7800:   title="Problem 2">
                   7801:  </resource>
                   7802: 
                   7803: Symbs are used by the random number generator, as well as to store and
                   7804: restore data specific to a certain instance of for example a problem.
                   7805: 
                   7806: =head2 Storing And Retrieving Data
                   7807: 
                   7808: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7809: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7810: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7811: is is the non-critical message twin of cstore. These functions are for
                   7812: handlers to store a perl hash to a user's permanent data space in an
                   7813: easy manner, and to retrieve it again on another call. It is expected
                   7814: that a handler would use this once at the beginning to retrieve data,
                   7815: and then again once at the end to send only the new data back.
                   7816: 
                   7817: The data is stored in the user's data directory on the user's
                   7818: homeserver under the ID of the course.
                   7819: 
                   7820: The hash that is returned by restore will have all of the previous
                   7821: value for all of the elements of the hash.
                   7822: 
                   7823: Example:
                   7824: 
                   7825:  #creating a hash
                   7826:  my %hash;
                   7827:  $hash{'foo'}='bar';
                   7828: 
                   7829:  #storing it
                   7830:  &Apache::lonnet::cstore(\%hash);
                   7831: 
                   7832:  #changing a value
                   7833:  $hash{'foo'}='notbar';
                   7834: 
                   7835:  #adding a new value
                   7836:  $hash{'bar'}='foo';
                   7837:  &Apache::lonnet::cstore(\%hash);
                   7838: 
                   7839:  #retrieving the hash
                   7840:  my %history=&Apache::lonnet::restore();
                   7841: 
                   7842:  #print the hash
                   7843:  foreach my $key (sort(keys(%history))) {
                   7844:    print("\%history{$key} = $history{$key}");
                   7845:  }
                   7846: 
                   7847: Will print out:
1.191     harris41 7848: 
1.394     bowersj2 7849:  %history{1:foo} = bar
                   7850:  %history{1:keys} = foo:timestamp
                   7851:  %history{1:timestamp} = 990455579
                   7852:  %history{2:bar} = foo
                   7853:  %history{2:foo} = notbar
                   7854:  %history{2:keys} = foo:bar:timestamp
                   7855:  %history{2:timestamp} = 990455580
                   7856:  %history{bar} = foo
                   7857:  %history{foo} = notbar
                   7858:  %history{timestamp} = 990455580
                   7859:  %history{version} = 2
                   7860: 
                   7861: Note that the special hash entries C<keys>, C<version> and
                   7862: C<timestamp> were added to the hash. C<version> will be equal to the
                   7863: total number of versions of the data that have been stored. The
                   7864: C<timestamp> attribute will be the UNIX time the hash was
                   7865: stored. C<keys> is available in every historical section to list which
                   7866: keys were added or changed at a specific historical revision of a
                   7867: hash.
                   7868: 
                   7869: B<Warning>: do not store the hash that restore returns directly. This
                   7870: will cause a mess since it will restore the historical keys as if the
                   7871: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7872: 
1.394     bowersj2 7873: Calling convention:
1.191     harris41 7874: 
1.394     bowersj2 7875:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7876:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7877: 
1.394     bowersj2 7878: For more detailed information, see lonnet specific documentation.
1.191     harris41 7879: 
1.394     bowersj2 7880: =head1 RETURN MESSAGES
1.191     harris41 7881: 
1.394     bowersj2 7882: =over 4
1.191     harris41 7883: 
1.394     bowersj2 7884: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7885: 
1.394     bowersj2 7886: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7887: when the connection is brought back up
1.191     harris41 7888: 
1.394     bowersj2 7889: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7890: for later delivery
1.191     harris41 7891: 
1.394     bowersj2 7892: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7893: 
1.394     bowersj2 7894: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7895: that was requested
1.191     harris41 7896: 
1.243     albertel 7897: =back
1.191     harris41 7898: 
1.243     albertel 7899: =head1 PUBLIC SUBROUTINES
1.191     harris41 7900: 
1.243     albertel 7901: =head2 Session Environment Functions
1.191     harris41 7902: 
1.243     albertel 7903: =over 4
1.191     harris41 7904: 
1.394     bowersj2 7905: =item * 
                   7906: X<appenv()>
                   7907: B<appenv(%hash)>: the value of %hash is written to
                   7908: the user envirnoment file, and will be restored for each access this
1.620     albertel 7909: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7910: process
1.191     harris41 7911: 
                   7912: =item *
1.394     bowersj2 7913: X<delenv()>
                   7914: B<delenv($regexp)>: removes all items from the session
                   7915: environment file that matches the regular expression in $regexp. The
1.620     albertel 7916: values are also delted from the current processes %env.
1.191     harris41 7917: 
1.795     albertel 7918: =item * get_env_multiple($name) 
                   7919: 
                   7920: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7921: values may be defined and end up as an array ref.
                   7922: 
                   7923: returns an array of values
                   7924: 
1.243     albertel 7925: =back
                   7926: 
                   7927: =head2 User Information
1.191     harris41 7928: 
1.243     albertel 7929: =over 4
1.191     harris41 7930: 
                   7931: =item *
1.394     bowersj2 7932: X<queryauthenticate()>
                   7933: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7934: authentication scheme
                   7935: 
                   7936: =item *
1.394     bowersj2 7937: X<authenticate()>
                   7938: B<authenticate($uname,$upass,$udom)>: try to
                   7939: authenticate user from domain's lib servers (first use the current
                   7940: one). C<$upass> should be the users password.
1.191     harris41 7941: 
                   7942: =item *
1.394     bowersj2 7943: X<homeserver()>
                   7944: B<homeserver($uname,$udom)>: find the server which has
                   7945: the user's directory and files (there must be only one), this caches
                   7946: the answer, and also caches if there is a borken connection.
1.191     harris41 7947: 
                   7948: =item *
1.394     bowersj2 7949: X<idget()>
                   7950: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7951: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7952: username, and only 1 username per ID in a specific domain) (returns
                   7953: hash: id=>name,id=>name)
1.191     harris41 7954: 
                   7955: =item *
1.394     bowersj2 7956: X<idrget()>
                   7957: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7958: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7959: 
                   7960: =item *
1.394     bowersj2 7961: X<idput()>
                   7962: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7963: 
                   7964: =item *
1.394     bowersj2 7965: X<rolesinit()>
                   7966: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7967: 
                   7968: =item *
1.551     albertel 7969: X<getsection()>
                   7970: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7971: course $cname, return section name/number or '' for "not in course"
                   7972: and '-1' for "no section"
                   7973: 
                   7974: =item *
1.394     bowersj2 7975: X<userenvironment()>
                   7976: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7977: passed in @what from the requested user's environment, returns a hash
                   7978: 
                   7979: =back
                   7980: 
                   7981: =head2 User Roles
                   7982: 
                   7983: =over 4
                   7984: 
                   7985: =item *
                   7986: 
1.810     raeburn  7987: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7988:  F: full access
                   7989:  U,I,K: authentication modes (cxx only)
                   7990:  '': forbidden
                   7991:  1: user needs to choose course
                   7992:  2: browse allowed
1.766     albertel 7993:  A: passphrase authentication needed
1.243     albertel 7994: 
                   7995: =item *
                   7996: 
                   7997: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7998: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7999: and course level
                   8000: 
                   8001: =item *
                   8002: 
                   8003: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8004: explanation of a user role term
                   8005: 
1.832     raeburn  8006: =item *
                   8007: 
1.834     albertel 8008: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
                   8009: optional.  Returns a hash of a user's roles, with keys set to
                   8010: colon-sparated $uname,$udom,and $role, and value set to
                   8011: colon-separated start and end times for the role. If no username and
                   8012: domain are specified, will default to current user/domain. Types,
                   8013: roles, and roledoms are references to arrays, of role statuses
                   8014: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
                   8015: of the roles which can be used to restrict the list if roles
                   8016: reported. If no array ref is provided for types, will default to
                   8017: return only active roles.
                   8018: 
1.243     albertel 8019: =back
                   8020: 
                   8021: =head2 User Modification
                   8022: 
                   8023: =over 4
                   8024: 
                   8025: =item *
                   8026: 
                   8027: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8028: user for the level given by URL.  Optional start and end dates (leave empty
                   8029: string or zero for "no date")
1.191     harris41 8030: 
                   8031: =item *
                   8032: 
1.243     albertel 8033: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8034: change a users, password, possible return values are: ok,
                   8035: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8036: refused
1.191     harris41 8037: 
                   8038: =item *
                   8039: 
1.243     albertel 8040: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8041: 
                   8042: =item *
                   8043: 
1.243     albertel 8044: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8045: modify user
1.191     harris41 8046: 
                   8047: =item *
                   8048: 
1.286     matthew  8049: modifystudent
                   8050: 
                   8051: modify a students enrollment and identification information.
                   8052: The course id is resolved based on the current users environment.  
                   8053: This means the envoking user must be a course coordinator or otherwise
                   8054: associated with a course.
                   8055: 
1.297     matthew  8056: This call is essentially a wrapper for lonnet::modifyuser and
                   8057: lonnet::modify_student_enrollment
1.286     matthew  8058: 
                   8059: Inputs: 
                   8060: 
                   8061: =over 4
                   8062: 
                   8063: =item B<$udom> Students loncapa domain
                   8064: 
                   8065: =item B<$uname> Students loncapa login name
                   8066: 
                   8067: =item B<$uid> Students id/student number
                   8068: 
                   8069: =item B<$umode> Students authentication mode
                   8070: 
                   8071: =item B<$upass> Students password
                   8072: 
                   8073: =item B<$first> Students first name
                   8074: 
                   8075: =item B<$middle> Students middle name
                   8076: 
                   8077: =item B<$last> Students last name
                   8078: 
                   8079: =item B<$gene> Students generation
                   8080: 
                   8081: =item B<$usec> Students section in course
                   8082: 
                   8083: =item B<$end> Unix time of the roles expiration
                   8084: 
                   8085: =item B<$start> Unix time of the roles start date
                   8086: 
                   8087: =item B<$forceid> If defined, allow $uid to be changed
                   8088: 
                   8089: =item B<$desiredhome> server to use as home server for student
                   8090: 
                   8091: =back
1.297     matthew  8092: 
                   8093: =item *
                   8094: 
                   8095: modify_student_enrollment
                   8096: 
                   8097: Change a students enrollment status in a class.  The environment variable
                   8098: 'role.request.course' must be defined for this function to proceed.
                   8099: 
                   8100: Inputs:
                   8101: 
                   8102: =over 4
                   8103: 
                   8104: =item $udom, students domain
                   8105: 
                   8106: =item $uname, students name
                   8107: 
                   8108: =item $uid, students user id
                   8109: 
                   8110: =item $first, students first name
                   8111: 
                   8112: =item $middle
                   8113: 
                   8114: =item $last
                   8115: 
                   8116: =item $gene
                   8117: 
                   8118: =item $usec
                   8119: 
                   8120: =item $end
                   8121: 
                   8122: =item $start
                   8123: 
                   8124: =back
                   8125: 
1.191     harris41 8126: 
                   8127: =item *
                   8128: 
1.243     albertel 8129: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8130: custom role; give a custom role to a user for the level given by URL.  Specify
                   8131: name and domain of role author, and role name
1.191     harris41 8132: 
                   8133: =item *
                   8134: 
1.243     albertel 8135: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8136: 
                   8137: =item *
                   8138: 
1.243     albertel 8139: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8140: 
                   8141: =back
                   8142: 
                   8143: =head2 Course Infomation
                   8144: 
                   8145: =over 4
1.191     harris41 8146: 
                   8147: =item *
                   8148: 
1.631     albertel 8149: coursedescription($courseid) : returns a hash of information about the
                   8150: specified course id, including all environment settings for the
                   8151: course, the description of the course will be in the hash under the
                   8152: key 'description'
1.191     harris41 8153: 
                   8154: =item *
                   8155: 
1.624     albertel 8156: resdata($name,$domain,$type,@which) : request for current parameter
                   8157: setting for a specific $type, where $type is either 'course' or 'user',
                   8158: @what should be a list of parameters to ask about. This routine caches
                   8159: answers for 5 minutes.
1.243     albertel 8160: 
                   8161: =back
                   8162: 
                   8163: =head2 Course Modification
                   8164: 
                   8165: =over 4
1.191     harris41 8166: 
                   8167: =item *
                   8168: 
1.243     albertel 8169: writecoursepref($courseid,%prefs) : write preferences (environment
                   8170: database) for a course
1.191     harris41 8171: 
                   8172: =item *
                   8173: 
1.243     albertel 8174: createcourse($udom,$description,$url) : make/modify course
                   8175: 
                   8176: =back
                   8177: 
                   8178: =head2 Resource Subroutines
                   8179: 
                   8180: =over 4
1.191     harris41 8181: 
                   8182: =item *
                   8183: 
1.243     albertel 8184: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8185: 
                   8186: =item *
                   8187: 
1.243     albertel 8188: repcopy($filename) : subscribes to the requested file, and attempts to
                   8189: replicate from the owning library server, Might return
1.607     raeburn  8190: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8191: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8192: resource. Expects the local filesystem pathname
                   8193: (/home/httpd/html/res/....)
                   8194: 
                   8195: =back
                   8196: 
                   8197: =head2 Resource Information
                   8198: 
                   8199: =over 4
1.191     harris41 8200: 
                   8201: =item *
                   8202: 
1.243     albertel 8203: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8204: a vairety of different possible values, $varname should be a request
                   8205: string, and the other parameters can be used to specify who and what
                   8206: one is asking about.
                   8207: 
                   8208: Possible values for $varname are environment.lastname (or other item
                   8209: from the envirnment hash), user.name (or someother aspect about the
                   8210: user), resource.0.maxtries (or some other part and parameter of a
                   8211: resource)
1.204     albertel 8212: 
                   8213: =item *
                   8214: 
1.243     albertel 8215: directcondval($number) : get current value of a condition; reads from a state
                   8216: string
1.204     albertel 8217: 
                   8218: =item *
                   8219: 
1.243     albertel 8220: condval($condidx) : value of condition index based on state
1.204     albertel 8221: 
                   8222: =item *
                   8223: 
1.243     albertel 8224: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8225: resource's metadata, $what should be either a specific key, or either
                   8226: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8227: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8228: 
                   8229: this function automatically caches all requests
1.191     harris41 8230: 
                   8231: =item *
                   8232: 
1.243     albertel 8233: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8234: network of library servers; returns file handle of where SQL and regex results
                   8235: will be stored for query
1.191     harris41 8236: 
                   8237: =item *
                   8238: 
1.243     albertel 8239: symbread($filename) : return symbolic list entry (filename argument optional);
                   8240: returns the data handle
1.191     harris41 8241: 
                   8242: =item *
                   8243: 
1.243     albertel 8244: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8245: a possible symb for the URL in $thisfn, and if is an encryypted
                   8246: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8247: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8248: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8249: 
1.191     harris41 8250: 
                   8251: =item *
                   8252: 
1.243     albertel 8253: symbclean($symb) : removes versions numbers from a symb, returns the
                   8254: cleaned symb
1.191     harris41 8255: 
                   8256: =item *
                   8257: 
1.243     albertel 8258: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8259: course map, user must be in a course for it to work.
1.191     harris41 8260: 
                   8261: =item *
                   8262: 
1.243     albertel 8263: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8264: 
                   8265: =item *
                   8266: 
1.243     albertel 8267: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8268: a random seed, all arguments are optional, if they aren't sent it uses the
                   8269: environment to derive them. Note: if symb isn't sent and it can't get one
                   8270: from &symbread it will use the current time as its return value
1.191     harris41 8271: 
                   8272: =item *
                   8273: 
1.243     albertel 8274: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8275: unfakeable, receipt
1.191     harris41 8276: 
                   8277: =item *
                   8278: 
1.620     albertel 8279: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8280: 
                   8281: =item *
                   8282: 
1.243     albertel 8283: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8284: 
                   8285: =item *
                   8286: 
1.243     albertel 8287: 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 8288: 
                   8289: =item *
                   8290: 
1.243     albertel 8291: 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 8292: 
                   8293: =item *
                   8294: 
1.243     albertel 8295: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8296: 
                   8297: =item *
                   8298: 
1.243     albertel 8299: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8300: forcing spreadsheet to reevaluate the resource scores next time.
                   8301: 
                   8302: =back
                   8303: 
                   8304: =head2 Storing/Retreiving Data
                   8305: 
                   8306: =over 4
1.191     harris41 8307: 
                   8308: =item *
                   8309: 
1.243     albertel 8310: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8311: for this url; hashref needs to be given and should be a \%hashname; the
                   8312: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8313: be derived from the env
1.191     harris41 8314: 
                   8315: =item *
                   8316: 
1.243     albertel 8317: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8318: uses critical subroutine
1.191     harris41 8319: 
                   8320: =item *
                   8321: 
1.243     albertel 8322: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8323: all args are optional
1.191     harris41 8324: 
                   8325: =item *
                   8326: 
1.717     albertel 8327: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8328: dumps the complete (or key matching regexp) namespace into a hash
                   8329: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8330: normally &store()ed into
                   8331: 
                   8332: $range should be either an integer '100' (give me the first 100
                   8333:                                            matching records)
                   8334:               or be  two integers sperated by a - with no spaces
                   8335:                  '30-50' (give me the 30th through the 50th matching
                   8336:                           records)
                   8337: 
                   8338: 
                   8339: =item *
                   8340: 
                   8341: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8342: replaces a &store() version of data with a replacement set of data
                   8343: for a particular resource in a namespace passed in the $storehash hash 
                   8344: reference
                   8345: 
                   8346: =item *
                   8347: 
1.243     albertel 8348: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8349: works very similar to store/cstore, but all data is stored in a
                   8350: temporary location and can be reset using tmpreset, $storehash should
                   8351: be a hash reference, returns nothing on success
1.191     harris41 8352: 
                   8353: =item *
                   8354: 
1.243     albertel 8355: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8356: similar to restore, but all data is stored in a temporary location and
                   8357: can be reset using tmpreset. Returns a hash of values on success,
                   8358: error string otherwise.
1.191     harris41 8359: 
                   8360: =item *
                   8361: 
1.243     albertel 8362: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8363: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8364: 
                   8365: =item *
                   8366: 
1.243     albertel 8367: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8368: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8369: 
                   8370: =item *
                   8371: 
1.243     albertel 8372: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8373: namesp ($udom and $uname are optional)
1.191     harris41 8374: 
                   8375: =item *
                   8376: 
1.702     albertel 8377: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8378: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8379: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8380: 
1.702     albertel 8381: $range should be either an integer '100' (give me the first 100
                   8382:                                            matching records)
                   8383:               or be  two integers sperated by a - with no spaces
                   8384:                  '30-50' (give me the 30th through the 50th matching
                   8385:                           records)
1.449     matthew  8386: =item *
                   8387: 
                   8388: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8389: $store can be a scalar, an array reference, or if the amount to be 
                   8390: incremented is > 1, a hash reference.
                   8391: 
                   8392: ($udom and $uname are optional)
1.191     harris41 8393: 
                   8394: =item *
                   8395: 
1.243     albertel 8396: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8397: ($udom and $uname are optional)
1.191     harris41 8398: 
                   8399: =item *
                   8400: 
1.243     albertel 8401: cput($namespace,$storehash,$udom,$uname) : critical put
                   8402: ($udom and $uname are optional)
1.191     harris41 8403: 
                   8404: =item *
                   8405: 
1.748     albertel 8406: newput($namespace,$storehash,$udom,$uname) :
                   8407: 
                   8408: Attempts to store the items in the $storehash, but only if they don't
                   8409: currently exist, if this succeeds you can be certain that you have 
                   8410: successfully created a new key value pair in the $namespace db.
                   8411: 
                   8412: 
                   8413: Args:
                   8414:  $namespace: name of database to store values to
                   8415:  $storehash: hashref to store to the db
                   8416:  $udom: (optional) domain of user containing the db
                   8417:  $uname: (optional) name of user caontaining the db
                   8418: 
                   8419: Returns:
                   8420:  'ok' -> succeeded in storing all keys of $storehash
                   8421:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8422:                         least <key> already existed in the db (other
                   8423:                         requested keys may also already exist)
                   8424:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8425:  'con_lost' -> unable to contact request server
                   8426:  'refused' -> action was not allowed by remote machine
                   8427: 
                   8428: 
                   8429: =item *
                   8430: 
1.243     albertel 8431: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8432: reference filled in from namesp (encrypts the return communication)
                   8433: ($udom and $uname are optional)
1.191     harris41 8434: 
                   8435: =item *
                   8436: 
1.243     albertel 8437: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8438: critical subroutine
                   8439: 
1.806     raeburn  8440: =item *
                   8441: 
                   8442: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8443: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8444: 
                   8445: =item *
                   8446: 
                   8447: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8448: 
1.243     albertel 8449: =back
                   8450: 
                   8451: =head2 Network Status Functions
                   8452: 
                   8453: =over 4
1.191     harris41 8454: 
                   8455: =item *
                   8456: 
                   8457: dirlist($uri) : return directory list based on URI
                   8458: 
                   8459: =item *
                   8460: 
1.243     albertel 8461: spareserver() : find server with least workload from spare.tab
                   8462: 
                   8463: =back
                   8464: 
                   8465: =head2 Apache Request
                   8466: 
                   8467: =over 4
1.191     harris41 8468: 
                   8469: =item *
                   8470: 
1.243     albertel 8471: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8472: localhost, posts hash
                   8473: 
                   8474: =back
                   8475: 
                   8476: =head2 Data to String to Data
                   8477: 
                   8478: =over 4
1.191     harris41 8479: 
                   8480: =item *
                   8481: 
1.243     albertel 8482: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8483: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8484: 
                   8485: =item *
                   8486: 
1.243     albertel 8487: hashref2str($hashref) : convert a hashref into a string complete with
                   8488: escaping and '=' and '&' separators, supports elements that are
                   8489: arrayrefs and hashrefs
1.191     harris41 8490: 
                   8491: =item *
                   8492: 
1.243     albertel 8493: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8494: with escaping and '&' separators, supports elements that are arrayrefs
                   8495: and hashrefs
1.191     harris41 8496: 
                   8497: =item *
                   8498: 
1.243     albertel 8499: str2hash($string) : convert string to hash using unescaping and
                   8500: splitting on '=' and '&', supports elements that are arrayrefs and
                   8501: hashrefs
1.191     harris41 8502: 
                   8503: =item *
                   8504: 
1.243     albertel 8505: str2array($string) : convert string to hash using unescaping and
                   8506: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8507: 
                   8508: =back
                   8509: 
                   8510: =head2 Logging Routines
                   8511: 
                   8512: =over 4
                   8513: 
                   8514: These routines allow one to make log messages in the lonnet.log and
                   8515: lonnet.perm logfiles.
1.191     harris41 8516: 
                   8517: =item *
                   8518: 
1.243     albertel 8519: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8520: 
                   8521: =item *
                   8522: 
1.243     albertel 8523: logthis() : append message to the normal lonnet.log file, it gets
                   8524: preiodically rolled over and deleted.
1.191     harris41 8525: 
                   8526: =item *
                   8527: 
1.243     albertel 8528: logperm() : append a permanent message to lonnet.perm.log, this log
                   8529: file never gets deleted by any automated portion of the system, only
                   8530: messages of critical importance should go in here.
                   8531: 
                   8532: =back
                   8533: 
                   8534: =head2 General File Helper Routines
                   8535: 
                   8536: =over 4
1.191     harris41 8537: 
                   8538: =item *
                   8539: 
1.481     raeburn  8540: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8541: (a) files in /uploaded
                   8542:   (i) If a local copy of the file exists - 
                   8543:       compares modification date of local copy with last-modified date for 
                   8544:       definitive version stored on home server for course. If local copy is 
                   8545:       stale, requests a new version from the home server and stores it. 
                   8546:       If the original has been removed from the home server, then local copy 
                   8547:       is unlinked.
                   8548:   (ii) If local copy does not exist -
                   8549:       requests the file from the home server and stores it. 
                   8550:   
                   8551:   If $caller is 'uploadrep':  
                   8552:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8553:     for request for files originally uploaded via DOCS. 
                   8554:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8555:   
                   8556:   Otherwise:
                   8557:      This indicates a call from the content generation phase of the request.
                   8558:      -  returns the entire contents of the file or -1.
                   8559:      
                   8560: (b) files in /res
                   8561:    - returns the entire contents of a file or -1; 
                   8562:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8563: 
1.712     albertel 8564: 
                   8565: =item *
                   8566: 
                   8567: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8568:                   reference
                   8569: 
                   8570: returns either a stat() list of data about the file or an empty list
                   8571: if the file doesn't exist or couldn't find out about it (connection
                   8572: problems or user unknown)
                   8573: 
1.191     harris41 8574: =item *
                   8575: 
1.243     albertel 8576: filelocation($dir,$file) : returns file system location of a file
                   8577: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8578: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8579: and a file of ../bob will become /a/bob)
1.191     harris41 8580: 
                   8581: =item *
                   8582: 
                   8583: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8584: filelocation except for hrefs
                   8585: 
                   8586: =item *
                   8587: 
                   8588: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8589: 
1.243     albertel 8590: =back
                   8591: 
1.608     albertel 8592: =head2 Usererfile file routines (/uploaded*)
                   8593: 
                   8594: =over 4
                   8595: 
                   8596: =item *
                   8597: 
                   8598: userfileupload(): main rotine for putting a file in a user or course's
                   8599:                   filespace, arguments are,
                   8600: 
1.620     albertel 8601:  formname - required - this is the name of the element in $env where the
1.608     albertel 8602:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8603:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8604:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8605:  coursedoc - if true, store the file in the course of the active role
                   8606:              of the current user
                   8607:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8608:          if undefined, it will be placed in "unknown"
                   8609: 
                   8610:  (This routine calls clean_filename() to remove any dangerous
                   8611:  characters from the filename, and then calls finuserfileupload() to
                   8612:  complete the transaction)
                   8613: 
                   8614:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8615:  and /adm/notfound.html if unsuccessful
                   8616: 
                   8617: =item *
                   8618: 
                   8619: clean_filename(): routine for cleaing a filename up for storage in
                   8620:                  userfile space, argument is:
                   8621: 
                   8622:  filename - proposed filename
                   8623: 
                   8624: returns: the new clean filename
                   8625: 
                   8626: =item *
                   8627: 
                   8628: finishuserfileupload(): routine that creaes and sends the file to
                   8629: userspace, probably shouldn't be called directly
                   8630: 
                   8631:   docuname: username or courseid of destination for the file
                   8632:   docudom: domain of user/course of destination for the file
                   8633:   formname: same as for userfileupload()
                   8634:   fname: filename (inculding subdirectories) for the file
                   8635: 
                   8636:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8637:  and /adm/notfound.html if unsuccessful
                   8638: 
                   8639: =item *
                   8640: 
                   8641: renameuserfile(): renames an existing userfile to a new name
                   8642: 
                   8643:   Args:
                   8644:    docuname: username or courseid of destination for the file
                   8645:    docudom: domain of user/course of destination for the file
                   8646:    old: current file name (including any subdirs under userfiles)
                   8647:    new: desired file name (including any subdirs under userfiles)
                   8648: 
                   8649: =item *
                   8650: 
                   8651: mkdiruserfile(): creates a directory is a userfiles dir
                   8652: 
                   8653:   Args:
                   8654:    docuname: username or courseid of destination for the file
                   8655:    docudom: domain of user/course of destination for the file
                   8656:    dir: dir to create (including any subdirs under userfiles)
                   8657: 
                   8658: =item *
                   8659: 
                   8660: removeuserfile(): removes a file that exists in userfiles
                   8661: 
                   8662:   Args:
                   8663:    docuname: username or courseid of destination for the file
                   8664:    docudom: domain of user/course of destination for the file
                   8665:    fname: filname to delete (including any subdirs under userfiles)
                   8666: 
                   8667: =item *
                   8668: 
                   8669: removeuploadedurl(): convience function for removeuserfile()
                   8670: 
                   8671:   Args:
                   8672:    url:  a full /uploaded/... url to delete
                   8673: 
1.747     albertel 8674: =item * 
                   8675: 
                   8676: get_portfile_permissions():
                   8677:   Args:
                   8678:     domain: domain of user or course contain the portfolio files
                   8679:     user: name of user or num of course contain the portfolio files
                   8680:   Returns:
                   8681:     hashref of a dump of the proper file_permissions.db
                   8682:    
                   8683: 
                   8684: =item * 
                   8685: 
                   8686: get_access_controls():
                   8687: 
                   8688: Args:
                   8689:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8690:   group: (optional) the group you want the files associated with
                   8691:   file: (optional) the file you want access info on
                   8692: 
                   8693: Returns:
1.749     raeburn  8694:     a hash (keys are file names) of hashes containing
                   8695:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8696:         values are XML containing access control settings (see below) 
1.747     albertel 8697: 
                   8698: Internal notes:
                   8699: 
1.749     raeburn  8700:  access controls are stored in file_permissions.db as key=value pairs.
                   8701:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8702:         where scope -> public,guest,course,group,domains or users.
                   8703:               end -> UNIX time for end of access (0 -> no end date)
                   8704:               start -> UNIX time for start of access
                   8705: 
                   8706:     value -> XML description of access control
                   8707:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8708:             <start></start>
                   8709:             <end></end>
                   8710: 
                   8711:             <password></password>  for scope type = guest
                   8712: 
                   8713:             <domain></domain>     for scope type = course or group
                   8714:             <number></number>
                   8715:             <roles id="">
                   8716:              <role></role>
                   8717:              <access></access>
                   8718:              <section></section>
                   8719:              <group></group>
                   8720:             </roles>
                   8721: 
                   8722:             <dom></dom>         for scope type = domains
                   8723: 
                   8724:             <users>             for scope type = users
                   8725:              <user>
                   8726:               <uname></uname>
                   8727:               <udom></udom>
                   8728:              </user>
                   8729:             </users>
                   8730:            </scope> 
                   8731:               
                   8732:  Access data is also aggregated for each file in an additional key=value pair:
                   8733:  key -> path to file/file_name\0accesscontrol 
                   8734:  value -> reference to hash
                   8735:           hash contains key = value pairs
                   8736:           where key = uniqueID:scope_end_start
                   8737:                 value = UNIX time record was last updated
                   8738: 
                   8739:           Used to improve speed of look-ups of access controls for each file.  
                   8740:  
                   8741:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8742: 
                   8743: modify_access_controls():
                   8744: 
                   8745: Modifies access controls for a portfolio file
                   8746: Args
                   8747: 1. file name
                   8748: 2. reference to hash of required changes,
                   8749: 3. domain
                   8750: 4. username
                   8751:   where domain,username are the domain of the portfolio owner 
                   8752:   (either a user or a course) 
                   8753: 
                   8754: Returns:
                   8755: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8756: 2. result of deletions ('ok' or 'error', with error message).
                   8757: 3. reference to hash of any new or updated access controls.
                   8758: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8759:    key = integer (inbound ID)
                   8760:    value = uniqueID  
1.747     albertel 8761: 
1.608     albertel 8762: =back
                   8763: 
1.243     albertel 8764: =head2 HTTP Helper Routines
                   8765: 
                   8766: =over 4
                   8767: 
1.191     harris41 8768: =item *
                   8769: 
                   8770: escape() : unpack non-word characters into CGI-compatible hex codes
                   8771: 
                   8772: =item *
                   8773: 
                   8774: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8775: 
1.243     albertel 8776: =back
                   8777: 
                   8778: =head1 PRIVATE SUBROUTINES
                   8779: 
                   8780: =head2 Underlying communication routines (Shouldn't call)
                   8781: 
                   8782: =over 4
                   8783: 
                   8784: =item *
                   8785: 
                   8786: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8787: 
                   8788: =item *
                   8789: 
                   8790: reply() : uses subreply to send a message to remote machine, logs all failures
                   8791: 
                   8792: =item *
                   8793: 
                   8794: critical() : passes a critical message to another server; if cannot
                   8795: get through then place message in connection buffer directory and
                   8796: returns con_delayed, if incapable of saving message, returns
                   8797: con_failed
                   8798: 
                   8799: =item *
                   8800: 
                   8801: reconlonc() : tries to reconnect lonc client processes.
                   8802: 
                   8803: =back
                   8804: 
                   8805: =head2 Resource Access Logging
                   8806: 
                   8807: =over 4
                   8808: 
                   8809: =item *
                   8810: 
                   8811: flushcourselogs() : flush (save) buffer logs and access logs
                   8812: 
                   8813: =item *
                   8814: 
                   8815: courselog($what) : save message for course in hash
                   8816: 
                   8817: =item *
                   8818: 
                   8819: courseacclog($what) : save message for course using &courselog().  Perform
                   8820: special processing for specific resource types (problems, exams, quizzes, etc).
                   8821: 
1.191     harris41 8822: =item *
                   8823: 
                   8824: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8825: as a PerlChildExitHandler
1.243     albertel 8826: 
                   8827: =back
                   8828: 
                   8829: =head2 Other
                   8830: 
                   8831: =over 4
                   8832: 
                   8833: =item *
                   8834: 
                   8835: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8836: 
                   8837: =back
                   8838: 
                   8839: =cut

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