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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.844   ! albertel    4: # $Id: lonnet.pm,v 1.843 2007/03/03 02:10:59 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.844   ! albertel   38: qw(%perlvar %badServerCache %iphost %spareid 
1.599     albertel   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.838     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.838     albertel  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.838     albertel  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) {
1.838     albertel  520: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  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.841     albertel  643: 
                    644:     my %servers = &get_servers($udom,'library');
                    645:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  646:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  647: 		 exists($badServerCache{$tryserver}));
1.841     albertel  648: 
                    649: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    650: 	if ($answer eq 'found') {
                    651: 	    delete($badServerCache{$tryserver}); 
                    652: 	    return $homecache{$index}=$tryserver;
                    653: 	} elsif ($answer eq 'no_host') {
                    654: 	    $badServerCache{$tryserver}=1;
                    655: 	}
1.1       albertel  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:     
1.841     albertel  666:     my %servers = &get_servers($udom,'library');
                    667:     foreach my $tryserver (keys(%servers)) {
                    668: 	my $idlist=join('&',@ids);
                    669: 	$idlist=~tr/A-Z/a-z/; 
                    670: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    671: 	my @answer=();
                    672: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    673: 	    @answer=split(/\&/,$reply);
                    674: 	}                    ;
                    675: 	my $i;
                    676: 	for ($i=0;$i<=$#ids;$i++) {
                    677: 	    if ($answer[$i]) {
                    678: 		$returnhash{$ids[$i]}=$answer[$i];
                    679: 	    } 
                    680: 	}
                    681:     } 
1.70      www       682:     return %returnhash;
                    683: }
                    684: 
                    685: # ------------------------------------- Find the IDs behind a list of usernames
                    686: 
                    687: sub idrget {
                    688:     my ($udom,@unames)=@_;
                    689:     my %returnhash=();
1.800     albertel  690:     foreach my $uname (@unames) {
                    691:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  692:     }
1.70      www       693:     return %returnhash;
                    694: }
                    695: 
                    696: # ------------------------------- Store away a list of names and associated IDs
                    697: 
                    698: sub idput {
                    699:     my ($udom,%ids)=@_;
                    700:     my %servers=();
1.800     albertel  701:     foreach my $uname (keys(%ids)) {
                    702: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    703:         my $uhom=&homeserver($uname,$udom);
1.70      www       704:         if ($uhom ne 'no_host') {
1.800     albertel  705:             my $id=&escape($ids{$uname});
1.70      www       706:             $id=~tr/A-Z/a-z/;
1.800     albertel  707:             my $esc_unam=&escape($uname);
1.70      www       708: 	    if ($servers{$uhom}) {
1.800     albertel  709: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       710:             } else {
1.800     albertel  711:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       712:             }
                    713:         }
1.191     harris41  714:     }
1.800     albertel  715:     foreach my $server (keys(%servers)) {
                    716:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  717:     }
1.344     www       718: }
                    719: 
1.806     raeburn   720: # ------------------------------------------- get items from domain db files   
                    721: 
                    722: sub get_dom {
                    723:     my ($namespace,$storearr,$udom)=@_;
                    724:     my $items='';
                    725:     foreach my $item (@$storearr) {
                    726:         $items.=&escape($item).'&';
                    727:     }
                    728:     $items=~s/\&$//;
                    729:     if (!$udom) { $udom=$env{'user.domain'}; }
                    730:     if (exists($domain_primary{$udom})) {
                    731:         my $uhome=$domain_primary{$udom};
                    732:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    733:         my @pairs=split(/\&/,$rep);
                    734:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    735:             return @pairs;
                    736:         }
                    737:         my %returnhash=();
                    738:         my $i=0;
                    739:         foreach my $item (@$storearr) {
                    740:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    741:             $i++;
                    742:         }
                    743:         return %returnhash;
                    744:     } else {
                    745:         &logthis("get_dom failed - no primary domain server for $udom");
                    746:     }
                    747: }
                    748: 
                    749: # -------------------------------------------- put items in domain db files 
                    750: 
                    751: sub put_dom {
                    752:     my ($namespace,$storehash,$udom)=@_;
                    753:     if (!$udom) { $udom=$env{'user.domain'}; }
                    754:     if (exists($domain_primary{$udom})) {
                    755:         my $uhome=$domain_primary{$udom};
                    756:         my $items='';
                    757:         foreach my $item (keys(%$storehash)) {
                    758:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    759:         }
                    760:         $items=~s/\&$//;
                    761:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    762:     } else {
                    763:         &logthis("put_dom failed - no primary domain server for $udom");
                    764:     }
                    765: }
                    766: 
1.837     raeburn   767: sub retrieve_inst_usertypes {
                    768:     my ($udom) = @_;
                    769:     my (%returnhash,@order);
                    770:     if (exists($domain_primary{$udom})) {
                    771:         my $uhome=$domain_primary{$udom};
                    772:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    773:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    774:         my @pairs=split(/\&/,$hashitems);
                    775:         foreach my $item (@pairs) {
                    776:             my ($key,$value)=split(/=/,$item,2);
                    777:             $key = &unescape($key);
                    778:             next if ($key =~ /^error: 2 /);
                    779:             $returnhash{$key}=&thaw_unescape($value);
                    780:         }
                    781:         my @esc_order = split(/\&/,$orderitems);
                    782:         foreach my $item (@esc_order) {
                    783:             push(@order,&unescape($item));
                    784:         }
                    785:     } else {
                    786:         &logthis("get_dom failed - no primary domain server for $udom");
                    787:     }
                    788:     return (\%returnhash,\@order);
                    789: }
                    790: 
1.344     www       791: # --------------------------------------------------- Assign a key to a student
                    792: 
                    793: sub assign_access_key {
1.364     www       794: #
                    795: # a valid key looks like uname:udom#comments
                    796: # comments are being appended
                    797: #
1.498     www       798:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    799:     $kdom=
1.620     albertel  800:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       801:     $knum=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       803:     $cdom=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       805:     $cnum=
1.620     albertel  806:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    807:     $udom=$env{'user.name'} unless (defined($udom));
                    808:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       809:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       810:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  811:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       812:                                                   # assigned to this person
                    813:                                                   # - this should not happen,
1.345     www       814:                                                   # unless something went wrong
                    815:                                                   # the first time around
                    816: # ready to assign
1.364     www       817:         $logentry=$1.'; '.$logentry;
1.496     www       818:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       819:                                                  $kdom,$knum) eq 'ok') {
1.345     www       820: # key now belongs to user
1.346     www       821: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       822:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    823:                 &appenv('environment.'.$envkey => $ckey);
                    824:                 return 'ok';
                    825:             } else {
                    826:                 return 
                    827:   'error: Count not permanently assign key, will need to be re-entered later.';
                    828: 	    }
                    829:         } else {
                    830:             return 'error: Could not assign key, try again later.';
                    831:         }
1.364     www       832:     } elsif (!$existing{$ckey}) {
1.345     www       833: # the key does not exist
                    834: 	return 'error: The key does not exist';
                    835:     } else {
                    836: # the key is somebody else's
                    837: 	return 'error: The key is already in use';
                    838:     }
1.344     www       839: }
                    840: 
1.364     www       841: # ------------------------------------------ put an additional comment on a key
                    842: 
                    843: sub comment_access_key {
                    844: #
                    845: # a valid key looks like uname:udom#comments
                    846: # comments are being appended
                    847: #
                    848:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    849:     $cdom=
1.620     albertel  850:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       851:     $cnum=
1.620     albertel  852:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       853:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    854:     if ($existing{$ckey}) {
                    855:         $existing{$ckey}.='; '.$logentry;
                    856: # ready to assign
1.367     www       857:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       858:                                                  $cdom,$cnum) eq 'ok') {
                    859: 	    return 'ok';
                    860:         } else {
                    861: 	    return 'error: Count not store comment.';
                    862:         }
                    863:     } else {
                    864: # the key does not exist
                    865: 	return 'error: The key does not exist';
                    866:     }
                    867: }
                    868: 
1.344     www       869: # ------------------------------------------------------ Generate a set of keys
                    870: 
                    871: sub generate_access_keys {
1.364     www       872:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       873:     $cdom=
1.620     albertel  874:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       875:     $cnum=
1.620     albertel  876:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       877:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       878:     unless (($cdom) && ($cnum)) { return 0; }
                    879:     if ($number>10000) { return 0; }
                    880:     sleep(2); # make sure don't get same seed twice
                    881:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    882:     my $total=0;
                    883:     for (my $i=1;$i<=$number;$i++) {
                    884:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    885:                   sprintf("%lx",int(100000*rand)).'-'.
                    886:                   sprintf("%lx",int(100000*rand));
                    887:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    888:        $newkey=~s/0/h/g; # and also 0 and O
                    889:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    890:        if ($existing{$newkey}) {
                    891:            $i--;
                    892:        } else {
1.364     www       893: 	  if (&put('accesskeys',
                    894:               { $newkey => '# generated '.localtime().
1.620     albertel  895:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       896:                            '; '.$logentry },
                    897: 		   $cdom,$cnum) eq 'ok') {
1.344     www       898:               $total++;
                    899: 	  }
                    900:        }
                    901:     }
1.620     albertel  902:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       903:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    904:     return $total;
                    905: }
                    906: 
                    907: # ------------------------------------------------------- Validate an accesskey
                    908: 
                    909: sub validate_access_key {
                    910:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    911:     $cdom=
1.620     albertel  912:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       913:     $cnum=
1.620     albertel  914:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    915:     $udom=$env{'user.domain'} unless (defined($udom));
                    916:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       917:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  918:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       919: }
                    920: 
                    921: # ------------------------------------- Find the section of student in a course
1.652     albertel  922: sub devalidate_getsection_cache {
                    923:     my ($udom,$unam,$courseid)=@_;
                    924:     my $hashid="$udom:$unam:$courseid";
                    925:     &devalidate_cache_new('getsection',$hashid);
                    926: }
1.298     matthew   927: 
1.815     albertel  928: sub courseid_to_courseurl {
                    929:     my ($courseid) = @_;
                    930:     #already url style courseid
                    931:     return $courseid if ($courseid =~ m{^/});
                    932: 
                    933:     if (exists($env{'course.'.$courseid.'.num'})) {
                    934: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    935: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    936: 	return "/$cdom/$cnum";
                    937:     }
                    938: 
                    939:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    940:     if (exists($courseinfo{'num'})) {
                    941: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    942:     }
                    943: 
                    944:     return undef;
                    945: }
                    946: 
1.298     matthew   947: sub getsection {
                    948:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  949:     my $cachetime=1800;
1.551     albertel  950: 
                    951:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  952:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  953:     if (defined($cached)) { return $result; }
                    954: 
1.298     matthew   955:     my %Pending; 
                    956:     my %Expired;
                    957:     #
                    958:     # Each role can either have not started yet (pending), be active, 
                    959:     #    or have expired.
                    960:     #
                    961:     # If there is an active role, we are done.
                    962:     #
                    963:     # If there is more than one role which has not started yet, 
                    964:     #     choose the one which will start sooner
                    965:     # If there is one role which has not started yet, return it.
                    966:     #
                    967:     # If there is more than one expired role, choose the one which ended last.
                    968:     # If there is a role which has expired, return it.
                    969:     #
1.815     albertel  970:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   971:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    972:     foreach my $key (keys(%roleshash)) {
1.479     albertel  973:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   974:         my $section=$1;
                    975:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   976:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   977:         my $now=time;
1.548     albertel  978:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   979:             $Expired{$end}=$section;
                    980:             next;
                    981:         }
1.548     albertel  982:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   983:             $Pending{$start}=$section;
                    984:             next;
                    985:         }
1.599     albertel  986:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   987:     }
                    988:     #
                    989:     # Presumedly there will be few matching roles from the above
                    990:     # loop and the sorting time will be negligible.
                    991:     if (scalar(keys(%Pending))) {
                    992:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  993:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   994:     } 
                    995:     if (scalar(keys(%Expired))) {
                    996:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    997:         my $time = pop(@sorted);
1.599     albertel  998:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   999:     }
1.599     albertel 1000:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1001: }
1.70      www      1002: 
1.599     albertel 1003: sub save_cache {
                   1004:     &purge_remembered();
1.722     albertel 1005:     #&Apache::loncommon::validate_page();
1.620     albertel 1006:     undef(%env);
1.780     albertel 1007:     undef($env_loaded);
1.599     albertel 1008: }
1.452     albertel 1009: 
1.599     albertel 1010: my $to_remember=-1;
                   1011: my %remembered;
                   1012: my %accessed;
                   1013: my $kicks=0;
                   1014: my $hits=0;
                   1015: sub devalidate_cache_new {
                   1016:     my ($name,$id,$debug) = @_;
                   1017:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                   1018:     $id=&escape($name.':'.$id);
                   1019:     $memcache->delete($id);
                   1020:     delete($remembered{$id});
                   1021:     delete($accessed{$id});
                   1022: }
                   1023: 
                   1024: sub is_cached_new {
                   1025:     my ($name,$id,$debug) = @_;
                   1026:     $id=&escape($name.':'.$id);
                   1027:     if (exists($remembered{$id})) {
                   1028: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1029: 	$accessed{$id}=[&gettimeofday()];
                   1030: 	$hits++;
                   1031: 	return ($remembered{$id},1);
                   1032:     }
                   1033:     my $value = $memcache->get($id);
                   1034:     if (!(defined($value))) {
                   1035: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1036: 	return (undef,undef);
1.416     albertel 1037:     }
1.599     albertel 1038:     if ($value eq '__undef__') {
                   1039: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1040: 	$value=undef;
                   1041:     }
                   1042:     &make_room($id,$value,$debug);
                   1043:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1044:     return ($value,1);
                   1045: }
                   1046: 
                   1047: sub do_cache_new {
                   1048:     my ($name,$id,$value,$time,$debug) = @_;
                   1049:     $id=&escape($name.':'.$id);
                   1050:     my $setvalue=$value;
                   1051:     if (!defined($setvalue)) {
                   1052: 	$setvalue='__undef__';
                   1053:     }
1.623     albertel 1054:     if (!defined($time) ) {
                   1055: 	$time=600;
                   1056:     }
1.599     albertel 1057:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1058:     $memcache->set($id,$setvalue,$time);
                   1059:     # need to make a copy of $value
                   1060:     #&make_room($id,$value,$debug);
1.599     albertel 1061:     return $value;
                   1062: }
                   1063: 
                   1064: sub make_room {
                   1065:     my ($id,$value,$debug)=@_;
                   1066:     $remembered{$id}=$value;
                   1067:     if ($to_remember<0) { return; }
                   1068:     $accessed{$id}=[&gettimeofday()];
                   1069:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1070:     my $to_kick;
                   1071:     my $max_time=0;
                   1072:     foreach my $other (keys(%accessed)) {
                   1073: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1074: 	    $to_kick=$other;
                   1075: 	    $max_time=&tv_interval($accessed{$other});
                   1076: 	}
                   1077:     }
                   1078:     delete($remembered{$to_kick});
                   1079:     delete($accessed{$to_kick});
                   1080:     $kicks++;
                   1081:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1082:     return;
                   1083: }
                   1084: 
1.599     albertel 1085: sub purge_remembered {
1.604     albertel 1086:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1087:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1088:     undef(%remembered);
                   1089:     undef(%accessed);
1.428     albertel 1090: }
1.70      www      1091: # ------------------------------------- Read an entry from a user's environment
                   1092: 
                   1093: sub userenvironment {
                   1094:     my ($udom,$unam,@what)=@_;
                   1095:     my %returnhash=();
                   1096:     my @answer=split(/\&/,
                   1097:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1098:                       &homeserver($unam,$udom)));
                   1099:     my $i;
                   1100:     for ($i=0;$i<=$#what;$i++) {
                   1101: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1102:     }
                   1103:     return %returnhash;
1.1       albertel 1104: }
                   1105: 
1.617     albertel 1106: # ---------------------------------------------------------- Get a studentphoto
                   1107: sub studentphoto {
                   1108:     my ($udom,$unam,$ext) = @_;
                   1109:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1110:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1111:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1112:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1113:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1114:             } else {
                   1115:                 my ($result,$perm_reqd)=
1.707     albertel 1116: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1117:                 if ($result eq 'ok') {
                   1118:                     if (!($perm_reqd eq 'yes')) {
                   1119:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1120:                     }
                   1121:                 }
                   1122:             }
                   1123:         }
                   1124:     } else {
                   1125:         my ($result,$perm_reqd) = 
1.707     albertel 1126: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1127:         if ($result eq 'ok') {
                   1128:             if (!($perm_reqd eq 'yes')) {
                   1129:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1130:             }
                   1131:         }
                   1132:     }
                   1133:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1134: }
                   1135: 
                   1136: sub retrievestudentphoto {
                   1137:     my ($udom,$unam,$ext,$type) = @_;
                   1138:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1139:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1140:     if ($ret eq 'ok') {
                   1141:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1142:         if ($type eq 'thumbnail') {
                   1143:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1144:         }
                   1145:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1146:         return $tokenurl;
                   1147:     } else {
                   1148:         if ($type eq 'thumbnail') {
                   1149:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1150:         } else { 
                   1151:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1152:         }
1.617     albertel 1153:     }
                   1154: }
                   1155: 
1.263     www      1156: # -------------------------------------------------------------------- New chat
                   1157: 
                   1158: sub chatsend {
1.724     raeburn  1159:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1160:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1161:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1162:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1163:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1164: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1165: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1166: }
                   1167: 
                   1168: # ------------------------------------------ Find current version of a resource
                   1169: 
                   1170: sub getversion {
                   1171:     my $fname=&clutter(shift);
                   1172:     unless ($fname=~/^\/res\//) { return -1; }
                   1173:     return &currentversion(&filelocation('',$fname));
                   1174: }
                   1175: 
                   1176: sub currentversion {
                   1177:     my $fname=shift;
1.599     albertel 1178:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1179:     if (defined($cached)) { return $result; }
1.292     www      1180:     my $author=$fname;
                   1181:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1182:     my ($udom,$uname)=split(/\//,$author);
                   1183:     my $home=homeserver($uname,$udom);
                   1184:     if ($home eq 'no_host') { 
                   1185:         return -1; 
                   1186:     }
                   1187:     my $answer=reply("currentversion:$fname",$home);
                   1188:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1189: 	return -1;
                   1190:     }
1.599     albertel 1191:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1192: }
                   1193: 
1.1       albertel 1194: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1195: 
1.1       albertel 1196: sub subscribe {
                   1197:     my $fname=shift;
1.761     raeburn  1198:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1199:     $fname=~s/[\n\r]//g;
1.1       albertel 1200:     my $author=$fname;
                   1201:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1202:     my ($udom,$uname)=split(/\//,$author);
                   1203:     my $home=homeserver($uname,$udom);
1.335     albertel 1204:     if ($home eq 'no_host') {
                   1205:         return 'not_found';
1.1       albertel 1206:     }
                   1207:     my $answer=reply("sub:$fname",$home);
1.64      www      1208:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1209: 	$answer.=' by '.$home;
                   1210:     }
1.1       albertel 1211:     return $answer;
                   1212: }
                   1213:     
1.8       www      1214: # -------------------------------------------------------------- Replicate file
                   1215: 
                   1216: sub repcopy {
                   1217:     my $filename=shift;
1.23      www      1218:     $filename=~s/\/+/\//g;
1.607     raeburn  1219:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1220:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1221:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1222: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1223: 	return &repcopy_userfile($filename);
                   1224:     }
1.532     albertel 1225:     $filename=~s/[\n\r]//g;
1.8       www      1226:     my $transname="$filename.in.transfer";
1.828     www      1227: # FIXME: this should flock
1.607     raeburn  1228:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1229:     my $remoteurl=subscribe($filename);
1.64      www      1230:     if ($remoteurl =~ /^con_lost by/) {
                   1231: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1232:            return 'unavailable';
1.8       www      1233:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1234: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1235: 	   return 'not_found';
1.64      www      1236:     } elsif ($remoteurl =~ /^rejected by/) {
                   1237: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1238:            return 'forbidden';
1.20      www      1239:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1240:            return 'ok';
1.8       www      1241:     } else {
1.290     www      1242:         my $author=$filename;
                   1243:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1244:         my ($udom,$uname)=split(/\//,$author);
                   1245:         my $home=homeserver($uname,$udom);
                   1246:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1247:            my @parts=split(/\//,$filename);
                   1248:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1249:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1250:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1251: 	       return 'bad_request';
1.8       www      1252:            }
                   1253:            my $count;
                   1254:            for ($count=5;$count<$#parts;$count++) {
                   1255:                $path.="/$parts[$count]";
                   1256:                if ((-e $path)!=1) {
                   1257: 		   mkdir($path,0777);
                   1258:                }
                   1259:            }
                   1260:            my $ua=new LWP::UserAgent;
                   1261:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1262:            my $response=$ua->request($request,$transname);
                   1263:            if ($response->is_error()) {
                   1264: 	       unlink($transname);
                   1265:                my $message=$response->status_line;
1.672     albertel 1266:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1267:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1268:                return 'unavailable';
1.8       www      1269:            } else {
1.16      www      1270: 	       if ($remoteurl!~/\.meta$/) {
                   1271:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1272:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1273:                   if ($mresponse->is_error()) {
                   1274: 		      unlink($filename.'.meta');
                   1275:                       &logthis(
1.672     albertel 1276:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1277:                   }
                   1278: 	       }
1.8       www      1279:                rename($transname,$filename);
1.607     raeburn  1280:                return 'ok';
1.8       www      1281:            }
1.290     www      1282:        }
1.8       www      1283:     }
1.330     www      1284: }
                   1285: 
                   1286: # ------------------------------------------------ Get server side include body
                   1287: sub ssi_body {
1.381     albertel 1288:     my ($filelink,%form)=@_;
1.606     matthew  1289:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1290:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1291:     }
1.330     www      1292:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1293:                                      &ssi($filelink,%form));
1.778     albertel 1294:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1295:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1296:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1297:     return $output;
1.8       www      1298: }
                   1299: 
1.15      www      1300: # --------------------------------------------------------- Server Side Include
                   1301: 
1.782     albertel 1302: sub absolute_url {
                   1303:     my ($host_name) = @_;
                   1304:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1305:     if ($host_name eq '') {
                   1306: 	$host_name = $ENV{'SERVER_NAME'};
                   1307:     }
                   1308:     return $protocol.$host_name;
                   1309: }
                   1310: 
1.15      www      1311: sub ssi {
                   1312: 
1.23      www      1313:     my ($fn,%form)=@_;
1.15      www      1314: 
                   1315:     my $ua=new LWP::UserAgent;
1.23      www      1316:     
                   1317:     my $request;
1.711     albertel 1318: 
                   1319:     $form{'no_update_last_known'}=1;
                   1320: 
1.23      www      1321:     if (%form) {
1.782     albertel 1322:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1323:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1324:     } else {
1.782     albertel 1325:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1326:     }
                   1327: 
1.15      www      1328:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1329:     my $response=$ua->request($request);
                   1330: 
1.324     www      1331:     return $response->content;
                   1332: }
                   1333: 
                   1334: sub externalssi {
                   1335:     my ($url)=@_;
                   1336:     my $ua=new LWP::UserAgent;
                   1337:     my $request=new HTTP::Request('GET',$url);
                   1338:     my $response=$ua->request($request);
1.15      www      1339:     return $response->content;
                   1340: }
1.254     www      1341: 
1.492     albertel 1342: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1343: 
                   1344: sub allowuploaded {
                   1345:     my ($srcurl,$url)=@_;
                   1346:     $url=&clutter(&declutter($url));
                   1347:     my $dir=$url;
                   1348:     $dir=~s/\/[^\/]+$//;
                   1349:     my %httpref=();
                   1350:     my $httpurl=&hreflocation('',$url);
                   1351:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1352:     &Apache::lonnet::appenv(%httpref);
1.254     www      1353: }
1.477     raeburn  1354: 
1.478     albertel 1355: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1356: # input: action, courseID, current domain, intended
1.637     raeburn  1357: #        path to file, source of file, instruction to parse file for objects,
                   1358: #        ref to hash for embedded objects,
                   1359: #        ref to hash for codebase of java objects.
                   1360: #
1.485     raeburn  1361: # output: url to file (if action was uploaddoc), 
                   1362: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1363: #
1.478     albertel 1364: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1365: # course.
1.477     raeburn  1366: #
1.478     albertel 1367: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1368: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1369: #          course's home server.
1.477     raeburn  1370: #
1.478     albertel 1371: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1372: #          be copied from $source (current location) to 
                   1373: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1374: #         and will then be copied to
                   1375: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1376: #         course's home server.
1.485     raeburn  1377: #
1.481     raeburn  1378: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1379: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1380: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1381: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1382: #         in course's home server.
1.637     raeburn  1383: #
1.477     raeburn  1384: 
                   1385: sub process_coursefile {
1.638     albertel 1386:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1387:     my $fetchresult;
1.638     albertel 1388:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1389:     if ($action eq 'propagate') {
1.638     albertel 1390:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1391: 			     $home);
1.481     raeburn  1392:     } else {
1.477     raeburn  1393:         my $fpath = '';
                   1394:         my $fname = $file;
1.478     albertel 1395:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1396:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1397:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1398:         if ($action eq 'copy') {
                   1399:             if ($source eq '') {
                   1400:                 $fetchresult = 'no source file';
                   1401:                 return $fetchresult;
                   1402:             } else {
                   1403:                 my $destination = $filepath.'/'.$fname;
                   1404:                 rename($source,$destination);
                   1405:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1406:                                  $home);
1.481     raeburn  1407:             }
                   1408:         } elsif ($action eq 'uploaddoc') {
                   1409:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1410:             print $fh $env{'form.'.$source};
1.481     raeburn  1411:             close($fh);
1.637     raeburn  1412:             if ($parser eq 'parse') {
                   1413:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1414:                 unless ($parse_result eq 'ok') {
                   1415:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1416:                 }
                   1417:             }
1.477     raeburn  1418:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1419:                                  $home);
1.481     raeburn  1420:             if ($fetchresult eq 'ok') {
                   1421:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1422:             } else {
                   1423:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1424:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1425:                 return '/adm/notfound.html';
                   1426:             }
1.477     raeburn  1427:         }
                   1428:     }
1.485     raeburn  1429:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1430:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1431:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1432:     }
                   1433:     return $fetchresult;
                   1434: }
                   1435: 
1.637     raeburn  1436: sub build_filepath {
                   1437:     my ($fpath) = @_;
                   1438:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1439:     unless ($fpath eq '') {
                   1440:         my @parts=split('/',$fpath);
                   1441:         foreach my $part (@parts) {
                   1442:             $filepath.= '/'.$part;
                   1443:             if ((-e $filepath)!=1) {
                   1444:                 mkdir($filepath,0777);
                   1445:             }
                   1446:         }
                   1447:     }
                   1448:     return $filepath;
                   1449: }
                   1450: 
                   1451: sub store_edited_file {
1.638     albertel 1452:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1453:     my $file = $primary_url;
                   1454:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1455:     my $fpath = '';
                   1456:     my $fname = $file;
                   1457:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1458:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1459:     my $filepath = &build_filepath($fpath);
                   1460:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1461:     print $fh $content;
                   1462:     close($fh);
1.638     albertel 1463:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1464:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1465: 			  $home);
1.637     raeburn  1466:     if ($$fetchresult eq 'ok') {
                   1467:         return '/uploaded/'.$fpath.'/'.$fname;
                   1468:     } else {
1.638     albertel 1469:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1470: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1471:         return '/adm/notfound.html';
                   1472:     }
                   1473: }
                   1474: 
1.531     albertel 1475: sub clean_filename {
1.831     albertel 1476:     my ($fname,$args)=@_;
1.315     www      1477: # Replace Windows backslashes by forward slashes
1.257     www      1478:     $fname=~s/\\/\//g;
1.831     albertel 1479:     if (!$args->{'keep_path'}) {
                   1480:         # Get rid of everything but the actual filename
                   1481: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1482:     }
1.315     www      1483: # Replace spaces by underscores
                   1484:     $fname=~s/\s+/\_/g;
                   1485: # Replace all other weird characters by nothing
1.831     albertel 1486:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1487: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1488: # numbers
                   1489:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1490:     return $fname;
                   1491: }
                   1492: 
1.608     albertel 1493: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1494: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1495: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1496: #        $coursedoc - if true up to the current course
                   1497: #                     if false
                   1498: #        $subdir - directory in userfile to store the file into
                   1499: #        $parser, $allfiles, $codebase - unknown
                   1500: #
                   1501: # output: url of file in userspace, or error: <message> 
                   1502: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1503: 
                   1504: 
1.531     albertel 1505: sub userfileupload {
1.719     banghart 1506:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1507:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1508:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1509:     $fname=&clean_filename($fname);
1.315     www      1510: # See if there is anything left
1.257     www      1511:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1512:     chop($env{'form.'.$formname});
1.523     raeburn  1513:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1514:         my $now = time;
                   1515:         my $filepath = 'tmp/helprequests/'.$now;
                   1516:         my @parts=split(/\//,$filepath);
                   1517:         my $fullpath = $perlvar{'lonDaemons'};
                   1518:         for (my $i=0;$i<@parts;$i++) {
                   1519:             $fullpath .= '/'.$parts[$i];
                   1520:             if ((-e $fullpath)!=1) {
                   1521:                 mkdir($fullpath,0777);
                   1522:             }
                   1523:         }
                   1524:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1525:         print $fh $env{'form.'.$formname};
1.523     raeburn  1526:         close($fh);
1.741     raeburn  1527:         return $fullpath.'/'.$fname;
                   1528:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1529:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1530:                        '_'.$env{'user.domain'}.'/pending';
                   1531:         my @parts=split(/\//,$filepath);
                   1532:         my $fullpath = $perlvar{'lonDaemons'};
                   1533:         for (my $i=0;$i<@parts;$i++) {
                   1534:             $fullpath .= '/'.$parts[$i];
                   1535:             if ((-e $fullpath)!=1) {
                   1536:                 mkdir($fullpath,0777);
                   1537:             }
                   1538:         }
                   1539:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1540:         print $fh $env{'form.'.$formname};
                   1541:         close($fh);
                   1542:         return $fullpath.'/'.$fname;
1.523     raeburn  1543:     }
1.719     banghart 1544:     
1.258     www      1545: # Create the directory if not present
1.493     albertel 1546:     $fname="$subdir/$fname";
1.259     www      1547:     if ($coursedoc) {
1.638     albertel 1548: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1549: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1550:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1551:             return &finishuserfileupload($docuname,$docudom,
                   1552: 					 $formname,$fname,$parser,$allfiles,
                   1553: 					 $codebase);
1.481     raeburn  1554:         } else {
1.620     albertel 1555:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1556:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1557: 				       $fname,$formname,$parser,
                   1558: 				       $allfiles,$codebase);
1.481     raeburn  1559:         }
1.719     banghart 1560:     } elsif (defined($destuname)) {
                   1561:         my $docuname=$destuname;
                   1562:         my $docudom=$destudom;
                   1563: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1564: 				     $fname,$parser,$allfiles,$codebase);
                   1565:         
1.259     www      1566:     } else {
1.638     albertel 1567:         my $docuname=$env{'user.name'};
                   1568:         my $docudom=$env{'user.domain'};
1.714     raeburn  1569:         if (exists($env{'form.group'})) {
                   1570:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1571:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1572:         }
1.638     albertel 1573: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1574: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1575:     }
1.271     www      1576: }
                   1577: 
                   1578: sub finishuserfileupload {
1.638     albertel 1579:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1580:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1581:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1582:     my ($fnamepath,$file);
                   1583:     $file=$fname;
                   1584:     if ($fname=~m|/|) {
                   1585:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1586: 	$path.=$fnamepath.'/';
                   1587:     }
1.259     www      1588:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1589:     my $count;
                   1590:     for ($count=4;$count<=$#parts;$count++) {
                   1591:         $filepath.="/$parts[$count]";
                   1592:         if ((-e $filepath)!=1) {
                   1593: 	    mkdir($filepath,0777);
                   1594:         }
                   1595:     }
                   1596: # Save the file
                   1597:     {
1.701     albertel 1598: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1599: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1600: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1601: 	    return '/adm/notfound.html';
                   1602: 	}
                   1603: 	if (!print FH ($env{'form.'.$formname})) {
                   1604: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1605: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1606: 	    return '/adm/notfound.html';
                   1607: 	}
1.570     albertel 1608: 	close(FH);
1.258     www      1609:     }
1.637     raeburn  1610:     if ($parser eq 'parse') {
1.638     albertel 1611:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1612: 						   $codebase);
1.637     raeburn  1613:         unless ($parse_result eq 'ok') {
1.638     albertel 1614:             &logthis('Failed to parse '.$filepath.$file.
                   1615: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1616:         }
                   1617:     }
1.259     www      1618: # Notify homeserver to grep it
                   1619: #
1.638     albertel 1620:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1621:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1622:     if ($fetchresult eq 'ok') {
1.259     www      1623: #
1.258     www      1624: # Return the URL to it
1.494     albertel 1625:         return '/uploaded/'.$path.$file;
1.263     www      1626:     } else {
1.494     albertel 1627:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1628: 		 ': '.$fetchresult);
1.263     www      1629:         return '/adm/notfound.html';
                   1630:     }    
1.493     albertel 1631: }
                   1632: 
1.637     raeburn  1633: sub extract_embedded_items {
1.648     raeburn  1634:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1635:     my @state = ();
                   1636:     my %javafiles = (
                   1637:                       codebase => '',
                   1638:                       code => '',
                   1639:                       archive => ''
                   1640:                     );
                   1641:     my %mediafiles = (
                   1642:                       src => '',
                   1643:                       movie => '',
                   1644:                      );
1.648     raeburn  1645:     my $p;
                   1646:     if ($content) {
                   1647:         $p = HTML::LCParser->new($content);
                   1648:     } else {
                   1649:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1650:     }
1.641     albertel 1651:     while (my $t=$p->get_token()) {
1.640     albertel 1652: 	if ($t->[0] eq 'S') {
                   1653: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1654: 	    push (@state, $tagname);
1.648     raeburn  1655:             if (lc($tagname) eq 'allow') {
                   1656:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1657:             }
1.640     albertel 1658: 	    if (lc($tagname) eq 'img') {
                   1659: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1660: 	    }
1.645     raeburn  1661:             if (lc($tagname) eq 'script') {
                   1662:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1663:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1664:                 } else {
                   1665:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1666:                 }
                   1667:             }
                   1668:             if (lc($tagname) eq 'link') {
                   1669:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1670:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1671:                 }
                   1672:             }
1.640     albertel 1673: 	    if (lc($tagname) eq 'object' ||
                   1674: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1675: 		foreach my $item (keys(%javafiles)) {
                   1676: 		    $javafiles{$item} = '';
                   1677: 		}
                   1678: 	    }
                   1679: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1680: 		my $name = lc($attr->{'name'});
                   1681: 		foreach my $item (keys(%javafiles)) {
                   1682: 		    if ($name eq $item) {
                   1683: 			$javafiles{$item} = $attr->{'value'};
                   1684: 			last;
                   1685: 		    }
                   1686: 		}
                   1687: 		foreach my $item (keys(%mediafiles)) {
                   1688: 		    if ($name eq $item) {
                   1689: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1690: 			last;
                   1691: 		    }
                   1692: 		}
                   1693: 	    }
                   1694: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1695: 		foreach my $item (keys(%javafiles)) {
                   1696: 		    if ($attr->{$item}) {
                   1697: 			$javafiles{$item} = $attr->{$item};
                   1698: 			last;
                   1699: 		    }
                   1700: 		}
                   1701: 		foreach my $item (keys(%mediafiles)) {
                   1702: 		    if ($attr->{$item}) {
                   1703: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1704: 			last;
                   1705: 		    }
                   1706: 		}
                   1707: 	    }
                   1708: 	} elsif ($t->[0] eq 'E') {
                   1709: 	    my ($tagname) = ($t->[1]);
                   1710: 	    if ($javafiles{'codebase'} ne '') {
                   1711: 		$javafiles{'codebase'} .= '/';
                   1712: 	    }  
                   1713: 	    if (lc($tagname) eq 'applet' ||
                   1714: 		lc($tagname) eq 'object' ||
                   1715: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1716: 		) {
                   1717: 		foreach my $item (keys(%javafiles)) {
                   1718: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1719: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1720: 			&add_filetype($allfiles,$file,$item);
                   1721: 		    }
                   1722: 		}
                   1723: 	    } 
                   1724: 	    pop @state;
                   1725: 	}
                   1726:     }
1.637     raeburn  1727:     return 'ok';
                   1728: }
                   1729: 
1.639     albertel 1730: sub add_filetype {
                   1731:     my ($allfiles,$file,$type)=@_;
                   1732:     if (exists($allfiles->{$file})) {
                   1733: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1734: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1735: 	}
                   1736:     } else {
                   1737: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1738:     }
                   1739: }
                   1740: 
1.493     albertel 1741: sub removeuploadedurl {
                   1742:     my ($url)=@_;
                   1743:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1744:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1745: }
                   1746: 
                   1747: sub removeuserfile {
                   1748:     my ($docuname,$docudom,$fname)=@_;
                   1749:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1750:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1751:     if ($result eq 'ok') {
                   1752:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1753:             my $metafile = $fname.'.meta';
                   1754:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1755: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1756:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1757:             my $sqlresult = 
1.823     albertel 1758:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1759:                                         'portfolio_metadata',$group,
                   1760:                                         'delete');
1.798     raeburn  1761:         }
                   1762:     }
                   1763:     return $result;
1.257     www      1764: }
1.15      www      1765: 
1.530     albertel 1766: sub mkdiruserfile {
                   1767:     my ($docuname,$docudom,$dir)=@_;
                   1768:     my $home=&homeserver($docuname,$docudom);
                   1769:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1770: }
                   1771: 
1.531     albertel 1772: sub renameuserfile {
                   1773:     my ($docuname,$docudom,$old,$new)=@_;
                   1774:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1775:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1776:                         &escape("$old").':'.&escape("$new"),$home);
                   1777:     if ($result eq 'ok') {
                   1778:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1779:             my $oldmeta = $old.'.meta';
                   1780:             my $newmeta = $new.'.meta';
                   1781:             my $metaresult = 
                   1782:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1783: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1784:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1785:             my $sqlresult = 
1.823     albertel 1786:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1787:                                         'portfolio_metadata',$group,
                   1788:                                         'delete');
1.798     raeburn  1789:         }
                   1790:     }
                   1791:     return $result;
1.531     albertel 1792: }
                   1793: 
1.14      www      1794: # ------------------------------------------------------------------------- Log
                   1795: 
                   1796: sub log {
                   1797:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1798:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1799: }
                   1800: 
                   1801: # ------------------------------------------------------------------ Course Log
1.352     www      1802: #
                   1803: # This routine flushes several buffers of non-mission-critical nature
                   1804: #
1.157     www      1805: 
                   1806: sub flushcourselogs {
1.352     www      1807:     &logthis('Flushing log buffers');
                   1808: #
                   1809: # course logs
                   1810: # This is a log of all transactions in a course, which can be used
                   1811: # for data mining purposes
                   1812: #
                   1813: # It also collects the courseid database, which lists last transaction
                   1814: # times and course titles for all courseids
                   1815: #
                   1816:     my %courseidbuffer=();
1.800     albertel 1817:     foreach my $crsid (keys %courselogs) {
1.352     www      1818:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1819: 		          &escape($courselogs{$crsid}),
                   1820: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1821: 	    delete $courselogs{$crsid};
                   1822:         } else {
                   1823:             &logthis('Failed to flush log buffer for '.$crsid);
                   1824:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1825:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1826:                         " exceeded maximum size, deleting.</font>");
                   1827:                delete $courselogs{$crsid};
                   1828:             }
1.352     www      1829:         }
                   1830:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1831:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1832: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1833:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1834:         } else {
                   1835:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1836: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1837:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1838:         }
1.191     harris41 1839:     }
1.352     www      1840: #
                   1841: # Write course id database (reverse lookup) to homeserver of courses 
                   1842: # Is used in pickcourse
                   1843: #
1.840     albertel 1844:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844   ! albertel 1845:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1846: 		     $crs_home);
1.352     www      1847:     }
                   1848: #
                   1849: # File accesses
                   1850: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1851: #
1.449     matthew  1852:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1853:         if ($entry =~ /___count$/) {
                   1854:             my ($dom,$name);
1.807     albertel 1855:             ($dom,$name,undef)=
1.811     albertel 1856: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1857:             if (! defined($dom) || $dom eq '' || 
                   1858:                 ! defined($name) || $name eq '') {
1.620     albertel 1859:                 my $cid = $env{'request.course.id'};
                   1860:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1861:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1862:             }
1.450     matthew  1863:             my $value = $accesshash{$entry};
                   1864:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1865:             my %temphash=($url => $value);
1.449     matthew  1866:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1867:             if ($result eq 'ok') {
                   1868:                 delete $accesshash{$entry};
                   1869:             } elsif ($result eq 'unknown_cmd') {
                   1870:                 # Target server has old code running on it.
1.450     matthew  1871:                 my %temphash=($entry => $value);
1.449     matthew  1872:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1873:                     delete $accesshash{$entry};
                   1874:                 }
                   1875:             }
                   1876:         } else {
1.811     albertel 1877:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1878:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1879:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1880:                 delete $accesshash{$entry};
                   1881:             }
1.185     www      1882:         }
1.191     harris41 1883:     }
1.352     www      1884: #
                   1885: # Roles
                   1886: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1887: #
1.800     albertel 1888:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1889:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1890: 	    split(/\:/,$entry);
                   1891:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1892:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1893:                 $rudom,$runame) eq 'ok') {
                   1894: 	    delete $userrolehash{$entry};
                   1895:         }
                   1896:     }
1.662     raeburn  1897: #
                   1898: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1899: #
                   1900:     my %domrolebuffer = ();
                   1901:     foreach my $entry (keys %domainrolehash) {
                   1902:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1903:         if ($domrolebuffer{$rudom}) {
                   1904:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1905:                       '='.&escape($domainrolehash{$entry});
                   1906:         } else {
                   1907:             $domrolebuffer{$rudom}.=&escape($entry).
                   1908:                       '='.&escape($domainrolehash{$entry});
                   1909:         }
                   1910:         delete $domainrolehash{$entry};
                   1911:     }
                   1912:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 1913: 	my %servers = &get_servers($dom,'library');
                   1914: 	foreach my $tryserver (keys(%servers)) {
                   1915: 	    unless (&reply('domroleput:'.$dom.':'.
                   1916: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1917: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1918: 	    }
1.662     raeburn  1919:         }
                   1920:     }
1.186     www      1921:     $dumpcount++;
1.157     www      1922: }
                   1923: 
                   1924: sub courselog {
                   1925:     my $what=shift;
1.158     www      1926:     $what=time.':'.$what;
1.620     albertel 1927:     unless ($env{'request.course.id'}) { return ''; }
                   1928:     $coursedombuf{$env{'request.course.id'}}=
                   1929:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1930:     $coursenumbuf{$env{'request.course.id'}}=
                   1931:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1932:     $coursehombuf{$env{'request.course.id'}}=
                   1933:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1934:     $coursedescrbuf{$env{'request.course.id'}}=
                   1935:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1936:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1937:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1938:     $courseownerbuf{$env{'request.course.id'}}=
                   1939:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1940:     $coursetypebuf{$env{'request.course.id'}}=
                   1941:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1942:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1943: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1944:     } else {
1.620     albertel 1945: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1946:     }
1.620     albertel 1947:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1948: 	&flushcourselogs();
                   1949:     }
1.158     www      1950: }
                   1951: 
                   1952: sub courseacclog {
                   1953:     my $fnsymb=shift;
1.620     albertel 1954:     unless ($env{'request.course.id'}) { return ''; }
                   1955:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1956:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1957:         $what.=':POST';
1.583     matthew  1958:         # FIXME: Probably ought to escape things....
1.800     albertel 1959: 	foreach my $key (keys(%env)) {
                   1960:             if ($key=~/^form\.(.*)/) {
                   1961: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1962:             }
1.191     harris41 1963:         }
1.583     matthew  1964:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1965:         # FIXME: We should not be depending on a form parameter that someone
                   1966:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1967:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1968:             $what.= ':POST';
                   1969:             # FIXME: Probably ought to escape things....
                   1970:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1971:                                  'crsdiscuss') {
1.620     albertel 1972:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1973:             }
                   1974:         }
1.158     www      1975:     }
                   1976:     &courselog($what);
1.149     www      1977: }
                   1978: 
1.185     www      1979: sub countacc {
                   1980:     my $url=&declutter(shift);
1.458     matthew  1981:     return if (! defined($url) || $url eq '');
1.620     albertel 1982:     unless ($env{'request.course.id'}) { return ''; }
                   1983:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1984:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1985:     $accesshash{$key}++;
1.185     www      1986: }
1.349     www      1987: 
1.361     www      1988: sub linklog {
                   1989:     my ($from,$to)=@_;
                   1990:     $from=&declutter($from);
                   1991:     $to=&declutter($to);
                   1992:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1993:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1994: }
                   1995:   
1.349     www      1996: sub userrolelog {
                   1997:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1998:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1999:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2000:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2001:         ($trole=~/^ta/)) {
1.350     www      2002:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2003:        $userrolehash
                   2004:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2005:                     =$tend.':'.$tstart;
1.662     raeburn  2006:     }
                   2007:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2008:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2009:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2010:         ($trole=~/^sc/)) {
                   2011:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2012:        $domainrolehash
                   2013:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2014:                     = $tend.':'.$tstart;
                   2015:     }
1.351     www      2016: }
                   2017: 
                   2018: sub get_course_adv_roles {
                   2019:     my $cid=shift;
1.620     albertel 2020:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2021:     my %coursehash=&coursedescription($cid);
1.470     www      2022:     my %nothide=();
1.800     albertel 2023:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2024: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2025:     }
1.351     www      2026:     my %returnhash=();
                   2027:     my %dumphash=
                   2028:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2029:     my $now=time;
1.800     albertel 2030:     foreach my $entry (keys %dumphash) {
                   2031: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2032:         if (($tstart) && ($tstart<0)) { next; }
                   2033:         if (($tend) && ($tend<$now)) { next; }
                   2034:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2035:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2036: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2037: 	if ((&privileged($username,$domain)) && 
                   2038: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2039: 	if ($role eq 'cr') { next; }
1.351     www      2040:         my $key=&plaintext($role);
                   2041:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2042:         if ($returnhash{$key}) {
                   2043: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2044:         } else {
                   2045:             $returnhash{$key}=$username.':'.$domain;
                   2046:         }
1.400     www      2047:      }
                   2048:     return %returnhash;
                   2049: }
                   2050: 
                   2051: sub get_my_roles {
1.832     raeburn  2052:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
1.620     albertel 2053:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2054:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2055:     my %dumphash=
                   2056:             &dump('nohist_userroles',$udom,$uname);
                   2057:     my %returnhash=();
                   2058:     my $now=time;
1.800     albertel 2059:     foreach my $entry (keys(%dumphash)) {
                   2060: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2061:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2062:         my $status = 'active';
                   2063:         if (($tend) && ($tend<$now)) {
                   2064:             $status = 'previous';
                   2065:         } 
                   2066:         if (($tstart) && ($now<$tstart)) {
                   2067:             $status = 'future';
                   2068:         }
                   2069:         if (ref($types) eq 'ARRAY') {
                   2070:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2071:                 next;
                   2072:             } 
                   2073:         } else {
                   2074:             if ($status ne 'active') {
                   2075:                 next;
                   2076:             }
                   2077:         }
1.800     albertel 2078:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.832     raeburn  2079:         if (ref($roledoms) eq 'ARRAY') {
                   2080:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2081:                 next;
                   2082:             }
                   2083:         }
                   2084:         if (ref($roles) eq 'ARRAY') {
                   2085:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2086:                 next;
                   2087:             }
                   2088:         } 
1.400     www      2089: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2090:     }
1.373     www      2091:     return %returnhash;
1.399     www      2092: }
                   2093: 
                   2094: # ----------------------------------------------------- Frontpage Announcements
                   2095: #
                   2096: #
                   2097: 
                   2098: sub postannounce {
                   2099:     my ($server,$text)=@_;
1.844   ! albertel 2100:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2101:     unless ($text=~/\w/) { $text=''; }
                   2102:     return &reply('setannounce:'.&escape($text),$server);
                   2103: }
                   2104: 
                   2105: sub getannounce {
1.448     albertel 2106: 
                   2107:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2108: 	my $announcement='';
1.800     albertel 2109: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2110: 	close($fh);
1.399     www      2111: 	if ($announcement=~/\w/) { 
                   2112: 	    return 
                   2113:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2114:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2115: 	} else {
                   2116: 	    return '';
                   2117: 	}
                   2118:     } else {
                   2119: 	return '';
                   2120:     }
1.351     www      2121: }
1.353     www      2122: 
                   2123: # ---------------------------------------------------------- Course ID routines
                   2124: # Deal with domain's nohist_courseid.db files
                   2125: #
                   2126: 
                   2127: sub courseidput {
                   2128:     my ($domain,$what,$coursehome)=@_;
                   2129:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2130: }
                   2131: 
                   2132: sub courseiddump {
1.791     raeburn  2133:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2134:     my %returnhash=();
1.355     www      2135:     unless ($domfilter) { $domfilter=''; }
1.353     www      2136:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2137:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.844   ! albertel 2138: 	    if ((!$domfilter) || (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2139: 	        foreach my $line (
1.844   ! albertel 2140:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2141: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2142:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2143:                                $tryserver))) {
1.800     albertel 2144: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2145:                     if (($key) && ($value)) {
1.516     raeburn  2146: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2147:                     }
1.353     www      2148:                 }
                   2149:             }
                   2150:         }
                   2151:     }
                   2152:     return %returnhash;
                   2153: }
                   2154: 
1.658     raeburn  2155: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2156: 
                   2157: sub dcmailput {
1.685     raeburn  2158:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2159:     my $status = &Apache::lonnet::critical(
1.740     www      2160:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2161:        &escape($message),$server);
1.662     raeburn  2162:     return $status;
                   2163: }
                   2164: 
1.658     raeburn  2165: sub dcmaildump {
                   2166:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2167:     my %returnhash=();
                   2168:     if (exists($domain_primary{$dom})) {
                   2169:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2170:                                                          &escape($enddate).':';
                   2171: 	my @esc_senders=map { &escape($_)} @$senders;
                   2172: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2173: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2174:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2175:             if (($key) && ($value)) {
                   2176:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2177:             }
                   2178:         }
                   2179:     }
                   2180:     return %returnhash;
                   2181: }
1.662     raeburn  2182: # ---------------------------------------------------------- Domain roles
                   2183: 
                   2184: sub get_domain_roles {
                   2185:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2186:     if (undef($startdate) || $startdate eq '') {
                   2187:         $startdate = '.';
                   2188:     }
                   2189:     if (undef($enddate) || $enddate eq '') {
                   2190:         $enddate = '.';
                   2191:     }
                   2192:     my $rolelist = join(':',@{$roles});
                   2193:     my %personnel = ();
1.841     albertel 2194: 
                   2195:     my %servers = &get_servers($dom,'library');
                   2196:     foreach my $tryserver (keys(%servers)) {
                   2197: 	%{$personnel{$tryserver}}=();
                   2198: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2199: 					    &escape($startdate).':'.
                   2200: 					    &escape($enddate).':'.
                   2201: 					    &escape($rolelist), $tryserver))) {
                   2202: 	    my ($key,$value) = split(/\=/,$line,2);
                   2203: 	    if (($key) && ($value)) {
                   2204: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2205: 	    }
                   2206: 	}
1.662     raeburn  2207:     }
                   2208:     return %personnel;
                   2209: }
1.658     raeburn  2210: 
1.149     www      2211: # ----------------------------------------------------------- Check out an item
                   2212: 
1.504     albertel 2213: sub get_first_access {
                   2214:     my ($type,$argsymb)=@_;
1.790     albertel 2215:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2216:     if ($argsymb) { $symb=$argsymb; }
                   2217:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2218:     if ($type eq 'map') {
                   2219: 	$res=&symbread($map);
                   2220:     } else {
                   2221: 	$res=$symb;
                   2222:     }
                   2223:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2224:     return $times{"$courseid\0$res"};
1.504     albertel 2225: }
                   2226: 
                   2227: sub set_first_access {
                   2228:     my ($type)=@_;
1.790     albertel 2229:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2230:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2231:     if ($type eq 'map') {
                   2232: 	$res=&symbread($map);
                   2233:     } else {
                   2234: 	$res=$symb;
                   2235:     }
                   2236:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2237:     if (!$firstaccess) {
1.588     albertel 2238: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2239:     }
                   2240:     return 'already_set';
1.504     albertel 2241: }
                   2242: 
1.149     www      2243: sub checkout {
                   2244:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2245:     my $now=time;
                   2246:     my $lonhost=$perlvar{'lonHostID'};
                   2247:     my $infostr=&escape(
1.234     www      2248:                  'CHECKOUTTOKEN&'.
1.149     www      2249:                  $tuname.'&'.
                   2250:                  $tudom.'&'.
                   2251:                  $tcrsid.'&'.
                   2252:                  $symb.'&'.
                   2253: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2254:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2255:     if ($token=~/^error\:/) { 
1.672     albertel 2256:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2257:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2258:                  "</font>");
                   2259:         return ''; 
                   2260:     }
                   2261: 
1.149     www      2262:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2263:     $token=~tr/a-z/A-Z/;
                   2264: 
1.153     www      2265:     my %infohash=('resource.0.outtoken' => $token,
                   2266:                   'resource.0.checkouttime' => $now,
                   2267:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2268: 
                   2269:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2270:        return '';
1.151     www      2271:     } else {
1.672     albertel 2272:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2273:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2274:                  "</font>");
1.149     www      2275:     }    
                   2276: 
                   2277:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2278:                          &escape('Checkout '.$infostr.' - '.
                   2279:                                                  $token)) ne 'ok') {
                   2280: 	return '';
1.151     www      2281:     } else {
1.672     albertel 2282:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2283:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2284:                  "</font>");
1.149     www      2285:     }
1.151     www      2286:     return $token;
1.149     www      2287: }
                   2288: 
                   2289: # ------------------------------------------------------------ Check in an item
                   2290: 
                   2291: sub checkin {
                   2292:     my $token=shift;
1.150     www      2293:     my $now=time;
                   2294:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2295:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2296:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2297:     $dtoken=~s/\W/\_/g;
1.234     www      2298:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2299:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2300: 
1.154     www      2301:     unless (($tuname) && ($tudom)) {
                   2302:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2303:         return '';
                   2304:     }
                   2305:     
                   2306:     unless (&allowed('mgr',$tcrsid)) {
                   2307:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2308:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2309:         return '';
                   2310:     }
                   2311: 
1.153     www      2312:     my %infohash=('resource.0.intoken' => $token,
                   2313:                   'resource.0.checkintime' => $now,
                   2314:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2315: 
                   2316:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2317:        return '';
                   2318:     }    
                   2319: 
                   2320:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2321:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2322: 	return '';
                   2323:     }
                   2324: 
                   2325:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2326: }
                   2327: 
                   2328: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2329: 
                   2330: sub expirespread {
                   2331:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2332:     my $cid=$env{'request.course.id'}; 
1.110     www      2333:     if ($cid) {
                   2334:        my $now=time;
                   2335:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2336:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2337:                             $env{'course.'.$cid.'.num'}.
1.110     www      2338: 	        	    ':nohist_expirationdates:'.
                   2339:                             &escape($key).'='.$now,
1.620     albertel 2340:                             $env{'course.'.$cid.'.home'})
1.110     www      2341:     }
                   2342:     return 'ok';
1.14      www      2343: }
                   2344: 
1.109     www      2345: # ----------------------------------------------------- Devalidate Spreadsheets
                   2346: 
                   2347: sub devalidate {
1.325     www      2348:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2349:     my $cid=$env{'request.course.id'}; 
1.109     www      2350:     if ($cid) {
1.391     matthew  2351:         # delete the stored spreadsheets for
                   2352:         # - the student level sheet of this user in course's homespace
                   2353:         # - the assessment level sheet for this resource 
                   2354:         #   for this user in user's homespace
1.553     albertel 2355: 	# - current conditional state info
1.325     www      2356: 	my $key=$uname.':'.$udom.':';
1.109     www      2357:         my $status=
1.299     matthew  2358: 	    &del('nohist_calculatedsheets',
1.391     matthew  2359: 		 [$key.'studentcalc:'],
1.620     albertel 2360: 		 $env{'course.'.$cid.'.domain'},
                   2361: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2362: 		.' '.
                   2363: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2364: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2365:         unless ($status eq 'ok ok') {
                   2366:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2367:                     $uname.' at '.$udom.' for '.
1.109     www      2368: 		    $symb.': '.$status);
1.133     albertel 2369:         }
1.553     albertel 2370: 	&delenv('user.state.'.$cid);
1.109     www      2371:     }
                   2372: }
                   2373: 
1.265     albertel 2374: sub get_scalar {
                   2375:     my ($string,$end) = @_;
                   2376:     my $value;
                   2377:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2378: 	$value = $1;
                   2379:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2380: 	$value = $1;
                   2381:     }
                   2382:     return &unescape($value);
                   2383: }
                   2384: 
                   2385: sub array2str {
                   2386:   my (@array) = @_;
                   2387:   my $result=&arrayref2str(\@array);
                   2388:   $result=~s/^__ARRAY_REF__//;
                   2389:   $result=~s/__END_ARRAY_REF__$//;
                   2390:   return $result;
                   2391: }
                   2392: 
1.204     albertel 2393: sub arrayref2str {
                   2394:   my ($arrayref) = @_;
1.265     albertel 2395:   my $result='__ARRAY_REF__';
1.204     albertel 2396:   foreach my $elem (@$arrayref) {
1.265     albertel 2397:     if(ref($elem) eq 'ARRAY') {
                   2398:       $result.=&arrayref2str($elem).'&';
                   2399:     } elsif(ref($elem) eq 'HASH') {
                   2400:       $result.=&hashref2str($elem).'&';
                   2401:     } elsif(ref($elem)) {
                   2402:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2403:     } else {
                   2404:       $result.=&escape($elem).'&';
                   2405:     }
                   2406:   }
                   2407:   $result=~s/\&$//;
1.265     albertel 2408:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2409:   return $result;
                   2410: }
                   2411: 
1.168     albertel 2412: sub hash2str {
1.204     albertel 2413:   my (%hash) = @_;
                   2414:   my $result=&hashref2str(\%hash);
1.265     albertel 2415:   $result=~s/^__HASH_REF__//;
                   2416:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2417:   return $result;
                   2418: }
                   2419: 
                   2420: sub hashref2str {
                   2421:   my ($hashref)=@_;
1.265     albertel 2422:   my $result='__HASH_REF__';
1.800     albertel 2423:   foreach my $key (sort(keys(%$hashref))) {
                   2424:     if (ref($key) eq 'ARRAY') {
                   2425:       $result.=&arrayref2str($key).'=';
                   2426:     } elsif (ref($key) eq 'HASH') {
                   2427:       $result.=&hashref2str($key).'=';
                   2428:     } elsif (ref($key)) {
1.265     albertel 2429:       $result.='=';
1.800     albertel 2430:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2431:     } else {
1.800     albertel 2432: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2433:     }
                   2434: 
1.800     albertel 2435:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2436:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2437:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2438:       $result.=&hashref2str($hashref->{$key}).'&';
                   2439:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2440:        $result.='&';
1.800     albertel 2441:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2442:     } else {
1.800     albertel 2443:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2444:     }
                   2445:   }
1.168     albertel 2446:   $result=~s/\&$//;
1.265     albertel 2447:   $result .= '__END_HASH_REF__';
1.168     albertel 2448:   return $result;
                   2449: }
                   2450: 
                   2451: sub str2hash {
1.265     albertel 2452:     my ($string)=@_;
                   2453:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2454:     return %$hash;
                   2455: }
                   2456: 
                   2457: sub str2hashref {
1.168     albertel 2458:   my ($string) = @_;
1.265     albertel 2459: 
                   2460:   my %hash;
                   2461: 
                   2462:   if($string !~ /^__HASH_REF__/) {
                   2463:       if (! ($string eq '' || !defined($string))) {
                   2464: 	  $hash{'error'}='Not hash reference';
                   2465:       }
                   2466:       return (\%hash, $string);
                   2467:   }
                   2468: 
                   2469:   $string =~ s/^__HASH_REF__//;
                   2470: 
                   2471:   while($string !~ /^__END_HASH_REF__/) {
                   2472:       #key
                   2473:       my $key='';
                   2474:       if($string =~ /^__HASH_REF__/) {
                   2475:           ($key, $string)=&str2hashref($string);
                   2476:           if(defined($key->{'error'})) {
                   2477:               $hash{'error'}='Bad data';
                   2478:               return (\%hash, $string);
                   2479:           }
                   2480:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2481:           ($key, $string)=&str2arrayref($string);
                   2482:           if($key->[0] eq 'Array reference error') {
                   2483:               $hash{'error'}='Bad data';
                   2484:               return (\%hash, $string);
                   2485:           }
                   2486:       } else {
                   2487:           $string =~ s/^(.*?)=//;
1.267     albertel 2488: 	  $key=&unescape($1);
1.265     albertel 2489:       }
                   2490:       $string =~ s/^=//;
                   2491: 
                   2492:       #value
                   2493:       my $value='';
                   2494:       if($string =~ /^__HASH_REF__/) {
                   2495:           ($value, $string)=&str2hashref($string);
                   2496:           if(defined($value->{'error'})) {
                   2497:               $hash{'error'}='Bad data';
                   2498:               return (\%hash, $string);
                   2499:           }
                   2500:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2501:           ($value, $string)=&str2arrayref($string);
                   2502:           if($value->[0] eq 'Array reference error') {
                   2503:               $hash{'error'}='Bad data';
                   2504:               return (\%hash, $string);
                   2505:           }
                   2506:       } else {
                   2507: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2508:       }
                   2509:       $string =~ s/^&//;
                   2510: 
                   2511:       $hash{$key}=$value;
1.204     albertel 2512:   }
1.265     albertel 2513: 
                   2514:   $string =~ s/^__END_HASH_REF__//;
                   2515: 
                   2516:   return (\%hash, $string);
1.204     albertel 2517: }
                   2518: 
                   2519: sub str2array {
1.265     albertel 2520:     my ($string)=@_;
                   2521:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2522:     return @$array;
                   2523: }
                   2524: 
                   2525: sub str2arrayref {
1.204     albertel 2526:   my ($string) = @_;
1.265     albertel 2527:   my @array;
                   2528: 
                   2529:   if($string !~ /^__ARRAY_REF__/) {
                   2530:       if (! ($string eq '' || !defined($string))) {
                   2531: 	  $array[0]='Array reference error';
                   2532:       }
                   2533:       return (\@array, $string);
                   2534:   }
                   2535: 
                   2536:   $string =~ s/^__ARRAY_REF__//;
                   2537: 
                   2538:   while($string !~ /^__END_ARRAY_REF__/) {
                   2539:       my $value='';
                   2540:       if($string =~ /^__HASH_REF__/) {
                   2541:           ($value, $string)=&str2hashref($string);
                   2542:           if(defined($value->{'error'})) {
                   2543:               $array[0] ='Array reference error';
                   2544:               return (\@array, $string);
                   2545:           }
                   2546:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2547:           ($value, $string)=&str2arrayref($string);
                   2548:           if($value->[0] eq 'Array reference error') {
                   2549:               $array[0] ='Array reference error';
                   2550:               return (\@array, $string);
                   2551:           }
                   2552:       } else {
                   2553: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2554:       }
                   2555:       $string =~ s/^&//;
                   2556: 
                   2557:       push(@array, $value);
1.191     harris41 2558:   }
1.265     albertel 2559: 
                   2560:   $string =~ s/^__END_ARRAY_REF__//;
                   2561: 
                   2562:   return (\@array, $string);
1.168     albertel 2563: }
                   2564: 
1.167     albertel 2565: # -------------------------------------------------------------------Temp Store
                   2566: 
1.168     albertel 2567: sub tmpreset {
                   2568:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2569:   if (!$symb) {
                   2570:     $symb=&symbread();
1.620     albertel 2571:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2572:   }
                   2573:   $symb=escape($symb);
                   2574: 
1.620     albertel 2575:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2576:   $namespace=~s/\//\_/g;
                   2577:   $namespace=~s/\W//g;
                   2578: 
1.620     albertel 2579:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2580:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2581:   if ($domain eq 'public' && $stuname eq 'public') {
                   2582:       $stuname=$ENV{'REMOTE_ADDR'};
                   2583:   }
1.168     albertel 2584:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2585:   my %hash;
                   2586:   if (tie(%hash,'GDBM_File',
                   2587: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2588: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2589:     foreach my $key (keys %hash) {
1.180     albertel 2590:       if ($key=~ /:$symb/) {
1.168     albertel 2591: 	delete($hash{$key});
                   2592:       }
                   2593:     }
                   2594:   }
                   2595: }
                   2596: 
1.167     albertel 2597: sub tmpstore {
1.168     albertel 2598:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2599: 
                   2600:   if (!$symb) {
                   2601:     $symb=&symbread();
1.620     albertel 2602:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2603:   }
                   2604:   $symb=escape($symb);
                   2605: 
                   2606:   if (!$namespace) {
                   2607:     # I don't think we would ever want to store this for a course.
                   2608:     # it seems this will only be used if we don't have a course.
1.620     albertel 2609:     #$namespace=$env{'request.course.id'};
1.168     albertel 2610:     #if (!$namespace) {
1.620     albertel 2611:       $namespace=$env{'request.state'};
1.168     albertel 2612:     #}
                   2613:   }
                   2614:   $namespace=~s/\//\_/g;
                   2615:   $namespace=~s/\W//g;
1.620     albertel 2616:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2617:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2618:   if ($domain eq 'public' && $stuname eq 'public') {
                   2619:       $stuname=$ENV{'REMOTE_ADDR'};
                   2620:   }
1.168     albertel 2621:   my $now=time;
                   2622:   my %hash;
                   2623:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2624:   if (tie(%hash,'GDBM_File',
                   2625: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2626: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2627:     $hash{"version:$symb"}++;
                   2628:     my $version=$hash{"version:$symb"};
                   2629:     my $allkeys=''; 
                   2630:     foreach my $key (keys(%$storehash)) {
                   2631:       $allkeys.=$key.':';
1.591     albertel 2632:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2633:     }
                   2634:     $hash{"$version:$symb:timestamp"}=$now;
                   2635:     $allkeys.='timestamp';
                   2636:     $hash{"$version:keys:$symb"}=$allkeys;
                   2637:     if (untie(%hash)) {
                   2638:       return 'ok';
                   2639:     } else {
                   2640:       return "error:$!";
                   2641:     }
                   2642:   } else {
                   2643:     return "error:$!";
                   2644:   }
                   2645: }
1.167     albertel 2646: 
1.168     albertel 2647: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2648: 
1.168     albertel 2649: sub tmprestore {
                   2650:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2651: 
1.168     albertel 2652:   if (!$symb) {
                   2653:     $symb=&symbread();
1.620     albertel 2654:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2655:   }
                   2656:   $symb=escape($symb);
                   2657: 
1.620     albertel 2658:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2659: 
1.620     albertel 2660:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2661:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2662:   if ($domain eq 'public' && $stuname eq 'public') {
                   2663:       $stuname=$ENV{'REMOTE_ADDR'};
                   2664:   }
1.168     albertel 2665:   my %returnhash;
                   2666:   $namespace=~s/\//\_/g;
                   2667:   $namespace=~s/\W//g;
                   2668:   my %hash;
                   2669:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2670:   if (tie(%hash,'GDBM_File',
                   2671: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2672: 	  &GDBM_READER(),0640)) {
1.168     albertel 2673:     my $version=$hash{"version:$symb"};
                   2674:     $returnhash{'version'}=$version;
                   2675:     my $scope;
                   2676:     for ($scope=1;$scope<=$version;$scope++) {
                   2677:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2678:       my @keys=split(/:/,$vkeys);
                   2679:       my $key;
                   2680:       $returnhash{"$scope:keys"}=$vkeys;
                   2681:       foreach $key (@keys) {
1.591     albertel 2682: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2683: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2684:       }
                   2685:     }
1.168     albertel 2686:     if (!(untie(%hash))) {
                   2687:       return "error:$!";
                   2688:     }
                   2689:   } else {
                   2690:     return "error:$!";
                   2691:   }
                   2692:   return %returnhash;
1.167     albertel 2693: }
                   2694: 
1.9       www      2695: # ----------------------------------------------------------------------- Store
                   2696: 
                   2697: sub store {
1.124     www      2698:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2699:     my $home='';
                   2700: 
1.168     albertel 2701:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2702: 
1.213     www      2703:     $symb=&symbclean($symb);
1.122     albertel 2704:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2705: 
1.620     albertel 2706:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2707:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2708: 
                   2709:     &devalidate($symb,$stuname,$domain);
1.109     www      2710: 
                   2711:     $symb=escape($symb);
1.187     www      2712:     if (!$namespace) { 
1.620     albertel 2713:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2714:           return ''; 
                   2715:        } 
                   2716:     }
1.620     albertel 2717:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2718: 
                   2719:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2720:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2721: 
1.12      www      2722:     my $namevalue='';
1.800     albertel 2723:     foreach my $key (keys(%$storehash)) {
                   2724:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2725:     }
1.12      www      2726:     $namevalue=~s/\&$//;
1.187     www      2727:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2728:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2729: }
                   2730: 
1.47      www      2731: # -------------------------------------------------------------- Critical Store
                   2732: 
                   2733: sub cstore {
1.124     www      2734:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2735:     my $home='';
                   2736: 
1.168     albertel 2737:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2738: 
1.213     www      2739:     $symb=&symbclean($symb);
1.122     albertel 2740:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2741: 
1.620     albertel 2742:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2743:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2744: 
                   2745:     &devalidate($symb,$stuname,$domain);
1.109     www      2746: 
                   2747:     $symb=escape($symb);
1.187     www      2748:     if (!$namespace) { 
1.620     albertel 2749:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2750:           return ''; 
                   2751:        } 
                   2752:     }
1.620     albertel 2753:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2754: 
                   2755:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2756:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2757: 
1.47      www      2758:     my $namevalue='';
1.800     albertel 2759:     foreach my $key (keys(%$storehash)) {
                   2760:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2761:     }
1.47      www      2762:     $namevalue=~s/\&$//;
1.187     www      2763:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2764:     return critical
                   2765:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2766: }
                   2767: 
1.9       www      2768: # --------------------------------------------------------------------- Restore
                   2769: 
                   2770: sub restore {
1.124     www      2771:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2772:     my $home='';
                   2773: 
1.168     albertel 2774:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2775: 
1.122     albertel 2776:     if (!$symb) {
                   2777:       unless ($symb=escape(&symbread())) { return ''; }
                   2778:     } else {
1.213     www      2779:       $symb=&escape(&symbclean($symb));
1.122     albertel 2780:     }
1.188     www      2781:     if (!$namespace) { 
1.620     albertel 2782:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2783:           return ''; 
                   2784:        } 
                   2785:     }
1.620     albertel 2786:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2787:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2788:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2789:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2790: 
1.12      www      2791:     my %returnhash=();
1.800     albertel 2792:     foreach my $line (split(/\&/,$answer)) {
                   2793: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2794:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2795:     }
1.75      www      2796:     my $version;
                   2797:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2798:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2799:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2800:        }
1.75      www      2801:     }
1.13      www      2802:     return %returnhash;
1.34      www      2803: }
                   2804: 
                   2805: # ---------------------------------------------------------- Course Description
                   2806: 
                   2807: sub coursedescription {
1.731     albertel 2808:     my ($courseid,$args)=@_;
1.34      www      2809:     $courseid=~s/^\///;
1.49      www      2810:     $courseid=~s/\_/\//g;
1.34      www      2811:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2812:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2813:     my $normalid=$cdomain.'_'.$cnum;
                   2814:     # need to always cache even if we get errors otherwise we keep 
                   2815:     # trying and trying and trying to get the course description.
                   2816:     my %envhash=();
                   2817:     my %returnhash=();
1.731     albertel 2818:     
                   2819:     my $expiretime=600;
                   2820:     if ($env{'request.course.id'} eq $normalid) {
                   2821: 	$expiretime=120;
                   2822:     }
                   2823: 
                   2824:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2825:     if (!$args->{'freshen_cache'}
                   2826: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2827: 	foreach my $key (keys(%env)) {
                   2828: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2829: 	    my ($setting) = $1;
                   2830: 	    $returnhash{$setting} = $env{$key};
                   2831: 	}
                   2832: 	return %returnhash;
                   2833:     }
                   2834: 
                   2835:     # get the data agin
                   2836:     if (!$args->{'one_time'}) {
                   2837: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2838:     }
1.811     albertel 2839: 
1.34      www      2840:     if ($chome ne 'no_host') {
1.302     albertel 2841:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2842:        if (!exists($returnhash{'con_lost'})) {
                   2843:            $returnhash{'home'}= $chome;
                   2844: 	   $returnhash{'domain'} = $cdomain;
                   2845: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2846:            if (!defined($returnhash{'type'})) {
                   2847:                $returnhash{'type'} = 'Course';
                   2848:            }
1.130     albertel 2849:            while (my ($name,$value) = each %returnhash) {
1.53      www      2850:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2851:            }
1.270     www      2852:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2853:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2854: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2855:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2856:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2857:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2858:        }
                   2859:     }
1.731     albertel 2860:     if (!$args->{'one_time'}) {
                   2861: 	&appenv(%envhash);
                   2862:     }
1.302     albertel 2863:     return %returnhash;
1.461     www      2864: }
                   2865: 
                   2866: # -------------------------------------------------See if a user is privileged
                   2867: 
                   2868: sub privileged {
                   2869:     my ($username,$domain)=@_;
                   2870:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2871: 			&homeserver($username,$domain));
                   2872:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2873:     my $now=time;
                   2874:     if ($rolesdump ne '') {
1.800     albertel 2875:         foreach my $entry (split(/&/,$rolesdump)) {
                   2876: 	    if ($entry!~/^rolesdef_/) {
                   2877: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2878: 		$area=~s/\_\w\w$//;
                   2879: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2880: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2881: 		    my $active=1;
                   2882: 		    if ($tend) {
                   2883: 			if ($tend<$now) { $active=0; }
                   2884: 		    }
                   2885: 		    if ($tstart) {
                   2886: 			if ($tstart>$now) { $active=0; }
                   2887: 		    }
                   2888: 		    if ($active) { return 1; }
                   2889: 		}
                   2890: 	    }
                   2891: 	}
                   2892:     }
                   2893:     return 0;
1.9       www      2894: }
1.1       albertel 2895: 
1.103     harris41 2896: # -------------------------------------------------------- Get user privileges
1.11      www      2897: 
                   2898: sub rolesinit {
                   2899:     my ($domain,$username,$authhost)=@_;
                   2900:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2901:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2902:     my %allroles=();
1.678     raeburn  2903:     my %allgroups=();   
1.11      www      2904:     my $now=time;
1.743     albertel 2905:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2906:     my $group_privs;
1.11      www      2907: 
                   2908:     if ($rolesdump ne '') {
1.800     albertel 2909:         foreach my $entry (split(/&/,$rolesdump)) {
                   2910: 	  if ($entry!~/^rolesdef_/) {
                   2911:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2912: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2913:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2914: 	    if ($role=~/^cr/) { 
1.807     albertel 2915: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2916: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2917: 		    ($tend,$tstart)=split('_',$trest);
                   2918: 		} else {
                   2919: 		    $trole=$role;
                   2920: 		}
1.678     raeburn  2921:             } elsif ($role =~ m|^gr/|) {
                   2922:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2923:                 ($trole,$group_privs) = split(/\//,$trole);
                   2924:                 $group_privs = &unescape($group_privs);
1.587     albertel 2925: 	    } else {
                   2926: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2927: 	    }
1.743     albertel 2928: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2929: 					 $username);
                   2930: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2931:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2932:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2933:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2934: 		my $spec=$trole.'.'.$area;
                   2935: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2936: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2937:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2938:                 } elsif ($trole eq 'gr') {
                   2939:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2940: 		} else {
1.567     raeburn  2941:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2942: 		}
1.12      www      2943:             }
1.662     raeburn  2944:           }
1.191     harris41 2945:         }
1.743     albertel 2946:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2947:         $userroles{'user.adv'}    = $adv;
                   2948: 	$userroles{'user.author'} = $author;
1.620     albertel 2949:         $env{'user.adv'}=$adv;
1.11      www      2950:     }
1.743     albertel 2951:     return \%userroles;  
1.11      www      2952: }
                   2953: 
1.567     raeburn  2954: sub set_arearole {
                   2955:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2956: # log the associated role with the area
                   2957:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2958:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2959: }
                   2960: 
                   2961: sub custom_roleprivs {
                   2962:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2963:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2964:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 2965:     if (&hostname($homsvr) ne '') {
1.567     raeburn  2966:         my ($rdummy,$roledef)=
                   2967:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2968:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2969:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2970:             if (defined($syspriv)) {
                   2971:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2972:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2973:             }
                   2974:             if ($tdomain ne '') {
                   2975:                 if (defined($dompriv)) {
                   2976:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2977:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2978:                 }
                   2979:                 if (($trest ne '') && (defined($coursepriv))) {
                   2980:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2981:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2982:                 }
                   2983:             }
                   2984:         }
                   2985:     }
                   2986: }
                   2987: 
1.678     raeburn  2988: sub group_roleprivs {
                   2989:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2990:     my $access = 1;
                   2991:     my $now = time;
                   2992:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2993:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2994:     if ($access) {
1.811     albertel 2995:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2996:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2997:     }
                   2998: }
1.567     raeburn  2999: 
                   3000: sub standard_roleprivs {
                   3001:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3002:     if (defined($pr{$trole.':s'})) {
                   3003:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3004:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3005:     }
                   3006:     if ($tdomain ne '') {
                   3007:         if (defined($pr{$trole.':d'})) {
                   3008:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3009:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3010:         }
                   3011:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3012:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3013:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3014:         }
                   3015:     }
                   3016: }
                   3017: 
                   3018: sub set_userprivs {
1.678     raeburn  3019:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3020:     my $author=0;
                   3021:     my $adv=0;
1.678     raeburn  3022:     my %grouproles = ();
                   3023:     if (keys(%{$allgroups}) > 0) {
                   3024:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3025:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3026:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3027:                 $trole = $1;
                   3028:                 $area = $2;
1.681     raeburn  3029:                 $sec = $3;
                   3030:                 $extendedarea = $area.$sec;
                   3031:                 if (exists($$allgroups{$area})) {
                   3032:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3033:                         my $spec = $trole.'.'.$extendedarea;
                   3034:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3035:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3036:                     }
                   3037:                 }
                   3038:             }
                   3039:         }
                   3040:     }
1.800     albertel 3041:     foreach my $group (keys(%grouproles)) {
                   3042:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3043:     }
1.800     albertel 3044:     foreach my $role (keys(%{$allroles})) {
                   3045:         my %thesepriv;
                   3046:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3047:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3048:             if ($item ne '') {
                   3049:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3050:                 if ($restrictions eq '') {
                   3051:                     $thesepriv{$privilege}='F';
                   3052:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3053:                     $thesepriv{$privilege}.=$restrictions;
                   3054:                 }
                   3055:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3056:             }
                   3057:         }
                   3058:         my $thesestr='';
1.800     albertel 3059:         foreach my $priv (keys(%thesepriv)) {
                   3060: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3061: 	}
                   3062:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3063:     }
                   3064:     return ($author,$adv);
                   3065: }
                   3066: 
1.12      www      3067: # --------------------------------------------------------------- get interface
                   3068: 
                   3069: sub get {
1.131     albertel 3070:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3071:    my $items='';
1.800     albertel 3072:    foreach my $item (@$storearr) {
                   3073:        $items.=&escape($item).'&';
1.191     harris41 3074:    }
1.12      www      3075:    $items=~s/\&$//;
1.620     albertel 3076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3077:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3078:    my $uhome=&homeserver($uname,$udomain);
                   3079: 
1.133     albertel 3080:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3081:    my @pairs=split(/\&/,$rep);
1.273     albertel 3082:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3083:      return @pairs;
                   3084:    }
1.15      www      3085:    my %returnhash=();
1.42      www      3086:    my $i=0;
1.800     albertel 3087:    foreach my $item (@$storearr) {
                   3088:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3089:       $i++;
1.191     harris41 3090:    }
1.15      www      3091:    return %returnhash;
1.27      www      3092: }
                   3093: 
                   3094: # --------------------------------------------------------------- del interface
                   3095: 
                   3096: sub del {
1.133     albertel 3097:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3098:    my $items='';
1.800     albertel 3099:    foreach my $item (@$storearr) {
                   3100:        $items.=&escape($item).'&';
1.191     harris41 3101:    }
1.27      www      3102:    $items=~s/\&$//;
1.620     albertel 3103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3104:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3105:    my $uhome=&homeserver($uname,$udomain);
                   3106: 
                   3107:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3108: }
                   3109: 
                   3110: # -------------------------------------------------------------- dump interface
                   3111: 
                   3112: sub dump {
1.755     albertel 3113:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3114:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3115:     if (!$uname) { $uname=$env{'user.name'}; }
                   3116:     my $uhome=&homeserver($uname,$udomain);
                   3117:     if ($regexp) {
                   3118: 	$regexp=&escape($regexp);
                   3119:     } else {
                   3120: 	$regexp='.';
                   3121:     }
                   3122:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3123:     my @pairs=split(/\&/,$rep);
                   3124:     my %returnhash=();
                   3125:     foreach my $item (@pairs) {
                   3126: 	my ($key,$value)=split(/=/,$item,2);
                   3127: 	$key = &unescape($key);
                   3128: 	next if ($key =~ /^error: 2 /);
                   3129: 	$returnhash{$key}=&thaw_unescape($value);
                   3130:     }
                   3131:     return %returnhash;
1.407     www      3132: }
                   3133: 
1.717     albertel 3134: # --------------------------------------------------------- dumpstore interface
                   3135: 
                   3136: sub dumpstore {
                   3137:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3138:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3139:    if (!$uname) { $uname=$env{'user.name'}; }
                   3140:    my $uhome=&homeserver($uname,$udomain);
                   3141:    if ($regexp) {
                   3142:        $regexp=&escape($regexp);
                   3143:    } else {
                   3144:        $regexp='.';
                   3145:    }
                   3146:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3147:    my @pairs=split(/\&/,$rep);
                   3148:    my %returnhash=();
                   3149:    foreach my $item (@pairs) {
                   3150:        my ($key,$value)=split(/=/,$item,2);
                   3151:        next if ($key =~ /^error: 2 /);
                   3152:        $returnhash{$key}=&thaw_unescape($value);
                   3153:    }
                   3154:    return %returnhash;
1.717     albertel 3155: }
                   3156: 
1.407     www      3157: # -------------------------------------------------------------- keys interface
                   3158: 
                   3159: sub getkeys {
                   3160:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3161:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3162:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3163:    my $uhome=&homeserver($uname,$udomain);
                   3164:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3165:    my @keyarray=();
1.800     albertel 3166:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3167:       next if ($key =~ /^error: 2 /);
1.800     albertel 3168:       push(@keyarray,&unescape($key));
1.407     www      3169:    }
                   3170:    return @keyarray;
1.318     matthew  3171: }
                   3172: 
1.319     matthew  3173: # --------------------------------------------------------------- currentdump
                   3174: sub currentdump {
1.328     matthew  3175:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3176:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3177:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3178:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3179:    my $uhome = &homeserver($sname,$sdom);
                   3180:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3181:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3182:    #
1.318     matthew  3183:    my %returnhash=();
1.319     matthew  3184:    #
                   3185:    if ($rep eq "unknown_cmd") { 
                   3186:        # an old lond will not know currentdump
                   3187:        # Do a dump and make it look like a currentdump
1.822     albertel 3188:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3189:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3190:        my %hash = @tmp;
                   3191:        @tmp=();
1.424     matthew  3192:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3193:    } else {
                   3194:        my @pairs=split(/\&/,$rep);
1.800     albertel 3195:        foreach my $pair (@pairs) {
                   3196:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3197:            my ($symb,$param) = split(/:/,$key);
                   3198:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3199:                                                         &thaw_unescape($value);
1.319     matthew  3200:        }
1.191     harris41 3201:    }
1.12      www      3202:    return %returnhash;
1.424     matthew  3203: }
                   3204: 
                   3205: sub convert_dump_to_currentdump{
                   3206:     my %hash = %{shift()};
                   3207:     my %returnhash;
                   3208:     # Code ripped from lond, essentially.  The only difference
                   3209:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3210:     # we might run in to problems with parameter names =~ /^v\./
                   3211:     while (my ($key,$value) = each(%hash)) {
                   3212:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3213: 	$symb  = &unescape($symb);
                   3214: 	$param = &unescape($param);
1.424     matthew  3215:         next if ($v eq 'version' || $symb eq 'keys');
                   3216:         next if (exists($returnhash{$symb}) &&
                   3217:                  exists($returnhash{$symb}->{$param}) &&
                   3218:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3219:         $returnhash{$symb}->{$param}=$value;
                   3220:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3221:     }
                   3222:     #
                   3223:     # Remove all of the keys in the hashes which keep track of
                   3224:     # the version of the parameter.
                   3225:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3226:         # use a foreach because we are going to delete from the hash.
                   3227:         foreach my $key (keys(%$param_hash)) {
                   3228:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3229:         }
                   3230:     }
                   3231:     return \%returnhash;
1.12      www      3232: }
                   3233: 
1.627     albertel 3234: # ------------------------------------------------------ critical inc interface
                   3235: 
                   3236: sub cinc {
                   3237:     return &inc(@_,'critical');
                   3238: }
                   3239: 
1.449     matthew  3240: # --------------------------------------------------------------- inc interface
                   3241: 
                   3242: sub inc {
1.627     albertel 3243:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3244:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3245:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3246:     my $uhome=&homeserver($uname,$udomain);
                   3247:     my $items='';
                   3248:     if (! ref($store)) {
                   3249:         # got a single value, so use that instead
                   3250:         $items = &escape($store).'=&';
                   3251:     } elsif (ref($store) eq 'SCALAR') {
                   3252:         $items = &escape($$store).'=&';        
                   3253:     } elsif (ref($store) eq 'ARRAY') {
                   3254:         $items = join('=&',map {&escape($_);} @{$store});
                   3255:     } elsif (ref($store) eq 'HASH') {
                   3256:         while (my($key,$value) = each(%{$store})) {
                   3257:             $items.= &escape($key).'='.&escape($value).'&';
                   3258:         }
                   3259:     }
                   3260:     $items=~s/\&$//;
1.627     albertel 3261:     if ($critical) {
                   3262: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3263:     } else {
                   3264: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3265:     }
1.449     matthew  3266: }
                   3267: 
1.12      www      3268: # --------------------------------------------------------------- put interface
                   3269: 
                   3270: sub put {
1.134     albertel 3271:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3272:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3273:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3274:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3275:    my $items='';
1.800     albertel 3276:    foreach my $item (keys(%$storehash)) {
                   3277:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3278:    }
1.12      www      3279:    $items=~s/\&$//;
1.134     albertel 3280:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3281: }
                   3282: 
1.631     albertel 3283: # ------------------------------------------------------------ newput interface
                   3284: 
                   3285: sub newput {
                   3286:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3287:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3288:    if (!$uname) { $uname=$env{'user.name'}; }
                   3289:    my $uhome=&homeserver($uname,$udomain);
                   3290:    my $items='';
                   3291:    foreach my $key (keys(%$storehash)) {
                   3292:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3293:    }
                   3294:    $items=~s/\&$//;
                   3295:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3296: }
                   3297: 
                   3298: # ---------------------------------------------------------  putstore interface
                   3299: 
1.524     raeburn  3300: sub putstore {
1.715     albertel 3301:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3302:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3303:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3304:    my $uhome=&homeserver($uname,$udomain);
                   3305:    my $items='';
1.715     albertel 3306:    foreach my $key (keys(%$storehash)) {
                   3307:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3308:    }
1.715     albertel 3309:    $items=~s/\&$//;
1.716     albertel 3310:    my $esc_symb=&escape($symb);
                   3311:    my $esc_v=&escape($version);
1.715     albertel 3312:    my $reply =
1.716     albertel 3313:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3314: 	      $uhome);
                   3315:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3316:        # gfall back to way things use to be done
1.715     albertel 3317:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3318: 			    $uname);
1.524     raeburn  3319:    }
1.715     albertel 3320:    return $reply;
                   3321: }
                   3322: 
                   3323: sub old_putstore {
1.716     albertel 3324:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3325:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3326:     if (!$uname) { $uname=$env{'user.name'}; }
                   3327:     my $uhome=&homeserver($uname,$udomain);
                   3328:     my %newstorehash;
1.800     albertel 3329:     foreach my $item (keys(%$storehash)) {
                   3330: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3331: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3332:     }
                   3333:     my $items='';
                   3334:     my %allitems = ();
1.800     albertel 3335:     foreach my $item (keys(%newstorehash)) {
                   3336: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3337: 	    my $key = $1.':keys:'.$2;
                   3338: 	    $allitems{$key} .= $3.':';
                   3339: 	}
1.800     albertel 3340: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3341:     }
1.800     albertel 3342:     foreach my $item (keys(%allitems)) {
                   3343: 	$allitems{$item} =~ s/\:$//;
                   3344: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3345:     }
                   3346:     $items=~s/\&$//;
                   3347:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3348: }
                   3349: 
1.47      www      3350: # ------------------------------------------------------ critical put interface
                   3351: 
                   3352: sub cput {
1.134     albertel 3353:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3354:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3355:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3356:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3357:    my $items='';
1.800     albertel 3358:    foreach my $item (keys(%$storehash)) {
                   3359:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3360:    }
1.47      www      3361:    $items=~s/\&$//;
1.134     albertel 3362:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3363: }
                   3364: 
                   3365: # -------------------------------------------------------------- eget interface
                   3366: 
                   3367: sub eget {
1.133     albertel 3368:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3369:    my $items='';
1.800     albertel 3370:    foreach my $item (@$storearr) {
                   3371:        $items.=&escape($item).'&';
1.191     harris41 3372:    }
1.12      www      3373:    $items=~s/\&$//;
1.620     albertel 3374:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3375:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3376:    my $uhome=&homeserver($uname,$udomain);
                   3377:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3378:    my @pairs=split(/\&/,$rep);
                   3379:    my %returnhash=();
1.42      www      3380:    my $i=0;
1.800     albertel 3381:    foreach my $item (@$storearr) {
                   3382:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3383:       $i++;
1.191     harris41 3384:    }
1.12      www      3385:    return %returnhash;
                   3386: }
                   3387: 
1.667     albertel 3388: # ------------------------------------------------------------ tmpput interface
                   3389: sub tmpput {
1.802     raeburn  3390:     my ($storehash,$server,$context)=@_;
1.667     albertel 3391:     my $items='';
1.800     albertel 3392:     foreach my $item (keys(%$storehash)) {
                   3393: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3394:     }
                   3395:     $items=~s/\&$//;
1.802     raeburn  3396:     if (defined($context)) {
                   3397:         $items .= ':'.&escape($context);
                   3398:     }
1.667     albertel 3399:     return &reply("tmpput:$items",$server);
                   3400: }
                   3401: 
                   3402: # ------------------------------------------------------------ tmpget interface
                   3403: sub tmpget {
1.688     albertel 3404:     my ($token,$server)=@_;
                   3405:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3406:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3407:     my %returnhash;
                   3408:     foreach my $item (split(/\&/,$rep)) {
                   3409: 	my ($key,$value)=split(/=/,$item);
                   3410: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3411:     }
                   3412:     return %returnhash;
                   3413: }
                   3414: 
1.688     albertel 3415: # ------------------------------------------------------------ tmpget interface
                   3416: sub tmpdel {
                   3417:     my ($token,$server)=@_;
                   3418:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3419:     return &reply("tmpdel:$token",$server);
                   3420: }
                   3421: 
1.765     albertel 3422: # -------------------------------------------------- portfolio access checking
                   3423: 
                   3424: sub portfolio_access {
1.766     albertel 3425:     my ($requrl) = @_;
1.765     albertel 3426:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3427:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3428:     if ($result) {
                   3429:         my %setters;
                   3430:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3431:             my ($startblock,$endblock) =
                   3432:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3433:             if ($startblock && $endblock) {
                   3434:                 return 'B';
                   3435:             }
                   3436:         } else {
                   3437:             my ($startblock,$endblock) =
                   3438:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3439:             if ($startblock && $endblock) {
                   3440:                 return 'B';
                   3441:             }
                   3442:         }
                   3443:     }
1.765     albertel 3444:     if ($result eq 'ok') {
1.766     albertel 3445:        return 'F';
1.765     albertel 3446:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3447:        return 'A';
1.765     albertel 3448:     }
1.766     albertel 3449:     return '';
1.765     albertel 3450: }
                   3451: 
                   3452: sub get_portfolio_access {
1.767     albertel 3453:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3454: 
                   3455:     if (!ref($access_hash)) {
                   3456: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3457: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3458: 						   $file_name);
                   3459: 	$access_hash = $access_controls{$file_name};
                   3460:     }
                   3461: 
1.765     albertel 3462:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3463:     my $now = time;
                   3464:     if (ref($access_hash) eq 'HASH') {
                   3465:         foreach my $key (keys(%{$access_hash})) {
                   3466:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3467:             if ($start > $now) {
                   3468:                 next;
                   3469:             }
                   3470:             if ($end && $end<$now) {
                   3471:                 next;
                   3472:             }
                   3473:             if ($scope eq 'public') {
                   3474:                 $public = $key;
                   3475:                 last;
                   3476:             } elsif ($scope eq 'guest') {
                   3477:                 $guest = $key;
                   3478:             } elsif ($scope eq 'domains') {
                   3479:                 push(@domains,$key);
                   3480:             } elsif ($scope eq 'users') {
                   3481:                 push(@users,$key);
                   3482:             } elsif ($scope eq 'course') {
                   3483:                 push(@courses,$key);
                   3484:             } elsif ($scope eq 'group') {
                   3485:                 push(@groups,$key);
                   3486:             }
                   3487:         }
                   3488:         if ($public) {
                   3489:             return 'ok';
                   3490:         }
                   3491:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3492:             if ($guest) {
                   3493:                 return $guest;
                   3494:             }
                   3495:         } else {
                   3496:             if (@domains > 0) {
                   3497:                 foreach my $domkey (@domains) {
                   3498:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3499:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3500:                             return 'ok';
                   3501:                         }
                   3502:                     }
                   3503:                 }
                   3504:             }
                   3505:             if (@users > 0) {
                   3506:                 foreach my $userkey (@users) {
                   3507:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3508:                         return 'ok';
                   3509:                     }
                   3510:                 }
                   3511:             }
                   3512:             my %roleshash;
                   3513:             my @courses_and_groups = @courses;
                   3514:             push(@courses_and_groups,@groups); 
                   3515:             if (@courses_and_groups > 0) {
                   3516:                 my (%allgroups,%allroles); 
                   3517:                 my ($start,$end,$role,$sec,$group);
                   3518:                 foreach my $envkey (%env) {
1.811     albertel 3519:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3520:                         my $cid = $2.'_'.$3; 
                   3521:                         if ($1 eq 'gr') {
                   3522:                             $group = $4;
                   3523:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3524:                         } else {
                   3525:                             if ($4 eq '') {
                   3526:                                 $sec = 'none';
                   3527:                             } else {
                   3528:                                 $sec = $4;
                   3529:                             }
                   3530:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3531:                         }
1.811     albertel 3532:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3533:                         my $cid = $2.'_'.$3;
                   3534:                         if ($4 eq '') {
                   3535:                             $sec = 'none';
                   3536:                         } else {
                   3537:                             $sec = $4;
                   3538:                         }
                   3539:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3540:                     }
                   3541:                 }
                   3542:                 if (keys(%allroles) == 0) {
                   3543:                     return;
                   3544:                 }
                   3545:                 foreach my $key (@courses_and_groups) {
                   3546:                     my %content = %{$$access_hash{$key}};
                   3547:                     my $cnum = $content{'number'};
                   3548:                     my $cdom = $content{'domain'};
                   3549:                     my $cid = $cdom.'_'.$cnum;
                   3550:                     if (!exists($allroles{$cid})) {
                   3551:                         next;
                   3552:                     }    
                   3553:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3554:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3555:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3556:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3557:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3558:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3559:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3560:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3561:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3562:                                         if (grep/^all$/,@sections) {
                   3563:                                             return 'ok';
                   3564:                                         } else {
                   3565:                                             if (grep/^$sec$/,@sections) {
                   3566:                                                 return 'ok';
                   3567:                                             }
                   3568:                                         }
                   3569:                                     }
                   3570:                                 }
                   3571:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3572:                                     if (grep/^none$/,@groups) {
                   3573:                                         return 'ok';
                   3574:                                     }
                   3575:                                 } else {
                   3576:                                     if (grep/^all$/,@groups) {
                   3577:                                         return 'ok';
                   3578:                                     } 
                   3579:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3580:                                         if (grep/^$group$/,@groups) {
                   3581:                                             return 'ok';
                   3582:                                         }
                   3583:                                     }
                   3584:                                 } 
                   3585:                             }
                   3586:                         }
                   3587:                     }
                   3588:                 }
                   3589:             }
                   3590:             if ($guest) {
                   3591:                 return $guest;
                   3592:             }
                   3593:         }
                   3594:     }
                   3595:     return;
                   3596: }
                   3597: 
                   3598: sub course_group_datechecker {
                   3599:     my ($dates,$now,$status) = @_;
                   3600:     my ($start,$end) = split(/\./,$dates);
                   3601:     if (!$start && !$end) {
                   3602:         return 'ok';
                   3603:     }
                   3604:     if (grep/^active$/,@{$status}) {
                   3605:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3606:             return 'ok';
                   3607:         }
                   3608:     }
                   3609:     if (grep/^previous$/,@{$status}) {
                   3610:         if ($end > $now ) {
                   3611:             return 'ok';
                   3612:         }
                   3613:     }
                   3614:     if (grep/^future$/,@{$status}) {
                   3615:         if ($start > $now) {
                   3616:             return 'ok';
                   3617:         }
                   3618:     }
                   3619:     return; 
                   3620: }
                   3621: 
                   3622: sub parse_portfolio_url {
                   3623:     my ($url) = @_;
                   3624: 
                   3625:     my ($type,$udom,$unum,$group,$file_name);
                   3626:     
1.823     albertel 3627:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3628: 	$type = 1;
                   3629:         $udom = $1;
                   3630:         $unum = $2;
                   3631:         $file_name = $3;
1.823     albertel 3632:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3633: 	$type = 2;
                   3634:         $udom = $1;
                   3635:         $unum = $2;
                   3636:         $group = $3;
                   3637:         $file_name = $3.'/'.$4;
                   3638:     }
                   3639:     if (wantarray) {
                   3640: 	return ($type,$udom,$unum,$file_name,$group);
                   3641:     }
                   3642:     return $type;
                   3643: }
                   3644: 
                   3645: sub is_portfolio_url {
                   3646:     my ($url) = @_;
                   3647:     return scalar(&parse_portfolio_url($url));
                   3648: }
                   3649: 
1.798     raeburn  3650: sub is_portfolio_file {
                   3651:     my ($file) = @_;
1.820     raeburn  3652:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3653:         return 1;
                   3654:     }
                   3655:     return;
                   3656: }
                   3657: 
                   3658: 
1.341     www      3659: # ---------------------------------------------- Custom access rule evaluation
                   3660: 
                   3661: sub customaccess {
                   3662:     my ($priv,$uri)=@_;
1.807     albertel 3663:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3664:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3665:     $udom = &LONCAPA::clean_domain($udom);
                   3666:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3667:     my $access=0;
1.800     albertel 3668:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3669: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3670:         if ($role) {
                   3671: 	   if ($role ne $urole) { next; }
                   3672:         }
1.800     albertel 3673:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3674:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3675:             if ($tdom) {
                   3676: 		if ($tdom ne $udom) { next; }
                   3677:             }
                   3678:             if ($tcrs) {
                   3679: 		if ($tcrs ne $ucrs) { next; }
                   3680:             }
                   3681:             if ($tsec) {
                   3682: 		if ($tsec ne $usec) { next; }
                   3683:             }
                   3684:             $access=($effect eq 'allow');
                   3685:             last;
1.342     www      3686:         }
1.402     bowersj2 3687: 	if ($realm eq '' && $role eq '') {
                   3688:             $access=($effect eq 'allow');
                   3689: 	}
1.341     www      3690:     }
                   3691:     return $access;
                   3692: }
                   3693: 
1.103     harris41 3694: # ------------------------------------------------- Check for a user privilege
1.12      www      3695: 
                   3696: sub allowed {
1.810     raeburn  3697:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3698:     my $ver_orguri=$uri;
1.439     www      3699:     $uri=&deversion($uri);
1.152     www      3700:     my $orguri=$uri;
1.52      www      3701:     $uri=&declutter($uri);
1.809     raeburn  3702: 
1.810     raeburn  3703:     if ($priv eq 'evb') {
                   3704: # Evade communication block restrictions for specified role in a course
                   3705:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3706:             return $1;
                   3707:         } else {
                   3708:             return;
                   3709:         }
                   3710:     }
                   3711: 
1.620     albertel 3712:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3713: # Free bre access to adm and meta resources
1.775     albertel 3714:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3715: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3716: 	&& ($priv eq 'bre')) {
1.14      www      3717: 	return 'F';
1.159     www      3718:     }
                   3719: 
1.545     banghart 3720: # Free bre access to user's own portfolio contents
1.714     raeburn  3721:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3722:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3723: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3724:         my %setters;
                   3725:         my ($startblock,$endblock) = 
                   3726:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3727:         if ($startblock && $endblock) {
                   3728:             return 'B';
                   3729:         } else {
                   3730:             return 'F';
                   3731:         }
1.545     banghart 3732:     }
                   3733: 
1.762     raeburn  3734: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3735:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3736:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3737:         if (exists($env{'request.course.id'})) {
                   3738:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3739:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3740:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3741:                 my $courseprivid=$env{'request.course.id'};
                   3742:                 $courseprivid=~s/\_/\//;
                   3743:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3744:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3745:                     return $1; 
1.762     raeburn  3746:                 } else {
                   3747:                     if ($env{'request.course.sec'}) {
                   3748:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3749:                     }
                   3750:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3751:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3752:                         return $2;
                   3753:                     }
1.714     raeburn  3754:                 }
                   3755:             }
                   3756:         }
                   3757:     }
                   3758: 
1.159     www      3759: # Free bre to public access
                   3760: 
                   3761:     if ($priv eq 'bre') {
1.238     www      3762:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3763: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3764:            return 'F'; 
                   3765:         }
1.238     www      3766:         if ($copyright eq 'priv') {
                   3767:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3768: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3769: 		return '';
                   3770:             }
                   3771:         }
                   3772:         if ($copyright eq 'domain') {
                   3773:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3774: 	    unless (($env{'user.domain'} eq $1) ||
                   3775:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3776: 		return '';
                   3777:             }
1.262     matthew  3778:         }
1.620     albertel 3779:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3780:             # Library role, so allow browsing of resources in this domain.
                   3781:             return 'F';
1.238     www      3782:         }
1.341     www      3783:         if ($copyright eq 'custom') {
                   3784: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3785:         }
1.14      www      3786:     }
1.264     matthew  3787:     # Domain coordinator is trying to create a course
1.620     albertel 3788:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3789:         # uri is the requested domain in this case.
                   3790:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3791:         # a role of dc for the domain in question.
1.620     albertel 3792:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3793:     }
1.29      www      3794: 
1.52      www      3795:     my $thisallowed='';
                   3796:     my $statecond=0;
                   3797:     my $courseprivid='';
                   3798: 
                   3799: # Course
                   3800: 
1.620     albertel 3801:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3802:        $thisallowed.=$1;
                   3803:     }
1.29      www      3804: 
1.52      www      3805: # Domain
                   3806: 
1.620     albertel 3807:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3808:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3809:        $thisallowed.=$1;
                   3810:     }
1.52      www      3811: 
                   3812: # Course: uri itself is a course
1.66      www      3813:     my $courseuri=$uri;
                   3814:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3815:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3816: 
1.620     albertel 3817:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3818:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3819:        $thisallowed.=$1;
                   3820:     }
1.29      www      3821: 
1.665     albertel 3822: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3823: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3824:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3825: 	$thisallowed='';
1.671     raeburn  3826:         my ($match)=&is_on_map($uri);
                   3827:         if ($match) {
                   3828:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3829:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3830:                 $thisallowed.=$1;
                   3831:             }
                   3832:         } else {
1.705     albertel 3833:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3834:             if ($refuri) {
                   3835:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3836:                     $thisallowed='F';
1.671     raeburn  3837:                 } else {
                   3838:                     $refuri=&declutter($refuri);
                   3839:                     my ($match) = &is_on_map($refuri);
                   3840:                     if ($match) {
                   3841:                         $thisallowed='F';
                   3842:                     }
1.669     raeburn  3843:                 }
1.671     raeburn  3844:             }
                   3845:         }
1.314     www      3846:     }
1.492     albertel 3847: 
1.766     albertel 3848:     if ($priv eq 'bre'
                   3849: 	&& $thisallowed ne 'F' 
                   3850: 	&& $thisallowed ne '2'
                   3851: 	&& &is_portfolio_url($uri)) {
                   3852: 	$thisallowed = &portfolio_access($uri);
                   3853:     }
                   3854:     
1.52      www      3855: # Full access at system, domain or course-wide level? Exit.
1.29      www      3856: 
                   3857:     if ($thisallowed=~/F/) {
                   3858: 	return 'F';
                   3859:     }
                   3860: 
1.52      www      3861: # If this is generating or modifying users, exit with special codes
1.29      www      3862: 
1.643     www      3863:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3864: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3865: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3866: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3867: 	    unless ($auname) { return $thisallowed; }
                   3868: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3869: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3870: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3871: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3872: 	}
1.52      www      3873: 	return $thisallowed;
                   3874:     }
                   3875: #
1.103     harris41 3876: # Gathered so far: system, domain and course wide privileges
1.52      www      3877: #
                   3878: # Course: See if uri or referer is an individual resource that is part of 
                   3879: # the course
                   3880: 
1.620     albertel 3881:     if ($env{'request.course.id'}) {
1.232     www      3882: 
1.620     albertel 3883:        $courseprivid=$env{'request.course.id'};
                   3884:        if ($env{'request.course.sec'}) {
                   3885:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3886:        }
                   3887:        $courseprivid=~s/\_/\//;
                   3888:        my $checkreferer=1;
1.232     www      3889:        my ($match,$cond)=&is_on_map($uri);
                   3890:        if ($match) {
                   3891:            $statecond=$cond;
1.620     albertel 3892:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3893:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3894:                $thisallowed.=$1;
                   3895:                $checkreferer=0;
                   3896:            }
1.29      www      3897:        }
1.83      www      3898:        
1.148     www      3899:        if ($checkreferer) {
1.620     albertel 3900: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3901:             unless ($refuri) {
1.800     albertel 3902:                 foreach my $key (keys(%env)) {
                   3903: 		    if ($key=~/^httpref\..*\*/) {
                   3904: 			my $pattern=$key;
1.156     www      3905:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3906:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3907:                         $pattern=~s/\//\\\//g;
1.152     www      3908:                         if ($orguri=~/$pattern/) {
1.800     albertel 3909: 			    $refuri=$env{$key};
1.148     www      3910:                         }
                   3911:                     }
1.191     harris41 3912:                 }
1.148     www      3913:             }
1.232     www      3914: 
1.148     www      3915:          if ($refuri) { 
1.152     www      3916: 	  $refuri=&declutter($refuri);
1.232     www      3917:           my ($match,$cond)=&is_on_map($refuri);
                   3918:             if ($match) {
                   3919:               my $refstatecond=$cond;
1.620     albertel 3920:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3921:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3922:                   $thisallowed.=$1;
1.53      www      3923:                   $uri=$refuri;
                   3924:                   $statecond=$refstatecond;
1.52      www      3925:               }
                   3926:           }
1.148     www      3927:         }
1.29      www      3928:        }
1.52      www      3929:    }
1.29      www      3930: 
1.52      www      3931: #
1.103     harris41 3932: # Gathered now: all privileges that could apply, and condition number
1.52      www      3933: # 
                   3934: #
                   3935: # Full or no access?
                   3936: #
1.29      www      3937: 
1.52      www      3938:     if ($thisallowed=~/F/) {
                   3939: 	return 'F';
                   3940:     }
1.29      www      3941: 
1.52      www      3942:     unless ($thisallowed) {
                   3943:         return '';
                   3944:     }
1.29      www      3945: 
1.52      www      3946: # Restrictions exist, deal with them
                   3947: #
                   3948: #   C:according to course preferences
                   3949: #   R:according to resource settings
                   3950: #   L:unless locked
                   3951: #   X:according to user session state
                   3952: #
                   3953: 
                   3954: # Possibly locked functionality, check all courses
1.54      www      3955: # Locks might take effect only after 10 minutes cache expiration for other
                   3956: # courses, and 2 minutes for current course
1.52      www      3957: 
                   3958:     my $envkey;
                   3959:     if ($thisallowed=~/L/) {
1.620     albertel 3960:         foreach $envkey (keys %env) {
1.54      www      3961:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3962:                my $courseid=$2;
                   3963:                my $roleid=$1.'.'.$2;
1.92      www      3964:                $courseid=~s/^\///;
1.54      www      3965:                my $expiretime=600;
1.620     albertel 3966:                if ($env{'request.role'} eq $roleid) {
1.54      www      3967: 		  $expiretime=120;
                   3968:                }
                   3969: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3970:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3971:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3972: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3973:                }
1.620     albertel 3974:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3975:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3976: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3977:                        &log($env{'user.domain'},$env{'user.name'},
                   3978:                             $env{'user.home'},
1.57      www      3979:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3980:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3981:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3982: 		       return '';
                   3983:                    }
                   3984:                }
1.620     albertel 3985:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3986:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3987: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3988:                        &log($env{'user.domain'},$env{'user.name'},
                   3989:                             $env{'user.home'},
1.57      www      3990:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3991:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3992:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3993: 		       return '';
                   3994:                    }
                   3995:                }
                   3996: 	   }
1.29      www      3997:        }
1.52      www      3998:     }
                   3999:    
                   4000: #
                   4001: # Rest of the restrictions depend on selected course
                   4002: #
                   4003: 
1.620     albertel 4004:     unless ($env{'request.course.id'}) {
1.766     albertel 4005: 	if ($thisallowed eq 'A') {
                   4006: 	    return 'A';
1.814     raeburn  4007:         } elsif ($thisallowed eq 'B') {
                   4008:             return 'B';
1.766     albertel 4009: 	} else {
                   4010: 	    return '1';
                   4011: 	}
1.52      www      4012:     }
1.29      www      4013: 
1.52      www      4014: #
                   4015: # Now user is definitely in a course
                   4016: #
1.53      www      4017: 
                   4018: 
                   4019: # Course preferences
                   4020: 
                   4021:    if ($thisallowed=~/C/) {
1.620     albertel 4022:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4023:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4024:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4025: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4026: 	   if ($priv ne 'pch') { 
                   4027: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4028: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4029: 			$env{'request.course.id'});
                   4030: 	   }
1.237     www      4031:            return '';
                   4032:        }
                   4033: 
1.620     albertel 4034:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4035: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4036: 	   if ($priv ne 'pch') { 
                   4037: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4038: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4039: 			$env{'request.course.id'});
                   4040: 	   }
1.54      www      4041:            return '';
                   4042:        }
1.53      www      4043:    }
                   4044: 
                   4045: # Resource preferences
                   4046: 
                   4047:    if ($thisallowed=~/R/) {
1.620     albertel 4048:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4049:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4050: 	   if ($priv ne 'pch') { 
                   4051: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4052: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4053: 	   }
                   4054: 	   return '';
1.54      www      4055:        }
1.53      www      4056:    }
1.30      www      4057: 
1.246     www      4058: # Restricted by state or randomout?
1.30      www      4059: 
1.52      www      4060:    if ($thisallowed=~/X/) {
1.620     albertel 4061:       if ($env{'acc.randomout'}) {
1.579     albertel 4062: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4063:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4064:             return ''; 
                   4065:          }
1.247     www      4066:       }
                   4067:       if (&condval($statecond)) {
1.52      www      4068: 	 return '2';
                   4069:       } else {
                   4070:          return '';
                   4071:       }
                   4072:    }
1.30      www      4073: 
1.766     albertel 4074:     if ($thisallowed eq 'A') {
                   4075: 	return 'A';
1.814     raeburn  4076:     } elsif ($thisallowed eq 'B') {
                   4077:         return 'B';
1.766     albertel 4078:     }
1.52      www      4079:    return 'F';
1.232     www      4080: }
                   4081: 
1.710     albertel 4082: sub split_uri_for_cond {
                   4083:     my $uri=&deversion(&declutter(shift));
                   4084:     my @uriparts=split(/\//,$uri);
                   4085:     my $filename=pop(@uriparts);
                   4086:     my $pathname=join('/',@uriparts);
                   4087:     return ($pathname,$filename);
                   4088: }
1.232     www      4089: # --------------------------------------------------- Is a resource on the map?
                   4090: 
                   4091: sub is_on_map {
1.710     albertel 4092:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4093:     #Trying to find the conditional for the file
1.620     albertel 4094:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4095: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4096:     if ($match) {
1.289     bowersj2 4097: 	return (1,$1);
                   4098:     } else {
1.434     www      4099: 	return (0,0);
1.289     bowersj2 4100:     }
1.12      www      4101: }
                   4102: 
1.427     www      4103: # --------------------------------------------------------- Get symb from alias
                   4104: 
                   4105: sub get_symb_from_alias {
                   4106:     my $symb=shift;
                   4107:     my ($map,$resid,$url)=&decode_symb($symb);
                   4108: # Already is a symb
                   4109:     if ($url) { return $symb; }
                   4110: # Must be an alias
                   4111:     my $aliassymb='';
                   4112:     my %bighash;
1.620     albertel 4113:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4114:                             &GDBM_READER(),0640)) {
                   4115:         my $rid=$bighash{'mapalias_'.$symb};
                   4116: 	if ($rid) {
                   4117: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4118: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4119: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4120: 	}
                   4121:         untie %bighash;
                   4122:     }
                   4123:     return $aliassymb;
                   4124: }
                   4125: 
1.12      www      4126: # ----------------------------------------------------------------- Define Role
                   4127: 
                   4128: sub definerole {
                   4129:   if (allowed('mcr','/')) {
                   4130:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4131:     foreach my $role (split(':',$sysrole)) {
                   4132: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4133:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4134:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4135: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4136:                return "refused:s:$crole&$cqual"; 
                   4137:             }
                   4138:         }
1.191     harris41 4139:     }
1.800     albertel 4140:     foreach my $role (split(':',$domrole)) {
                   4141: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4142:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4143:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4144: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4145:                return "refused:d:$crole&$cqual"; 
                   4146:             }
                   4147:         }
1.191     harris41 4148:     }
1.800     albertel 4149:     foreach my $role (split(':',$courole)) {
                   4150: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4151:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4152:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4153: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4154:                return "refused:c:$crole&$cqual"; 
                   4155:             }
                   4156:         }
1.191     harris41 4157:     }
1.620     albertel 4158:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4159:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4160: 	        "rolesdef_$rolename=".
                   4161:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4162:     return reply($command,$env{'user.home'});
1.12      www      4163:   } else {
                   4164:     return 'refused';
                   4165:   }
1.105     harris41 4166: }
                   4167: 
                   4168: # ---------------- Make a metadata query against the network of library servers
                   4169: 
                   4170: sub metadata_query {
1.244     matthew  4171:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4172:     my %rhash;
1.244     matthew  4173:     my @server_list = (defined($server_array) ? @$server_array
                   4174:                                               : keys(%libserv) );
                   4175:     for my $server (@server_list) {
1.118     harris41 4176: 	unless ($custom or $customshow) {
                   4177: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4178: 	    $rhash{$server}=$reply;
                   4179: 	}
                   4180: 	else {
                   4181: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4182: 			     &escape($custom).':'.&escape($customshow),
                   4183: 			     $server);
                   4184: 	    $rhash{$server}=$reply;
                   4185: 	}
1.112     harris41 4186:     }
1.118     harris41 4187:     return \%rhash;
1.240     www      4188: }
                   4189: 
                   4190: # ----------------------------------------- Send log queries and wait for reply
                   4191: 
                   4192: sub log_query {
                   4193:     my ($uname,$udom,$query,%filters)=@_;
                   4194:     my $uhome=&homeserver($uname,$udom);
                   4195:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4196:     my $uhost=&hostname($uhome);
1.800     albertel 4197:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4198:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4199:                        $uhome);
1.479     albertel 4200:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4201:     return get_query_reply($queryid);
                   4202: }
                   4203: 
1.818     raeburn  4204: # -------------------------- Update MySQL table for portfolio file
                   4205: 
                   4206: sub update_portfolio_table {
1.821     raeburn  4207:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4208:     my $homeserver = &homeserver($uname,$udom);
                   4209:     my $queryid=
1.821     raeburn  4210:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4211:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4212:     my $reply = &get_query_reply($queryid);
                   4213:     return $reply;
                   4214: }
                   4215: 
1.508     raeburn  4216: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4217: 
                   4218: sub fetch_enrollment_query {
1.511     raeburn  4219:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4220:     my $homeserver;
1.547     raeburn  4221:     my $maxtries = 1;
1.508     raeburn  4222:     if ($context eq 'automated') {
                   4223:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4224:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4225:     } else {
                   4226:         $homeserver = &homeserver($cnum,$dom);
                   4227:     }
1.838     albertel 4228:     my $host=&hostname($homeserver);
1.506     raeburn  4229:     my $cmd = '';
1.800     albertel 4230:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4231:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4232:     }
                   4233:     $cmd =~ s/%%$//;
                   4234:     $cmd = &escape($cmd);
                   4235:     my $query = 'fetchenrollment';
1.620     albertel 4236:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4237:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4238:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4239:         return 'error: '.$queryid;
                   4240:     }
1.506     raeburn  4241:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4242:     my $tries = 1;
                   4243:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4244:         $reply = &get_query_reply($queryid);
                   4245:         $tries ++;
                   4246:     }
1.526     raeburn  4247:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4248:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4249:     } else {
1.515     raeburn  4250:         my @responses = split/:/,$reply;
                   4251:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4252:             foreach my $line (@responses) {
                   4253:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4254:                 $$replyref{$key} = $value;
                   4255:             }
                   4256:         } else {
1.506     raeburn  4257:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4258:             foreach my $line (@responses) {
                   4259:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4260:                 $$replyref{$key} = $value;
                   4261:                 if ($value > 0) {
1.800     albertel 4262:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4263:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4264:                         my $destname = $pathname.'/'.$filename;
                   4265:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4266:                         if ($xml_classlist =~ /^error/) {
                   4267:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4268:                         } else {
1.506     raeburn  4269:                             if ( open(FILE,">$destname") ) {
                   4270:                                 print FILE &unescape($xml_classlist);
                   4271:                                 close(FILE);
1.526     raeburn  4272:                             } else {
                   4273:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4274:                             }
                   4275:                         }
                   4276:                     }
                   4277:                 }
                   4278:             }
                   4279:         }
                   4280:         return 'ok';
                   4281:     }
                   4282:     return 'error';
                   4283: }
                   4284: 
1.242     www      4285: sub get_query_reply {
                   4286:     my $queryid=shift;
1.240     www      4287:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4288:     my $reply='';
                   4289:     for (1..100) {
                   4290: 	sleep 2;
                   4291:         if (-e $replyfile.'.end') {
1.448     albertel 4292: 	    if (open(my $fh,$replyfile)) {
1.240     www      4293:                $reply.=<$fh>;
1.448     albertel 4294:                close($fh);
1.240     www      4295: 	   } else { return 'error: reply_file_error'; }
1.242     www      4296:            return &unescape($reply);
                   4297: 	}
1.240     www      4298:     }
1.242     www      4299:     return 'timeout:'.$queryid;
1.240     www      4300: }
                   4301: 
                   4302: sub courselog_query {
1.241     www      4303: #
                   4304: # possible filters:
                   4305: # url: url or symb
                   4306: # username
                   4307: # domain
                   4308: # action: view, submit, grade
                   4309: # start: timestamp
                   4310: # end: timestamp
                   4311: #
1.240     www      4312:     my (%filters)=@_;
1.620     albertel 4313:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4314:     if ($filters{'url'}) {
                   4315: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4316:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4317:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4318:     }
1.620     albertel 4319:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4320:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4321:     return &log_query($cname,$cdom,'courselog',%filters);
                   4322: }
                   4323: 
                   4324: sub userlog_query {
                   4325:     my ($uname,$udom,%filters)=@_;
                   4326:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4327: }
                   4328: 
1.506     raeburn  4329: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4330: 
                   4331: sub auto_run {
1.508     raeburn  4332:     my ($cnum,$cdom) = @_;
                   4333:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4334:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4335:     return $response;
                   4336: }
1.776     albertel 4337: 
1.506     raeburn  4338: sub auto_get_sections {
1.508     raeburn  4339:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4340:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4341:     my @secs = ();
1.511     raeburn  4342:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4343:     unless ($response eq 'refused') {
                   4344:         @secs = split/:/,$response;
                   4345:     }
                   4346:     return @secs;
                   4347: }
1.776     albertel 4348: 
1.506     raeburn  4349: sub auto_new_course {
1.508     raeburn  4350:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4351:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4352:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4353:     return $response;
                   4354: }
1.776     albertel 4355: 
1.506     raeburn  4356: sub auto_validate_courseID {
1.508     raeburn  4357:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4358:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4359:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4360:     return $response;
                   4361: }
1.776     albertel 4362: 
1.506     raeburn  4363: sub auto_create_password {
1.508     raeburn  4364:     my ($cnum,$cdom,$authparam) = @_;
                   4365:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4366:     my $create_passwd = 0;
                   4367:     my $authchk = '';
1.511     raeburn  4368:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4369:     if ($response eq 'refused') {
                   4370:         $authchk = 'refused';
                   4371:     } else {
                   4372:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4373:     }
                   4374:     return ($authparam,$create_passwd,$authchk);
                   4375: }
                   4376: 
1.706     raeburn  4377: sub auto_photo_permission {
                   4378:     my ($cnum,$cdom,$students) = @_;
                   4379:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4380:     my ($outcome,$perm_reqd,$conditions) = 
                   4381: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4382:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4383: 	return (undef,undef);
                   4384:     }
1.706     raeburn  4385:     return ($outcome,$perm_reqd,$conditions);
                   4386: }
                   4387: 
                   4388: sub auto_checkphotos {
                   4389:     my ($uname,$udom,$pid) = @_;
                   4390:     my $homeserver = &homeserver($uname,$udom);
                   4391:     my ($result,$resulttype);
                   4392:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4393: 				   &escape($uname).':'.&escape($pid),
                   4394: 				   $homeserver));
1.709     albertel 4395:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4396: 	return (undef,undef);
                   4397:     }
1.706     raeburn  4398:     if ($outcome) {
                   4399:         ($result,$resulttype) = split(/:/,$outcome);
                   4400:     } 
                   4401:     return ($result,$resulttype);
                   4402: }
                   4403: 
                   4404: sub auto_photochoice {
                   4405:     my ($cnum,$cdom) = @_;
                   4406:     my $homeserver = &homeserver($cnum,$cdom);
                   4407:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4408: 						       &escape($cdom),
                   4409: 						       $homeserver)));
1.709     albertel 4410:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4411: 	return (undef,undef);
                   4412:     }
1.706     raeburn  4413:     return ($update,$comment);
                   4414: }
                   4415: 
                   4416: sub auto_photoupdate {
                   4417:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4418:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4419:     my $host=&hostname($homeserver);
1.706     raeburn  4420:     my $cmd = '';
                   4421:     my $maxtries = 1;
1.800     albertel 4422:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4423:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4424:     }
                   4425:     $cmd =~ s/%%$//;
                   4426:     $cmd = &escape($cmd);
                   4427:     my $query = 'institutionalphotos';
                   4428:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4429:     unless ($queryid=~/^\Q$host\E\_/) {
                   4430:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4431:         return 'error: '.$queryid;
                   4432:     }
                   4433:     my $reply = &get_query_reply($queryid);
                   4434:     my $tries = 1;
                   4435:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4436:         $reply = &get_query_reply($queryid);
                   4437:         $tries ++;
                   4438:     }
                   4439:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4440:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4441:     } else {
                   4442:         my @responses = split(/:/,$reply);
                   4443:         my $outcome = shift(@responses); 
                   4444:         foreach my $item (@responses) {
                   4445:             my ($key,$value) = split(/=/,$item);
                   4446:             $$photo{$key} = $value;
                   4447:         }
                   4448:         return $outcome;
                   4449:     }
                   4450:     return 'error';
                   4451: }
                   4452: 
1.521     raeburn  4453: sub auto_instcode_format {
1.793     albertel 4454:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4455: 	$cat_order) = @_;
1.521     raeburn  4456:     my $courses = '';
1.772     raeburn  4457:     my @homeservers;
1.521     raeburn  4458:     if ($caller eq 'global') {
1.841     albertel 4459: 	my %servers = &get_servers($codedom,'library');
                   4460: 	foreach my $tryserver (keys(%servers)) {
                   4461: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4462: 		push(@homeservers,$tryserver);
                   4463: 	    }
1.584     raeburn  4464:         }
1.521     raeburn  4465:     } else {
1.772     raeburn  4466:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4467:     }
1.793     albertel 4468:     foreach my $code (keys(%{$instcodes})) {
                   4469:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4470:     }
                   4471:     chop($courses);
1.772     raeburn  4472:     my $ok_response = 0;
                   4473:     my $response;
                   4474:     while (@homeservers > 0 && $ok_response == 0) {
                   4475:         my $server = shift(@homeservers); 
                   4476:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4477:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4478:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4479: 		split/:/,$response;
1.772     raeburn  4480:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4481:             push(@{$codetitles},&str2array($codetitles_str));
                   4482:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4483:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4484:             $ok_response = 1;
                   4485:         }
                   4486:     }
                   4487:     if ($ok_response) {
1.521     raeburn  4488:         return 'ok';
1.772     raeburn  4489:     } else {
                   4490:         return $response;
1.521     raeburn  4491:     }
                   4492: }
                   4493: 
1.792     raeburn  4494: sub auto_instcode_defaults {
                   4495:     my ($domain,$returnhash,$code_order) = @_;
                   4496:     my @homeservers;
1.841     albertel 4497: 
                   4498:     my %servers = &get_servers($domain,'library');
                   4499:     foreach my $tryserver (keys(%servers)) {
                   4500: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4501: 	    push(@homeservers,$tryserver);
                   4502: 	}
1.792     raeburn  4503:     }
1.841     albertel 4504: 
1.792     raeburn  4505:     my $response;
1.841     albertel 4506:     foreach my $server (@homeservers) {
1.792     raeburn  4507:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4508:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4509: 	
                   4510: 	foreach my $pair (split(/\&/,$response)) {
                   4511: 	    my ($name,$value)=split(/\=/,$pair);
                   4512: 	    if ($name eq 'code_order') {
                   4513: 		@{$code_order} = split(/\&/,&unescape($value));
                   4514: 	    } else {
                   4515: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4516: 	    }
                   4517: 	}
                   4518: 	return 'ok';
1.792     raeburn  4519:     }
1.841     albertel 4520: 
                   4521:     return $response;
1.792     raeburn  4522: } 
                   4523: 
1.777     albertel 4524: sub auto_validate_class_sec {
1.773     raeburn  4525:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4526:     my $homeserver = &homeserver($cnum,$cdom);
                   4527:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4528:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4529:     return $response;
                   4530: }
                   4531: 
1.679     raeburn  4532: # ------------------------------------------------------- Course Group routines
                   4533: 
                   4534: sub get_coursegroups {
1.809     raeburn  4535:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4536:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4537: }
                   4538: 
1.679     raeburn  4539: sub modify_coursegroup {
                   4540:     my ($cdom,$cnum,$groupsettings) = @_;
                   4541:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4542: }
                   4543: 
1.809     raeburn  4544: sub toggle_coursegroup_status {
                   4545:     my ($cdom,$cnum,$group,$action) = @_;
                   4546:     my ($from_namespace,$to_namespace);
                   4547:     if ($action eq 'delete') {
                   4548:         $from_namespace = 'coursegroups';
                   4549:         $to_namespace = 'deleted_groups';
                   4550:     } else {
                   4551:         $from_namespace = 'deleted_groups';
                   4552:         $to_namespace = 'coursegroups';
                   4553:     }
                   4554:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4555:     if (my $tmp = &error(%curr_group)) {
                   4556:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4557:         return ('read error',$tmp);
                   4558:     } else {
                   4559:         my %savedsettings = %curr_group; 
1.809     raeburn  4560:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4561:         my $deloutcome;
                   4562:         if ($result eq 'ok') {
1.809     raeburn  4563:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4564:         } else {
                   4565:             return ('write error',$result);
                   4566:         }
                   4567:         if ($deloutcome eq 'ok') {
                   4568:             return 'ok';
                   4569:         } else {
                   4570:             return ('delete error',$deloutcome);
                   4571:         }
                   4572:     }
                   4573: }
                   4574: 
1.679     raeburn  4575: sub modify_group_roles {
                   4576:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4577:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4578:     my $role = 'gr/'.&escape($userprivs);
                   4579:     my ($uname,$udom) = split(/:/,$user);
                   4580:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4581:     if ($result eq 'ok') {
                   4582:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4583:     }
1.679     raeburn  4584:     return $result;
                   4585: }
                   4586: 
                   4587: sub modify_coursegroup_membership {
                   4588:     my ($cdom,$cnum,$membership) = @_;
                   4589:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4590:     return $result;
                   4591: }
                   4592: 
1.682     raeburn  4593: sub get_active_groups {
                   4594:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4595:     my $now = time;
                   4596:     my %groups = ();
                   4597:     foreach my $key (keys(%env)) {
1.811     albertel 4598:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4599:             my ($start,$end) = split(/\./,$env{$key});
                   4600:             if (($end!=0) && ($end<$now)) { next; }
                   4601:             if (($start!=0) && ($start>$now)) { next; }
                   4602:             if ($1 eq $cdom && $2 eq $cnum) {
                   4603:                 $groups{$3} = $env{$key} ;
                   4604:             }
                   4605:         }
                   4606:     }
                   4607:     return %groups;
                   4608: }
                   4609: 
1.683     raeburn  4610: sub get_group_membership {
                   4611:     my ($cdom,$cnum,$group) = @_;
                   4612:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4613: }
                   4614: 
                   4615: sub get_users_groups {
                   4616:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4617:     my @usersgroups;
1.683     raeburn  4618:     my $cachetime=1800;
                   4619: 
                   4620:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4621:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4622:     if (defined($cached)) {
1.734     albertel 4623:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4624:     } else {  
                   4625:         $grouplist = '';
1.816     raeburn  4626:         my $courseurl = &courseid_to_courseurl($courseid);
                   4627:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4628:         my $access_end = $env{'course.'.$courseid.
                   4629:                               '.default_enrollment_end_date'};
                   4630:         my $now = time;
                   4631:         foreach my $key (keys(%roleshash)) {
                   4632:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4633:                 my $group = $1;
                   4634:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4635:                     my $start = $2;
                   4636:                     my $end = $1;
                   4637:                     if ($start == -1) { next; } # deleted from group
                   4638:                     if (($start!=0) && ($start>$now)) { next; }
                   4639:                     if (($end!=0) && ($end<$now)) {
                   4640:                         if ($access_end && $access_end < $now) {
                   4641:                             if ($access_end - $end < 86400) {
                   4642:                                 push(@usersgroups,$group);
1.733     raeburn  4643:                             }
                   4644:                         }
1.817     raeburn  4645:                         next;
1.733     raeburn  4646:                     }
1.817     raeburn  4647:                     push(@usersgroups,$group);
1.683     raeburn  4648:                 }
                   4649:             }
                   4650:         }
1.817     raeburn  4651:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4652:         $grouplist = join(':',@usersgroups);
                   4653:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4654:     }
1.733     raeburn  4655:     return @usersgroups;
1.683     raeburn  4656: }
                   4657: 
                   4658: sub devalidate_getgroups_cache {
                   4659:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4660:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4661: 
1.683     raeburn  4662:     my $hashid="$udom:$uname:$courseid";
                   4663:     &devalidate_cache_new('getgroups',$hashid);
                   4664: }
                   4665: 
1.12      www      4666: # ------------------------------------------------------------------ Plain Text
                   4667: 
                   4668: sub plaintext {
1.742     raeburn  4669:     my ($short,$type,$cid) = @_;
1.758     albertel 4670:     if ($short =~ /^cr/) {
                   4671: 	return (split('/',$short))[-1];
                   4672:     }
1.742     raeburn  4673:     if (!defined($cid)) {
                   4674:         $cid = $env{'request.course.id'};
                   4675:     }
                   4676:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4677:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4678:                                           '.plaintext'});
                   4679:     }
                   4680:     my %rolenames = (
                   4681:                       Course => 'std',
                   4682:                       Group => 'alt1',
                   4683:                     );
                   4684:     if (defined($type) && 
                   4685:          defined($rolenames{$type}) && 
                   4686:          defined($prp{$short}{$rolenames{$type}})) {
                   4687:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4688:     } else {
                   4689:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4690:     }
1.12      www      4691: }
                   4692: 
                   4693: # ----------------------------------------------------------------- Assign Role
                   4694: 
                   4695: sub assignrole {
1.357     www      4696:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4697:     my $mrole;
                   4698:     if ($role =~ /^cr\//) {
1.393     www      4699:         my $cwosec=$url;
1.811     albertel 4700:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4701: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4702:            &logthis('Refused custom assignrole: '.
                   4703:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4704: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4705:            return 'refused'; 
                   4706:         }
1.21      www      4707:         $mrole='cr';
1.678     raeburn  4708:     } elsif ($role =~ /^gr\//) {
                   4709:         my $cwogrp=$url;
1.811     albertel 4710:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4711:         unless (&allowed('mdg',$cwogrp)) {
                   4712:             &logthis('Refused group assignrole: '.
                   4713:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4714:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4715:             return 'refused';
                   4716:         }
                   4717:         $mrole='gr';
1.21      www      4718:     } else {
1.82      www      4719:         my $cwosec=$url;
1.811     albertel 4720:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4721:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4722:            &logthis('Refused assignrole: '.
                   4723:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4724: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4725:            return 'refused'; 
                   4726:         }
1.21      www      4727:         $mrole=$role;
                   4728:     }
1.620     albertel 4729:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4730:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4731:     if ($end) { $command.='_'.$end; }
1.21      www      4732:     if ($start) {
                   4733: 	if ($end) { 
1.81      www      4734:            $command.='_'.$start; 
1.21      www      4735:         } else {
1.81      www      4736:            $command.='_0_'.$start;
1.21      www      4737:         }
                   4738:     }
1.739     raeburn  4739:     my $origstart = $start;
                   4740:     my $origend = $end;
1.357     www      4741: # actually delete
                   4742:     if ($deleteflag) {
1.373     www      4743: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4744: # modify command to delete the role
1.620     albertel 4745:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4746:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4747: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4748: # set start and finish to negative values for userrolelog
                   4749:            $start=-1;
                   4750:            $end=-1;
                   4751:         }
                   4752:     }
                   4753: # send command
1.349     www      4754:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4755: # log new user role if status is ok
1.349     www      4756:     if ($answer eq 'ok') {
1.663     raeburn  4757: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4758: # for course roles, perform group memberships changes triggered by role change.
                   4759:         unless ($role =~ /^gr/) {
                   4760:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4761:                                              $origstart);
                   4762:         }
1.349     www      4763:     }
                   4764:     return $answer;
1.169     harris41 4765: }
                   4766: 
                   4767: # -------------------------------------------------- Modify user authentication
1.197     www      4768: # Overrides without validation
                   4769: 
1.169     harris41 4770: sub modifyuserauth {
                   4771:     my ($udom,$uname,$umode,$upass)=@_;
                   4772:     my $uhome=&homeserver($uname,$udom);
1.197     www      4773:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4774:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4775:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4776:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4777:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4778: 		     &escape($upass),$uhome);
1.620     albertel 4779:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4780:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4781:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4782:     &log($udom,,$uname,$uhome,
1.620     albertel 4783:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4784:                                      $env{'user.name'}.', '.$umode.
1.197     www      4785:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4786:     unless ($reply eq 'ok') {
1.197     www      4787:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4788: 	return 'error: '.$reply;
                   4789:     }   
1.170     harris41 4790:     return 'ok';
1.80      www      4791: }
                   4792: 
1.81      www      4793: # --------------------------------------------------------------- Modify a user
1.80      www      4794: 
1.81      www      4795: sub modifyuser {
1.206     matthew  4796:     my ($udom,    $uname, $uid,
                   4797:         $umode,   $upass, $first,
                   4798:         $middle,  $last,  $gene,
1.387     www      4799:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4800:     $udom= &LONCAPA::clean_domain($udom);
                   4801:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4802:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4803:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4804: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4805:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4806:                                      ' desiredhome not specified'). 
1.620     albertel 4807:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4808:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4809:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4810: # ----------------------------------------------------------------- Create User
1.406     albertel 4811:     if (($uhome eq 'no_host') && 
                   4812: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4813:         my $unhome='';
1.844   ! albertel 4814:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4815:             $unhome = $desiredhome;
1.620     albertel 4816: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4817: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4818:         } else { # load balancing routine for determining $unhome
1.81      www      4819:             my $loadm=10000000;
1.841     albertel 4820: 	    my %servers = &get_servers($udom,'library');
                   4821: 	    foreach my $tryserver (keys(%servers)) {
                   4822: 		my $answer=reply('load',$tryserver);
                   4823: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4824: 		    $loadm=$answer;
                   4825: 		    $unhome=$tryserver;
                   4826: 		}
1.80      www      4827: 	    }
                   4828:         }
                   4829:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4830: 	    return 'error: unable to find a home server for '.$uname.
                   4831:                    ' in domain '.$udom;
1.80      www      4832:         }
                   4833:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4834:                          &escape($upass),$unhome);
                   4835: 	unless ($reply eq 'ok') {
                   4836:             return 'error: '.$reply;
                   4837:         }   
1.230     stredwic 4838:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4839:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4840: 	    return 'error: unable verify users home machine.';
1.80      www      4841:         }
1.209     matthew  4842:     }   # End of creation of new user
1.80      www      4843: # ---------------------------------------------------------------------- Add ID
                   4844:     if ($uid) {
                   4845:        $uid=~tr/A-Z/a-z/;
                   4846:        my %uidhash=&idrget($udom,$uname);
1.196     www      4847:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4848:          && (!$forceid)) {
1.80      www      4849: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4850: 	      return 'error: user id "'.$uid.'" does not match '.
                   4851:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4852:           }
                   4853:        } else {
                   4854: 	  &idput($udom,($uname => $uid));
                   4855:        }
                   4856:     }
                   4857: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4858:     my @tmp=&get('environment',
1.134     albertel 4859: 		   ['firstname','middlename','lastname','generation'],
                   4860: 		   $udom,$uname);
1.313     matthew  4861:     my %names;
                   4862:     if ($tmp[0] =~ m/^error:.*/) { 
                   4863:         %names=(); 
                   4864:     } else {
                   4865:         %names = @tmp;
                   4866:     }
1.388     www      4867: #
                   4868: # Make sure to not trash student environment if instructor does not bother
                   4869: # to supply name and email information
                   4870: #
                   4871:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4872:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4873:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4874:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4875:     if ($email) {
                   4876:        $email=~s/[^\w\@\.\-\,]//gs;
                   4877:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4878: 			   $names{'critnotification'} = $email;
                   4879: 			   $names{'permanentemail'} = $email; }
                   4880:     }
1.134     albertel 4881:     my $reply = &put('environment', \%names, $udom,$uname);
                   4882:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4883:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4884:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4885:              $umode.', '.$first.', '.$middle.', '.
                   4886: 	     $last.', '.$gene.' by '.
1.620     albertel 4887:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4888:     return 'ok';
1.80      www      4889: }
                   4890: 
1.81      www      4891: # -------------------------------------------------------------- Modify student
1.80      www      4892: 
1.81      www      4893: sub modifystudent {
                   4894:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4895:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4896:     if (!$cid) {
1.620     albertel 4897: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4898: 	    return 'not_in_class';
                   4899: 	}
1.80      www      4900:     }
                   4901: # --------------------------------------------------------------- Make the user
1.81      www      4902:     my $reply=&modifyuser
1.209     matthew  4903: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4904:          $desiredhome,$email);
1.80      www      4905:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4906:     # This will cause &modify_student_enrollment to get the uid from the
                   4907:     # students environment
                   4908:     $uid = undef if (!$forceid);
1.455     albertel 4909:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4910: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4911:     return $reply;
                   4912: }
                   4913: 
                   4914: sub modify_student_enrollment {
1.515     raeburn  4915:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4916:     my ($cdom,$cnum,$chome);
                   4917:     if (!$cid) {
1.620     albertel 4918: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4919: 	    return 'not_in_class';
                   4920: 	}
1.620     albertel 4921: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4922: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4923:     } else {
                   4924: 	($cdom,$cnum)=split(/_/,$cid);
                   4925:     }
1.620     albertel 4926:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4927:     if (!$chome) {
1.457     raeburn  4928: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4929:     }
1.455     albertel 4930:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4931:     # Make sure the user exists
1.81      www      4932:     my $uhome=&homeserver($uname,$udom);
                   4933:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4934: 	return 'error: no such user';
                   4935:     }
1.297     matthew  4936:     # Get student data if we were not given enough information
                   4937:     if (!defined($first)  || $first  eq '' || 
                   4938:         !defined($last)   || $last   eq '' || 
                   4939:         !defined($uid)    || $uid    eq '' || 
                   4940:         !defined($middle) || $middle eq '' || 
                   4941:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4942:         # They did not supply us with enough data to enroll the student, so
                   4943:         # we need to pick up more information.
1.297     matthew  4944:         my %tmp = &get('environment',
1.294     matthew  4945:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4946:                        ,$udom,$uname);
                   4947: 
1.800     albertel 4948:         #foreach my $key (keys(%tmp)) {
                   4949:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4950:         #}
1.294     matthew  4951:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4952:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4953:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4954:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4955:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4956:     }
1.556     albertel 4957:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4958:     my $reply=cput('classlist',
                   4959: 		   {"$uname:$udom" => 
1.515     raeburn  4960: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4961: 		   $cdom,$cnum);
1.81      www      4962:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4963: 	return 'error: '.$reply;
1.652     albertel 4964:     } else {
                   4965: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4966:     }
1.297     matthew  4967:     # Add student role to user
1.83      www      4968:     my $uurl='/'.$cid;
1.81      www      4969:     $uurl=~s/\_/\//g;
                   4970:     if ($usec) {
                   4971: 	$uurl.='/'.$usec;
                   4972:     }
                   4973:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4974: }
                   4975: 
1.556     albertel 4976: sub format_name {
                   4977:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4978:     my $name;
                   4979:     if ($first ne 'lastname') {
                   4980: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4981:     } else {
                   4982: 	if ($lastname=~/\S/) {
                   4983: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4984: 	    $name=~s/\s+,/,/;
                   4985: 	} else {
                   4986: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4987: 	}
                   4988:     }
                   4989:     $name=~s/^\s+//;
                   4990:     $name=~s/\s+$//;
                   4991:     $name=~s/\s+/ /g;
                   4992:     return $name;
                   4993: }
                   4994: 
1.84      www      4995: # ------------------------------------------------- Write to course preferences
                   4996: 
                   4997: sub writecoursepref {
                   4998:     my ($courseid,%prefs)=@_;
                   4999:     $courseid=~s/^\///;
                   5000:     $courseid=~s/\_/\//g;
                   5001:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5002:     my $chome=homeserver($cnum,$cdomain);
                   5003:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5004: 	return 'error: no such course';
                   5005:     }
                   5006:     my $cstring='';
1.800     albertel 5007:     foreach my $pref (keys(%prefs)) {
                   5008: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5009:     }
1.84      www      5010:     $cstring=~s/\&$//;
                   5011:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5012: }
                   5013: 
                   5014: # ---------------------------------------------------------- Make/modify course
                   5015: 
                   5016: sub createcourse {
1.741     raeburn  5017:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5018:         $course_owner,$crstype)=@_;
1.84      www      5019:     $url=&declutter($url);
                   5020:     my $cid='';
1.264     matthew  5021:     unless (&allowed('ccc',$udom)) {
1.84      www      5022:         return 'refused';
                   5023:     }
                   5024: # ------------------------------------------------------------------- Create ID
1.674     www      5025:    my $uname=int(1+rand(9)).
                   5026:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5027:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5028:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5029: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5030:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5031:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5032:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5033:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5034:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5035:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5036:            return 'error: unable to generate unique course-ID';
                   5037:        } 
                   5038:    }
1.264     matthew  5039: # ------------------------------------------------ Check supplied server name
1.620     albertel 5040:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  5041:     if (! exists($libserv{$course_server})) {
                   5042:         return 'error:bad server name '.$course_server;
                   5043:     }
1.84      www      5044: # ------------------------------------------------------------- Make the course
                   5045:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5046:                       $course_server);
1.84      www      5047:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5048:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5049:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5050: 	return 'error: no such course';
                   5051:     }
1.271     www      5052: # ----------------------------------------------------------------- Course made
1.516     raeburn  5053: # log existence
                   5054:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5055:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5056:                   &escape($crstype),$uhome);
1.358     www      5057:     &flushcourselogs();
                   5058: # set toplevel url
1.271     www      5059:     my $topurl=$url;
                   5060:     unless ($nonstandard) {
                   5061: # ------------------------------------------ For standard courses, make top url
                   5062:         my $mapurl=&clutter($url);
1.278     www      5063:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5064:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5065: <map>
                   5066: <resource id="1" type="start"></resource>
                   5067: <resource id="2" src="$mapurl"></resource>
                   5068: <resource id="3" type="finish"></resource>
                   5069: <link index="1" from="1" to="2"></link>
                   5070: <link index="2" from="2" to="3"></link>
                   5071: </map>
                   5072: ENDINITMAP
                   5073:         $topurl=&declutter(
1.638     albertel 5074:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5075:                           );
                   5076:     }
                   5077: # ----------------------------------------------------------- Write preferences
1.84      www      5078:     &writecoursepref($udom.'_'.$uname,
                   5079:                      ('description' => $description,
1.271     www      5080:                       'url'         => $topurl));
1.84      www      5081:     return '/'.$udom.'/'.$uname;
                   5082: }
                   5083: 
1.813     albertel 5084: sub is_course {
                   5085:     my ($cdom,$cnum) = @_;
                   5086:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5087: 				undef,'.');
                   5088:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5089:         return 1;
                   5090:     }
                   5091:     return 0;
                   5092: }
                   5093: 
1.21      www      5094: # ---------------------------------------------------------- Assign Custom Role
                   5095: 
                   5096: sub assigncustomrole {
1.357     www      5097:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5098:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5099:                        $end,$start,$deleteflag);
1.21      www      5100: }
                   5101: 
                   5102: # ----------------------------------------------------------------- Revoke Role
                   5103: 
                   5104: sub revokerole {
1.357     www      5105:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5106:     my $now=time;
1.357     www      5107:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5108: }
                   5109: 
                   5110: # ---------------------------------------------------------- Revoke Custom Role
                   5111: 
                   5112: sub revokecustomrole {
1.357     www      5113:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5114:     my $now=time;
1.357     www      5115:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5116:            $deleteflag);
1.17      www      5117: }
                   5118: 
1.533     banghart 5119: # ------------------------------------------------------------ Disk usage
1.535     albertel 5120: sub diskusage {
1.533     banghart 5121:     my ($udom,$uname,$directoryRoot)=@_;
                   5122:     $directoryRoot =~ s/\/$//;
1.535     albertel 5123:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5124:     return $listing;
1.512     banghart 5125: }
                   5126: 
1.566     banghart 5127: sub is_locked {
                   5128:     my ($file_name, $domain, $user) = @_;
                   5129:     my @check;
                   5130:     my $is_locked;
                   5131:     push @check, $file_name;
1.613     albertel 5132:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5133: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5134:     my ($tmp)=keys(%locked);
                   5135:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5136:     
1.566     banghart 5137:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5138:         $is_locked = 'false';
                   5139:         foreach my $entry (@{$locked{$file_name}}) {
                   5140:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5141:                $is_locked = 'true';
                   5142:                last;
1.745     raeburn  5143:            }
                   5144:        }
1.566     banghart 5145:     } else {
                   5146:         $is_locked = 'false';
                   5147:     }
                   5148: }
                   5149: 
1.759     albertel 5150: sub declutter_portfile {
                   5151:     my ($file) = @_;
1.833     albertel 5152:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5153:     return $file;
                   5154: }
                   5155: 
1.559     banghart 5156: # ------------------------------------------------------------- Mark as Read Only
                   5157: 
                   5158: sub mark_as_readonly {
                   5159:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5160:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5161:     my ($tmp)=keys(%current_permissions);
                   5162:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5163:     foreach my $file (@{$files}) {
1.759     albertel 5164: 	$file = &declutter_portfile($file);
1.561     banghart 5165:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5166:     }
1.613     albertel 5167:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5168:     return;
                   5169: }
                   5170: 
1.572     banghart 5171: # ------------------------------------------------------------Save Selected Files
                   5172: 
                   5173: sub save_selected_files {
                   5174:     my ($user, $path, @files) = @_;
                   5175:     my $filename = $user."savedfiles";
1.573     banghart 5176:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5177:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5178:     foreach my $file (@files) {
1.620     albertel 5179:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5180:     }
                   5181:     foreach my $file (@other_files) {
1.574     banghart 5182:         print (OUT $file."\n");
1.572     banghart 5183:     }
1.574     banghart 5184:     close (OUT);
1.572     banghart 5185:     return 'ok';
                   5186: }
                   5187: 
1.574     banghart 5188: sub clear_selected_files {
                   5189:     my ($user) = @_;
                   5190:     my $filename = $user."savedfiles";
                   5191:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5192:     print (OUT undef);
                   5193:     close (OUT);
                   5194:     return ("ok");    
                   5195: }
                   5196: 
1.572     banghart 5197: sub files_in_path {
                   5198:     my ($user, $path) = @_;
                   5199:     my $filename = $user."savedfiles";
                   5200:     my %return_files;
1.574     banghart 5201:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5202:     while (my $line_in = <IN>) {
1.574     banghart 5203:         chomp ($line_in);
                   5204:         my @paths_and_file = split (m!/!, $line_in);
                   5205:         my $file_part = pop (@paths_and_file);
                   5206:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5207:         $path_part.='/';
                   5208:         my $path_and_file = $path_part.$file_part;
                   5209:         if ($path_part eq $path) {
                   5210:             $return_files{$file_part}= 'selected';
                   5211:         }
                   5212:     }
1.574     banghart 5213:     close (IN);
                   5214:     return (\%return_files);
1.572     banghart 5215: }
                   5216: 
                   5217: # called in portfolio select mode, to show files selected NOT in current directory
                   5218: sub files_not_in_path {
                   5219:     my ($user, $path) = @_;
                   5220:     my $filename = $user."savedfiles";
                   5221:     my @return_files;
                   5222:     my $path_part;
1.800     albertel 5223:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5224:     while (my $line = <IN>) {
1.572     banghart 5225:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5226:         my @paths_and_file = split(m|/|, $line);
                   5227:         my $file_part = pop(@paths_and_file);
                   5228:         chomp($file_part);
                   5229:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5230:         $path_part .= '/';
                   5231:         my $path_and_file = $path_part.$file_part;
                   5232:         if ($path_part ne $path) {
1.800     albertel 5233:             push(@return_files, ($path_and_file));
1.572     banghart 5234:         }
                   5235:     }
1.800     albertel 5236:     close(OUT);
1.574     banghart 5237:     return (@return_files);
1.572     banghart 5238: }
                   5239: 
1.745     raeburn  5240: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5241: 
1.745     raeburn  5242: sub get_portfile_permissions {
                   5243:     my ($domain,$user) = @_;
1.613     albertel 5244:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5245:     my ($tmp)=keys(%current_permissions);
                   5246:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5247:     return \%current_permissions;
                   5248: }
                   5249: 
                   5250: #---------------------------------------------Get portfolio file access controls
                   5251: 
1.749     raeburn  5252: sub get_access_controls {
1.745     raeburn  5253:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5254:     my %access;
                   5255:     my $real_file = $file;
                   5256:     $file =~ s/\.meta$//;
1.745     raeburn  5257:     if (defined($file)) {
1.749     raeburn  5258:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5259:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5260:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5261:             }
                   5262:         }
1.745     raeburn  5263:     } else {
1.749     raeburn  5264:         foreach my $key (keys(%{$current_permissions})) {
                   5265:             if ($key =~ /\0accesscontrol$/) {
                   5266:                 if (defined($group)) {
                   5267:                     if ($key !~ m-^\Q$group\E/-) {
                   5268:                         next;
                   5269:                     }
                   5270:                 }
                   5271:                 my ($fullpath) = split(/\0/,$key);
                   5272:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5273:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5274:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5275:                     }
                   5276:                 }
                   5277:             }
                   5278:         }
                   5279:     }
                   5280:     return %access;
                   5281: }
                   5282: 
                   5283: sub modify_access_controls {
                   5284:     my ($file_name,$changes,$domain,$user)=@_;
                   5285:     my ($outcome,$deloutcome);
                   5286:     my %store_permissions;
                   5287:     my %new_values;
                   5288:     my %new_control;
                   5289:     my %translation;
                   5290:     my @deletions = ();
                   5291:     my $now = time;
                   5292:     if (exists($$changes{'activate'})) {
                   5293:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5294:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5295:             my $numnew = scalar(@newitems);
                   5296:             for (my $i=0; $i<$numnew; $i++) {
                   5297:                 my $newkey = $newitems[$i];
                   5298:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5299:                 if ($newkey =~ /^\d+:/) { 
                   5300:                     $newkey =~ s/^(\d+)/$newid/;
                   5301:                     $translation{$1} = $newid;
                   5302:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5303:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5304:                     $translation{$1} = $newid;
                   5305:                 }
1.749     raeburn  5306:                 $new_values{$file_name."\0".$newkey} = 
                   5307:                                           $$changes{'activate'}{$newitems[$i]};
                   5308:                 $new_control{$newkey} = $now;
                   5309:             }
                   5310:         }
                   5311:     }
                   5312:     my %todelete;
                   5313:     my %changed_items;
                   5314:     foreach my $action ('delete','update') {
                   5315:         if (exists($$changes{$action})) {
                   5316:             if (ref($$changes{$action}) eq 'HASH') {
                   5317:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5318:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5319:                     if ($action eq 'delete') { 
                   5320:                         $todelete{$itemnum} = 1;
                   5321:                     } else {
                   5322:                         $changed_items{$itemnum} = $key;
                   5323:                     }
                   5324:                 }
1.745     raeburn  5325:             }
                   5326:         }
1.749     raeburn  5327:     }
                   5328:     # get lock on access controls for file.
                   5329:     my $lockhash = {
                   5330:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5331:                                                        ':'.$env{'user.domain'},
                   5332:                    }; 
                   5333:     my $tries = 0;
                   5334:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5335:    
                   5336:     while (($gotlock ne 'ok') && $tries <3) {
                   5337:         $tries ++;
                   5338:         sleep 1;
                   5339:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5340:     }
                   5341:     if ($gotlock eq 'ok') {
                   5342:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5343:         my ($tmp)=keys(%curr_permissions);
                   5344:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5345:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5346:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5347:             if (ref($curr_controls) eq 'HASH') {
                   5348:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5349:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5350:                     if (defined($todelete{$itemnum})) {
                   5351:                         push(@deletions,$file_name."\0".$control_item);
                   5352:                     } else {
                   5353:                         if (defined($changed_items{$itemnum})) {
                   5354:                             $new_control{$changed_items{$itemnum}} = $now;
                   5355:                             push(@deletions,$file_name."\0".$control_item);
                   5356:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5357:                         } else {
                   5358:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5359:                         }
                   5360:                     }
1.745     raeburn  5361:                 }
                   5362:             }
                   5363:         }
1.749     raeburn  5364:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5365:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5366:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5367:         #  remove lock
                   5368:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5369:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5370:         my ($file,$group);
                   5371:         if (&is_course($domain,$user)) {
                   5372:             ($group,$file) = split(/\//,$file_name,2);
                   5373:         } else {
                   5374:             $file = $file_name;
                   5375:         }
                   5376:         my $sqlresult =
                   5377:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5378:                                     $group);
1.749     raeburn  5379:     } else {
                   5380:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5381:     }
1.749     raeburn  5382:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5383: }
                   5384: 
1.827     raeburn  5385: sub make_public_indefinitely {
                   5386:     my ($requrl) = @_;
                   5387:     my $now = time;
                   5388:     my $action = 'activate';
                   5389:     my $aclnum = 0;
                   5390:     if (&is_portfolio_url($requrl)) {
                   5391:         my (undef,$udom,$unum,$file_name,$group) =
                   5392:             &parse_portfolio_url($requrl);
                   5393:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5394:         my %access_controls = &get_access_controls($current_perms,
                   5395:                                                    $group,$file_name);
                   5396:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5397:             my ($num,$scope,$end,$start) = 
                   5398:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5399:             if ($scope eq 'public') {
                   5400:                 if ($start <= $now && $end == 0) {
                   5401:                     $action = 'none';
                   5402:                 } else {
                   5403:                     $action = 'update';
                   5404:                     $aclnum = $num;
                   5405:                 }
                   5406:                 last;
                   5407:             }
                   5408:         }
                   5409:         if ($action eq 'none') {
                   5410:              return 'ok';
                   5411:         } else {
                   5412:             my %changes;
                   5413:             my $newend = 0;
                   5414:             my $newstart = $now;
                   5415:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5416:             $changes{$action}{$newkey} = {
                   5417:                 type => 'public',
                   5418:                 time => {
                   5419:                     start => $newstart,
                   5420:                     end   => $newend,
                   5421:                 },
                   5422:             };
                   5423:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5424:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5425:             return $outcome;
                   5426:         }
                   5427:     } else {
                   5428:         return 'invalid';
                   5429:     }
                   5430: }
                   5431: 
1.745     raeburn  5432: #------------------------------------------------------Get Marked as Read Only
                   5433: 
                   5434: sub get_marked_as_readonly {
                   5435:     my ($domain,$user,$what,$group) = @_;
                   5436:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5437:     my @readonly_files;
1.629     banghart 5438:     my $cmp1=$what;
                   5439:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5440:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5441:         if (defined($group)) {
                   5442:             if ($file_name !~ m-^\Q$group\E/-) {
                   5443:                 next;
                   5444:             }
                   5445:         }
1.561     banghart 5446:         if (ref($value) eq "ARRAY"){
                   5447:             foreach my $stored_what (@{$value}) {
1.629     banghart 5448:                 my $cmp2=$stored_what;
1.759     albertel 5449:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5450:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5451:                 }
1.629     banghart 5452:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5453:                     push(@readonly_files, $file_name);
1.745     raeburn  5454:                     last;
1.563     banghart 5455:                 } elsif (!defined($what)) {
                   5456:                     push(@readonly_files, $file_name);
1.745     raeburn  5457:                     last;
1.561     banghart 5458:                 }
                   5459:             }
1.745     raeburn  5460:         }
1.561     banghart 5461:     }
                   5462:     return @readonly_files;
                   5463: }
1.577     banghart 5464: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5465: 
1.577     banghart 5466: sub get_marked_as_readonly_hash {
1.745     raeburn  5467:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5468:     my %readonly_files;
1.745     raeburn  5469:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5470:         if (defined($group)) {
                   5471:             if ($file_name !~ m-^\Q$group\E/-) {
                   5472:                 next;
                   5473:             }
                   5474:         }
1.577     banghart 5475:         if (ref($value) eq "ARRAY"){
                   5476:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5477:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5478:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5479:                         if ($lock_descriptor eq 'graded') {
                   5480:                             $readonly_files{$file_name} = 'graded';
                   5481:                         } elsif ($lock_descriptor eq 'handback') {
                   5482:                             $readonly_files{$file_name} = 'handback';
                   5483:                         } else {
                   5484:                             if (!exists($readonly_files{$file_name})) {
                   5485:                                 $readonly_files{$file_name} = 'locked';
                   5486:                             }
                   5487:                         }
1.745     raeburn  5488:                     }
1.750     banghart 5489:                 } 
1.577     banghart 5490:             }
                   5491:         } 
                   5492:     }
                   5493:     return %readonly_files;
                   5494: }
1.559     banghart 5495: # ------------------------------------------------------------ Unmark as Read Only
                   5496: 
                   5497: sub unmark_as_readonly {
1.629     banghart 5498:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5499:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5500:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5501:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5502:     my $symb_crs = $what;
                   5503:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5504:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5505:     my ($tmp)=keys(%current_permissions);
                   5506:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5507:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5508:     foreach my $file (@readonly_files) {
1.759     albertel 5509: 	my $clean_file = &declutter_portfile($file);
                   5510: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5511: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5512:         my @new_locks;
                   5513:         my @del_keys;
                   5514:         if (ref($current_locks) eq "ARRAY"){
                   5515:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5516:                 my $compare=$locker;
1.749     raeburn  5517:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5518:                     $compare=join('',@{$locker});
1.746     raeburn  5519:                     if ($compare ne $symb_crs) {
                   5520:                         push(@new_locks, $locker);
                   5521:                     }
1.563     banghart 5522:                 }
                   5523:             }
1.650     albertel 5524:             if (scalar(@new_locks) > 0) {
1.563     banghart 5525:                 $current_permissions{$file} = \@new_locks;
                   5526:             } else {
                   5527:                 push(@del_keys, $file);
1.613     albertel 5528:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5529:                 delete($current_permissions{$file});
1.563     banghart 5530:             }
                   5531:         }
1.561     banghart 5532:     }
1.613     albertel 5533:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5534:     return;
                   5535: }
1.512     banghart 5536: 
1.17      www      5537: # ------------------------------------------------------------ Directory lister
                   5538: 
                   5539: sub dirlist {
1.253     stredwic 5540:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5541: 
1.18      www      5542:     $uri=~s/^\///;
                   5543:     $uri=~s/\/$//;
1.253     stredwic 5544:     my ($udom, $uname);
                   5545:     (undef,$udom,$uname)=split(/\//,$uri);
                   5546:     if(defined($userdomain)) {
                   5547:         $udom = $userdomain;
                   5548:     }
                   5549:     if(defined($username)) {
                   5550:         $uname = $username;
                   5551:     }
                   5552: 
                   5553:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5554:     if(defined($alternateDirectoryRoot)) {
                   5555:         $dirRoot = $alternateDirectoryRoot;
                   5556:         $dirRoot =~ s/\/$//;
1.751     banghart 5557:     }
1.253     stredwic 5558: 
                   5559:     if($udom) {
                   5560:         if($uname) {
1.800     albertel 5561:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5562: 				 &homeserver($uname,$udom));
1.605     matthew  5563:             my @listing_results;
                   5564:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5565:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5566: 				  &homeserver($uname,$udom));
1.605     matthew  5567:                 @listing_results = split(/:/,$listing);
                   5568:             } else {
                   5569:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5570:             }
                   5571:             return @listing_results;
1.253     stredwic 5572:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5573:             my %allusers;
1.841     albertel 5574: 	    my %servers = &get_servers($udom,'library');
                   5575: 	    foreach my $tryserver (keys(%servers)) {
                   5576: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5577: 				     $udom, $tryserver);
                   5578: 		my @listing_results;
                   5579: 		if ($listing eq 'unknown_cmd') {
                   5580: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5581: 				      $udom, $tryserver);
                   5582: 		    @listing_results = split(/:/,$listing);
                   5583: 		} else {
                   5584: 		    @listing_results =
                   5585: 			map { &unescape($_); } split(/:/,$listing);
                   5586: 		}
                   5587: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5588: 		    $listing_results[0] ne 'empty'       &&
                   5589: 		    $listing_results[0] ne 'con_lost') {
                   5590: 		    foreach my $line (@listing_results) {
                   5591: 			my ($entry) = split(/&/,$line,2);
                   5592: 			$allusers{$entry} = 1;
                   5593: 		    }
                   5594: 		}
1.253     stredwic 5595:             }
                   5596:             my $alluserstr='';
1.800     albertel 5597:             foreach my $user (sort(keys(%allusers))) {
                   5598:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5599:             }
                   5600:             $alluserstr=~s/:$//;
                   5601:             return split(/:/,$alluserstr);
                   5602:         } else {
1.800     albertel 5603:             return ('missing user name');
1.253     stredwic 5604:         }
                   5605:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5606:         my @all_domains = sort(&all_domains());
                   5607:          foreach my $domain (@all_domains) {
                   5608:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5609:          }
                   5610:          return @all_domains;
                   5611:      } else {
1.800     albertel 5612:         return ('missing domain');
1.275     stredwic 5613:     }
                   5614: }
                   5615: 
                   5616: # --------------------------------------------- GetFileTimestamp
                   5617: # This function utilizes dirlist and returns the date stamp for
                   5618: # when it was last modified.  It will also return an error of -1
                   5619: # if an error occurs
                   5620: 
1.410     matthew  5621: ##
                   5622: ## FIXME: This subroutine assumes its caller knows something about the
                   5623: ## directory structure of the home server for the student ($root).
                   5624: ## Not a good assumption to make.  Since this is for looking up files
                   5625: ## in user directories, the full path should be constructed by lond, not
                   5626: ## whatever machine we request data from.
                   5627: ##
1.275     stredwic 5628: sub GetFileTimestamp {
                   5629:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5630:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5631:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5632:     my $subdir=$studentName.'__';
                   5633:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5634:     my $proname="$studentDomain/$subdir/$studentName";
                   5635:     $proname .= '/'.$filename;
1.375     matthew  5636:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5637:                                               $studentName, $root);
1.275     stredwic 5638:     my @stats = split('&', $fileStat);
                   5639:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5640:         # @stats contains first the filename, then the stat output
                   5641:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5642:     } else {
                   5643:         return -1;
1.253     stredwic 5644:     }
1.26      www      5645: }
                   5646: 
1.712     albertel 5647: sub stat_file {
                   5648:     my ($uri) = @_;
1.787     albertel 5649:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5650: 
1.712     albertel 5651:     my ($udom,$uname,$file,$dir);
                   5652:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5653: 	($udom,$uname,$file) =
1.811     albertel 5654: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5655: 	$file = 'userfiles/'.$file;
1.740     www      5656: 	$dir = &propath($udom,$uname);
1.712     albertel 5657:     }
                   5658:     if ($uri =~ m-^/res/-) {
                   5659: 	($udom,$uname) = 
1.807     albertel 5660: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5661: 	$file = $uri;
                   5662:     }
                   5663: 
                   5664:     if (!$udom || !$uname || !$file) {
                   5665: 	# unable to handle the uri
                   5666: 	return ();
                   5667:     }
                   5668: 
                   5669:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5670:     my @stats = split('&', $result);
1.721     banghart 5671:     
1.712     albertel 5672:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5673: 	shift(@stats); #filename is first
                   5674: 	return @stats;
                   5675:     }
                   5676:     return ();
                   5677: }
                   5678: 
1.26      www      5679: # -------------------------------------------------------- Value of a Condition
                   5680: 
1.713     albertel 5681: # gets the value of a specific preevaluated condition
                   5682: #    stored in the string  $env{user.state.<cid>}
                   5683: # or looks up a condition reference in the bighash and if if hasn't
                   5684: # already been evaluated recurses into docondval to get the value of
                   5685: # the condition, then memoizing it to 
                   5686: #   $env{user.state.<cid>.<condition>}
1.40      www      5687: sub directcondval {
                   5688:     my $number=shift;
1.620     albertel 5689:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5690: 	&Apache::lonuserstate::evalstate();
                   5691:     }
1.713     albertel 5692:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5693: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5694:     } elsif ($number =~ /^_/) {
                   5695: 	my $sub_condition;
                   5696: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5697: 		&GDBM_READER(),0640)) {
                   5698: 	    $sub_condition=$bighash{'conditions'.$number};
                   5699: 	    untie(%bighash);
                   5700: 	}
                   5701: 	my $value = &docondval($sub_condition);
                   5702: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5703: 	return $value;
                   5704:     }
1.620     albertel 5705:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5706:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5707:     } else {
                   5708:        return 2;
                   5709:     }
                   5710: }
                   5711: 
1.713     albertel 5712: # get the collection of conditions for this resource
1.26      www      5713: sub condval {
                   5714:     my $condidx=shift;
1.54      www      5715:     my $allpathcond='';
1.713     albertel 5716:     foreach my $cond (split(/\|/,$condidx)) {
                   5717: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5718: 	    $allpathcond.=
                   5719: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5720: 	}
1.191     harris41 5721:     }
1.54      www      5722:     $allpathcond=~s/\|$//;
1.713     albertel 5723:     return &docondval($allpathcond);
                   5724: }
                   5725: 
                   5726: #evaluates an expression of conditions
                   5727: sub docondval {
                   5728:     my ($allpathcond) = @_;
                   5729:     my $result=0;
                   5730:     if ($env{'request.course.id'}
                   5731: 	&& defined($allpathcond)) {
                   5732: 	my $operand='|';
                   5733: 	my @stack;
                   5734: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5735: 	    if ($chunk eq '(') {
                   5736: 		push @stack,($operand,$result);
                   5737: 	    } elsif ($chunk eq ')') {
                   5738: 		my $before=pop @stack;
                   5739: 		if (pop @stack eq '&') {
                   5740: 		    $result=$result>$before?$before:$result;
                   5741: 		} else {
                   5742: 		    $result=$result>$before?$result:$before;
                   5743: 		}
                   5744: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5745: 		$operand=$chunk;
                   5746: 	    } else {
                   5747: 		my $new=directcondval($chunk);
                   5748: 		if ($operand eq '&') {
                   5749: 		    $result=$result>$new?$new:$result;
                   5750: 		} else {
                   5751: 		    $result=$result>$new?$result:$new;
                   5752: 		}
                   5753: 	    }
                   5754: 	}
1.26      www      5755:     }
                   5756:     return $result;
1.421     albertel 5757: }
                   5758: 
                   5759: # ---------------------------------------------------- Devalidate courseresdata
                   5760: 
                   5761: sub devalidatecourseresdata {
                   5762:     my ($coursenum,$coursedomain)=@_;
                   5763:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5764:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5765: }
                   5766: 
1.763     www      5767: 
1.200     www      5768: # --------------------------------------------------- Course Resourcedata Query
                   5769: 
1.624     albertel 5770: sub get_courseresdata {
                   5771:     my ($coursenum,$coursedomain)=@_;
1.200     www      5772:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5773:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5774:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5775:     my %dumpreply;
1.417     albertel 5776:     unless (defined($cached)) {
1.624     albertel 5777: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5778: 	$result=\%dumpreply;
1.251     albertel 5779: 	my ($tmp) = keys(%dumpreply);
                   5780: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5781: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5782: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5783: 	    return $tmp;
1.416     albertel 5784: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5785: 	    $result=undef;
1.599     albertel 5786: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5787: 	}
                   5788:     }
1.624     albertel 5789:     return $result;
                   5790: }
                   5791: 
1.633     albertel 5792: sub devalidateuserresdata {
                   5793:     my ($uname,$udom)=@_;
                   5794:     my $hashid="$udom:$uname";
                   5795:     &devalidate_cache_new('userres',$hashid);
                   5796: }
                   5797: 
1.624     albertel 5798: sub get_userresdata {
                   5799:     my ($uname,$udom)=@_;
                   5800:     #most student don\'t have any data set, check if there is some data
                   5801:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5802: 
                   5803:     my $hashid="$udom:$uname";
                   5804:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5805:     if (!defined($cached)) {
                   5806: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5807: 	$result=\%resourcedata;
                   5808: 	&do_cache_new('userres',$hashid,$result,600);
                   5809:     }
                   5810:     my ($tmp)=keys(%$result);
                   5811:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5812: 	return $result;
                   5813:     }
                   5814:     #error 2 occurs when the .db doesn't exist
                   5815:     if ($tmp!~/error: 2 /) {
1.672     albertel 5816: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5817: 		 " Trying to get resource data for ".
                   5818: 		 $uname." at ".$udom.": ".
                   5819: 		 $tmp."</font>");
                   5820:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5821: 	#&EXT_cache_set($udom,$uname);
                   5822: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5823: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5824:     }
                   5825:     return $tmp;
                   5826: }
                   5827: 
                   5828: sub resdata {
                   5829:     my ($name,$domain,$type,@which)=@_;
                   5830:     my $result;
                   5831:     if ($type eq 'course') {
                   5832: 	$result=&get_courseresdata($name,$domain);
                   5833:     } elsif ($type eq 'user') {
                   5834: 	$result=&get_userresdata($name,$domain);
                   5835:     }
                   5836:     if (!ref($result)) { return $result; }    
1.251     albertel 5837:     foreach my $item (@which) {
1.417     albertel 5838: 	if (defined($result->{$item})) {
                   5839: 	    return $result->{$item};
1.251     albertel 5840: 	}
1.250     albertel 5841:     }
1.291     albertel 5842:     return undef;
1.200     www      5843: }
                   5844: 
1.379     matthew  5845: #
                   5846: # EXT resource caching routines
                   5847: #
                   5848: 
                   5849: sub clear_EXT_cache_status {
1.383     albertel 5850:     &delenv('cache.EXT.');
1.379     matthew  5851: }
                   5852: 
                   5853: sub EXT_cache_status {
                   5854:     my ($target_domain,$target_user) = @_;
1.383     albertel 5855:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5856:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5857:         # We know already the user has no data
                   5858:         return 1;
                   5859:     } else {
                   5860:         return 0;
                   5861:     }
                   5862: }
                   5863: 
                   5864: sub EXT_cache_set {
                   5865:     my ($target_domain,$target_user) = @_;
1.383     albertel 5866:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5867:     #&appenv($cachename => time);
1.379     matthew  5868: }
                   5869: 
1.28      www      5870: # --------------------------------------------------------- Value of a Variable
1.58      www      5871: sub EXT {
1.715     albertel 5872: 
1.395     albertel 5873:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5874:     unless ($varname) { return ''; }
1.218     albertel 5875:     #get real user name/domain, courseid and symb
                   5876:     my $courseid;
1.359     albertel 5877:     my $publicuser;
1.427     www      5878:     if ($symbparm) {
                   5879: 	$symbparm=&get_symb_from_alias($symbparm);
                   5880:     }
1.218     albertel 5881:     if (!($uname && $udom)) {
1.790     albertel 5882:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5883:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5884:     } else {
1.620     albertel 5885: 	$courseid=$env{'request.course.id'};
1.218     albertel 5886:     }
1.48      www      5887:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5888:     my $rest;
1.320     albertel 5889:     if (defined($therest[0])) {
1.48      www      5890:        $rest=join('.',@therest);
                   5891:     } else {
                   5892:        $rest='';
                   5893:     }
1.320     albertel 5894: 
1.57      www      5895:     my $qualifierrest=$qualifier;
                   5896:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5897:     my $spacequalifierrest=$space;
                   5898:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5899:     if ($realm eq 'user') {
1.48      www      5900: # --------------------------------------------------------------- user.resource
                   5901: 	if ($space eq 'resource') {
1.651     albertel 5902: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5903: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5904: 		 &&
1.744     albertel 5905: 		 ($symbparm eq &symbread()) ) {	
                   5906: 		# if we are in the middle of processing the resource the
                   5907: 		# get the value we are planning on committing
                   5908:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5909:                     return $Apache::lonhomework::results{$qualifierrest};
                   5910:                 } else {
                   5911:                     return $Apache::lonhomework::history{$qualifierrest};
                   5912:                 }
1.335     albertel 5913: 	    } else {
1.359     albertel 5914: 		my %restored;
1.620     albertel 5915: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5916: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5917: 		} else {
                   5918: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5919: 		}
1.335     albertel 5920: 		return $restored{$qualifierrest};
                   5921: 	    }
1.48      www      5922: # ----------------------------------------------------------------- user.access
                   5923:         } elsif ($space eq 'access') {
1.218     albertel 5924: 	    # FIXME - not supporting calls for a specific user
1.48      www      5925:             return &allowed($qualifier,$rest);
                   5926: # ------------------------------------------ user.preferences, user.environment
                   5927:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5928: 	    if (($uname eq $env{'user.name'}) &&
                   5929: 		($udom eq $env{'user.domain'})) {
                   5930: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5931: 	    } else {
1.359     albertel 5932: 		my %returnhash;
                   5933: 		if (!$publicuser) {
                   5934: 		    %returnhash=&userenvironment($udom,$uname,
                   5935: 						 $qualifierrest);
                   5936: 		}
1.218     albertel 5937: 		return $returnhash{$qualifierrest};
                   5938: 	    }
1.48      www      5939: # ----------------------------------------------------------------- user.course
                   5940:         } elsif ($space eq 'course') {
1.218     albertel 5941: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5942:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5943: # ------------------------------------------------------------------- user.role
                   5944:         } elsif ($space eq 'role') {
1.218     albertel 5945: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5946:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5947:             if ($qualifier eq 'value') {
                   5948: 		return $role;
                   5949:             } elsif ($qualifier eq 'extent') {
                   5950:                 return $where;
                   5951:             }
                   5952: # ----------------------------------------------------------------- user.domain
                   5953:         } elsif ($space eq 'domain') {
1.218     albertel 5954:             return $udom;
1.48      www      5955: # ------------------------------------------------------------------- user.name
                   5956:         } elsif ($space eq 'name') {
1.218     albertel 5957:             return $uname;
1.48      www      5958: # ---------------------------------------------------- Any other user namespace
1.29      www      5959:         } else {
1.359     albertel 5960: 	    my %reply;
                   5961: 	    if (!$publicuser) {
                   5962: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5963: 	    }
                   5964: 	    return $reply{$qualifierrest};
1.48      www      5965:         }
1.236     www      5966:     } elsif ($realm eq 'query') {
                   5967: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5968:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5969: 						[$spacequalifierrest]);
1.620     albertel 5970: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5971:    } elsif ($realm eq 'request') {
1.48      www      5972: # ------------------------------------------------------------- request.browser
                   5973:         if ($space eq 'browser') {
1.430     www      5974: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5975: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5976: 		    return 1;
                   5977: 		} else {
                   5978: 		    return 0;
                   5979: 		}
                   5980: 	    } else {
1.620     albertel 5981: 		return $env{'browser.'.$qualifier};
1.430     www      5982: 	    }
1.57      www      5983: # ------------------------------------------------------------ request.filename
                   5984:         } else {
1.620     albertel 5985:             return $env{'request.'.$spacequalifierrest};
1.29      www      5986:         }
1.28      www      5987:     } elsif ($realm eq 'course') {
1.48      www      5988: # ---------------------------------------------------------- course.description
1.620     albertel 5989:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5990:     } elsif ($realm eq 'resource') {
1.165     www      5991: 
1.620     albertel 5992: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5993: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5994: 	}
1.693     albertel 5995: 
                   5996: 	if ($space eq 'title') {
                   5997: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5998: 	    return &gettitle($symbparm);
                   5999: 	}
                   6000: 	
                   6001: 	if ($space eq 'map') {
                   6002: 	    my ($map) = &decode_symb($symbparm);
                   6003: 	    return &symbread($map);
                   6004: 	}
                   6005: 
                   6006: 	my ($section, $group, @groups);
1.593     albertel 6007: 	my ($courselevelm,$courselevel);
1.539     albertel 6008: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6009: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6010: 
1.218     albertel 6011: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6012: 
1.60      www      6013: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6014: 	    my $symbp=$symbparm;
1.735     albertel 6015: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6016: 
                   6017: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6018: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6019: 
1.620     albertel 6020: 	    if (($env{'user.name'} eq $uname) &&
                   6021: 		($env{'user.domain'} eq $udom)) {
                   6022: 		$section=$env{'request.course.sec'};
1.733     raeburn  6023:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6024:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6025: 	    } else {
1.539     albertel 6026: 		if (! defined($usection)) {
1.551     albertel 6027: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6028: 		} else {
                   6029: 		    $section = $usection;
                   6030: 		}
1.733     raeburn  6031:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6032: 	    }
                   6033: 
                   6034: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6035: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6036: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6037: 
1.593     albertel 6038: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6039: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6040: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6041: 
1.60      www      6042: # ----------------------------------------------------------- first, check user
1.624     albertel 6043: 
                   6044: 	    my $userreply=&resdata($uname,$udom,'user',
                   6045: 				       ($courselevelr,$courselevelm,
                   6046: 					$courselevel));
                   6047: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6048: 
1.594     albertel 6049: # ------------------------------------------------ second, check some of course
1.684     raeburn  6050:             my $coursereply;
1.691     raeburn  6051:             if (@groups > 0) {
                   6052:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6053:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6054:                 if (defined($coursereply)) { return $coursereply; }
                   6055:             }
1.96      www      6056: 
1.684     raeburn  6057: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6058: 				     $env{'course.'.$courseid.'.domain'},
                   6059: 				     'course',
                   6060: 				     ($seclevelr,$seclevelm,$seclevel,
                   6061: 				      $courselevelr));
1.287     albertel 6062: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6063: 
1.60      www      6064: # ------------------------------------------------------ third, check map parms
1.218     albertel 6065: 	    my %parmhash=();
                   6066: 	    my $thisparm='';
                   6067: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6068: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6069: 		    &GDBM_READER(),0640)) {
1.218     albertel 6070: 		$thisparm=$parmhash{$symbparm};
                   6071: 		untie(%parmhash);
                   6072: 	    }
                   6073: 	    if ($thisparm) { return $thisparm; }
                   6074: 	}
1.594     albertel 6075: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6076: 
1.218     albertel 6077: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6078: 	my $filename;
                   6079: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6080: 	if ($symbparm) {
1.409     www      6081: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6082: 	} else {
1.620     albertel 6083: 	    $filename=$env{'request.filename'};
1.282     albertel 6084: 	}
                   6085: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6086: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6087: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6088: 	if (defined($metadata)) { return $metadata; }
1.142     www      6089: 
1.594     albertel 6090: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6091: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6092: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6093: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6094: 				     $env{'course.'.$courseid.'.domain'},
                   6095: 				     'course',
                   6096: 				     ($courselevelm,$courselevel));
1.593     albertel 6097: 	    if (defined($coursereply)) { return $coursereply; }
                   6098: 	}
1.145     www      6099: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6100: 	unless ($space eq '0') {
1.336     albertel 6101: 	    my @parts=split(/_/,$space);
                   6102: 	    my $id=pop(@parts);
                   6103: 	    my $part=join('_',@parts);
                   6104: 	    if ($part eq '') { $part='0'; }
                   6105: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6106: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6107: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6108: 	}
1.395     albertel 6109: 	if ($recurse) { return undef; }
                   6110: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6111: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6112: 
1.48      www      6113: # ---------------------------------------------------- Any other user namespace
                   6114:     } elsif ($realm eq 'environment') {
                   6115: # ----------------------------------------------------------------- environment
1.620     albertel 6116: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6117: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6118: 	} else {
1.770     albertel 6119: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6120: 		return '';
                   6121: 	    }
1.219     albertel 6122: 	    my %returnhash=&userenvironment($udom,$uname,
                   6123: 					    $spacequalifierrest);
                   6124: 	    return $returnhash{$spacequalifierrest};
                   6125: 	}
1.28      www      6126:     } elsif ($realm eq 'system') {
1.48      www      6127: # ----------------------------------------------------------------- system.time
                   6128: 	if ($space eq 'time') {
                   6129: 	    return time;
                   6130:         }
1.696     albertel 6131:     } elsif ($realm eq 'server') {
                   6132: # ----------------------------------------------------------------- system.time
                   6133: 	if ($space eq 'name') {
                   6134: 	    return $ENV{'SERVER_NAME'};
                   6135:         }
1.28      www      6136:     }
1.48      www      6137:     return '';
1.61      www      6138: }
                   6139: 
1.691     raeburn  6140: sub check_group_parms {
                   6141:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6142:     my @groupitems = ();
                   6143:     my $resultitem;
                   6144:     my @levels = ($symbparm,$mapparm,$what);
                   6145:     foreach my $group (@{$groups}) {
                   6146:         foreach my $level (@levels) {
                   6147:              my $item = $courseid.'.['.$group.'].'.$level;
                   6148:              push(@groupitems,$item);
                   6149:         }
                   6150:     }
                   6151:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6152:                             $env{'course.'.$courseid.'.domain'},
                   6153:                                      'course',@groupitems);
                   6154:     return $coursereply;
                   6155: }
                   6156: 
                   6157: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6158:     my ($courseid,@groups) = @_;
                   6159:     @groups = sort(@groups);
1.691     raeburn  6160:     return @groups;
                   6161: }
                   6162: 
1.395     albertel 6163: sub packages_tab_default {
                   6164:     my ($uri,$varname)=@_;
                   6165:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6166: 
                   6167:     my (@extension,@specifics,$do_default);
                   6168:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6169: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6170: 	if ($pack_type eq 'default') {
                   6171: 	    $do_default=1;
                   6172: 	} elsif ($pack_type eq 'extension') {
                   6173: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6174: 	} else {
                   6175: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6176: 	}
                   6177:     }
                   6178:     # first look for a package that matches the requested part id
                   6179:     foreach my $package (@specifics) {
                   6180: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6181: 	next if ($pack_part ne $part);
                   6182: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6183: 	    return $packagetab{"$pack_type&$name&default"};
                   6184: 	}
                   6185:     }
                   6186:     # look for any possible matching non extension_ package
                   6187:     foreach my $package (@specifics) {
                   6188: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6189: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6190: 	    return $packagetab{"$pack_type&$name&default"};
                   6191: 	}
1.585     albertel 6192: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6193: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6194: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6195: 	}
                   6196:     }
1.738     albertel 6197:     # look for any posible extension_ match
                   6198:     foreach my $package (@extension) {
                   6199: 	my ($package,$pack_type)=@{$package};
                   6200: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6201: 	    return $packagetab{"$pack_type&$name&default"};
                   6202: 	}
                   6203: 	if (defined($packagetab{$package."&$name&default"})) {
                   6204: 	    return $packagetab{$package."&$name&default"};
                   6205: 	}
                   6206:     }
                   6207:     # look for a global default setting
                   6208:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6209: 	return $packagetab{"default&$name&default"};
                   6210:     }
1.395     albertel 6211:     return undef;
                   6212: }
                   6213: 
1.334     albertel 6214: sub add_prefix_and_part {
                   6215:     my ($prefix,$part)=@_;
                   6216:     my $keyroot;
                   6217:     if (defined($prefix) && $prefix !~ /^__/) {
                   6218: 	# prefix that has a part already
                   6219: 	$keyroot=$prefix;
                   6220:     } elsif (defined($prefix)) {
                   6221: 	# prefix that is missing a part
                   6222: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6223:     } else {
                   6224: 	# no prefix at all
                   6225: 	if (defined($part)) { $keyroot='_'.$part; }
                   6226:     }
                   6227:     return $keyroot;
                   6228: }
                   6229: 
1.71      www      6230: # ---------------------------------------------------------------- Get metadata
                   6231: 
1.599     albertel 6232: my %metaentry;
1.71      www      6233: sub metadata {
1.176     www      6234:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6235:     $uri=&declutter($uri);
1.288     albertel 6236:     # if it is a non metadata possible uri return quickly
1.529     albertel 6237:     if (($uri eq '') || 
                   6238: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6239: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6240:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6241: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6242: 	return undef;
1.288     albertel 6243:     }
1.73      www      6244:     my $filename=$uri;
                   6245:     $uri=~s/\.meta$//;
1.172     www      6246: #
                   6247: # Is the metadata already cached?
1.177     www      6248: # Look at timestamp of caching
1.172     www      6249: # Everything is cached by the main uri, libraries are never directly cached
                   6250: #
1.428     albertel 6251:     if (!defined($liburi)) {
1.599     albertel 6252: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6253: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6254:     }
                   6255:     {
1.172     www      6256: #
                   6257: # Is this a recursive call for a library?
                   6258: #
1.599     albertel 6259: #	if (! exists($metacache{$uri})) {
                   6260: #	    $metacache{$uri}={};
                   6261: #	}
1.171     www      6262:         if ($liburi) {
                   6263: 	    $liburi=&declutter($liburi);
                   6264:             $filename=$liburi;
1.401     bowersj2 6265:         } else {
1.599     albertel 6266: 	    &devalidate_cache_new('meta',$uri);
                   6267: 	    undef(%metaentry);
1.401     bowersj2 6268: 	}
1.140     www      6269:         my %metathesekeys=();
1.73      www      6270:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6271: 	my $metastring;
1.768     albertel 6272: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6273: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6274: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6275: 	    $metastring=&getfile($file);
1.489     albertel 6276: 	}
1.208     albertel 6277:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6278:         my $token;
1.140     www      6279:         undef %metathesekeys;
1.71      www      6280:         while ($token=$parser->get_token) {
1.339     albertel 6281: 	    if ($token->[0] eq 'S') {
                   6282: 		if (defined($token->[2]->{'package'})) {
1.172     www      6283: #
                   6284: # This is a package - get package info
                   6285: #
1.339     albertel 6286: 		    my $package=$token->[2]->{'package'};
                   6287: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6288: 		    if (defined($token->[2]->{'id'})) { 
                   6289: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6290: 		    }
1.599     albertel 6291: 		    if ($metaentry{':packages'}) {
                   6292: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6293: 		    } else {
1.599     albertel 6294: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6295: 		    }
1.736     albertel 6296: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6297: 			my $part=$keyroot;
                   6298: 			$part=~s/^\_//;
1.736     albertel 6299: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6300: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6301: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6302: 			    # ignore package.tab specified default values
                   6303:                             # here &package_tab_default() will fetch those
                   6304: 			    if ($subp eq 'default') { next; }
1.736     albertel 6305: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6306: 			    my $unikey;
                   6307: 			    if ($pack =~ /_0$/) {
                   6308: 				$unikey='parameter_0_'.$name;
                   6309: 				$part=0;
                   6310: 			    } else {
                   6311: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6312: 			    }
1.339     albertel 6313: 			    if ($subp eq 'display') {
                   6314: 				$value.=' [Part: '.$part.']';
                   6315: 			    }
1.599     albertel 6316: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6317: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6318: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6319: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6320: 			    }
1.599     albertel 6321: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6322: 				$metaentry{':'.$unikey}=
                   6323: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6324: 			    }
1.339     albertel 6325: 			}
                   6326: 		    }
                   6327: 		} else {
1.172     www      6328: #
                   6329: # This is not a package - some other kind of start tag
1.339     albertel 6330: #
                   6331: 		    my $entry=$token->[1];
                   6332: 		    my $unikey;
                   6333: 		    if ($entry eq 'import') {
                   6334: 			$unikey='';
                   6335: 		    } else {
                   6336: 			$unikey=$entry;
                   6337: 		    }
                   6338: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6339: 
                   6340: 		    if (defined($token->[2]->{'id'})) { 
                   6341: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6342: 		    }
1.175     www      6343: 
1.339     albertel 6344: 		    if ($entry eq 'import') {
1.175     www      6345: #
                   6346: # Importing a library here
1.339     albertel 6347: #
                   6348: 			if ($depthcount<20) {
                   6349: 			    my $location=$parser->get_text('/import');
                   6350: 			    my $dir=$filename;
                   6351: 			    $dir=~s|[^/]*$||;
                   6352: 			    $location=&filelocation($dir,$location);
1.736     albertel 6353: 			    my $metadata = 
                   6354: 				&metadata($uri,'keys', $location,$unikey,
                   6355: 					  $depthcount+1);
                   6356: 			    foreach my $meta (split(',',$metadata)) {
                   6357: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6358: 				$metathesekeys{$meta}=1;
1.339     albertel 6359: 			    }
                   6360: 			}
                   6361: 		    } else { 
                   6362: 			
                   6363: 			if (defined($token->[2]->{'name'})) { 
                   6364: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6365: 			}
                   6366: 			$metathesekeys{$unikey}=1;
1.736     albertel 6367: 			foreach my $param (@{$token->[3]}) {
                   6368: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6369: 				$token->[2]->{$param};
1.339     albertel 6370: 			}
                   6371: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6372: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6373: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6374: 		 # only ws inside the tag, and not in default, so use default
                   6375: 		 # as value
1.599     albertel 6376: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6377: 			} else {
1.321     albertel 6378: 		  # either something interesting inside the tag or default
                   6379:                   # uninteresting
1.599     albertel 6380: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6381: 			}
1.172     www      6382: # end of not-a-package not-a-library import
1.339     albertel 6383: 		    }
1.172     www      6384: # end of not-a-package start tag
1.339     albertel 6385: 		}
1.172     www      6386: # the next is the end of "start tag"
1.339     albertel 6387: 	    }
                   6388: 	}
1.483     albertel 6389: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6390: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6391: 	    #no specific packages #how's our extension
                   6392: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6393: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6394: 					 \%metathesekeys);
                   6395: 	}
1.599     albertel 6396: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6397: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6398: 		#no specific packages well let's get default then
                   6399: 		if ($key!~/^default&/) { next; }
1.488     albertel 6400: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6401: 					     \%metathesekeys);
                   6402: 	    }
                   6403: 	}
1.338     www      6404: # are there custom rights to evaluate
1.599     albertel 6405: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6406: 
1.338     www      6407:     #
                   6408:     # Importing a rights file here
1.339     albertel 6409:     #
                   6410: 	    unless ($depthcount) {
1.599     albertel 6411: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6412: 		my $dir=$filename;
                   6413: 		$dir=~s|[^/]*$||;
                   6414: 		$location=&filelocation($dir,$location);
1.736     albertel 6415: 		my $rights_metadata =
                   6416: 		    &metadata($uri,'keys',$location,'_rights',
                   6417: 			      $depthcount+1);
                   6418: 		foreach my $rights (split(',',$rights_metadata)) {
                   6419: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6420: 		    $metathesekeys{$rights}=1;
1.339     albertel 6421: 		}
                   6422: 	    }
                   6423: 	}
1.737     albertel 6424: 	# uniqifiy package listing
                   6425: 	my %seen;
                   6426: 	my @uniq_packages =
                   6427: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6428: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6429: 
                   6430: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6431: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6432: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6433: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6434: # this is the end of "was not already recently cached
1.71      www      6435:     }
1.599     albertel 6436:     return $metaentry{':'.$what};
1.261     albertel 6437: }
                   6438: 
1.488     albertel 6439: sub metadata_create_package_def {
1.483     albertel 6440:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6441:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6442:     if ($subp eq 'default') { next; }
                   6443:     
1.599     albertel 6444:     if (defined($metaentry{':packages'})) {
                   6445: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6446:     } else {
1.599     albertel 6447: 	$metaentry{':packages'}=$package;
1.483     albertel 6448:     }
                   6449:     my $value=$packagetab{$key};
                   6450:     my $unikey;
                   6451:     $unikey='parameter_0_'.$name;
1.599     albertel 6452:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6453:     $$metathesekeys{$unikey}=1;
1.599     albertel 6454:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6455: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6456:     }
1.599     albertel 6457:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6458: 	$metaentry{':'.$unikey}=
                   6459: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6460:     }
                   6461: }
                   6462: 
1.261     albertel 6463: sub metadata_generate_part0 {
                   6464:     my ($metadata,$metacache,$uri) = @_;
                   6465:     my %allnames;
1.737     albertel 6466:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6467: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6468: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6469: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6470: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6471: 	    $allnames{$name}=$part;
                   6472: 	  }
                   6473: 	}
                   6474:     }
                   6475:     foreach my $name (keys(%allnames)) {
                   6476:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6477:       my $key=":parameter_0_$name";
1.261     albertel 6478:       $$metacache{"$key.part"}='0';
                   6479:       $$metacache{"$key.name"}=$name;
1.428     albertel 6480:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6481: 					   $allnames{$name}.'_'.$name.
                   6482: 					   '.type'};
1.428     albertel 6483:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6484: 			     '.display'};
1.644     www      6485:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6486:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6487:       $$metacache{"$key.display"}=$olddis;
                   6488:     }
1.71      www      6489: }
                   6490: 
1.764     albertel 6491: # ------------------------------------------------------ Devalidate title cache
                   6492: 
                   6493: sub devalidate_title_cache {
                   6494:     my ($url)=@_;
                   6495:     if (!$env{'request.course.id'}) { return; }
                   6496:     my $symb=&symbread($url);
                   6497:     if (!$symb) { return; }
                   6498:     my $key=$env{'request.course.id'}."\0".$symb;
                   6499:     &devalidate_cache_new('title',$key);
                   6500: }
                   6501: 
1.301     www      6502: # ------------------------------------------------- Get the title of a resource
                   6503: 
                   6504: sub gettitle {
                   6505:     my $urlsymb=shift;
                   6506:     my $symb=&symbread($urlsymb);
1.534     albertel 6507:     if ($symb) {
1.620     albertel 6508: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6509: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6510: 	if (defined($cached)) { 
                   6511: 	    return $result;
                   6512: 	}
1.534     albertel 6513: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6514: 	my $title='';
                   6515: 	my %bighash;
1.620     albertel 6516: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6517: 		&GDBM_READER(),0640)) {
                   6518: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6519: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6520: 	    untie %bighash;
                   6521: 	}
                   6522: 	$title=~s/\&colon\;/\:/gs;
                   6523: 	if ($title) {
1.599     albertel 6524: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6525: 	}
                   6526: 	$urlsymb=$url;
                   6527:     }
                   6528:     my $title=&metadata($urlsymb,'title');
                   6529:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6530:     return $title;
1.301     www      6531: }
1.613     albertel 6532: 
1.614     albertel 6533: sub get_slot {
                   6534:     my ($which,$cnum,$cdom)=@_;
                   6535:     if (!$cnum || !$cdom) {
1.790     albertel 6536: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6537: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6538: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6539:     }
1.703     albertel 6540:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6541:     my %slotinfo;
                   6542:     if (exists($remembered{$key})) {
                   6543: 	$slotinfo{$which} = $remembered{$key};
                   6544:     } else {
                   6545: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6546: 	&Apache::lonhomework::showhash(%slotinfo);
                   6547: 	my ($tmp)=keys(%slotinfo);
                   6548: 	if ($tmp=~/^error:/) { return (); }
                   6549: 	$remembered{$key} = $slotinfo{$which};
                   6550:     }
1.616     albertel 6551:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6552: 	return %{$slotinfo{$which}};
                   6553:     }
                   6554:     return $slotinfo{$which};
1.614     albertel 6555: }
1.31      www      6556: # ------------------------------------------------- Update symbolic store links
                   6557: 
                   6558: sub symblist {
                   6559:     my ($mapname,%newhash)=@_;
1.438     www      6560:     $mapname=&deversion(&declutter($mapname));
1.31      www      6561:     my %hash;
1.620     albertel 6562:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6563:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6564:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6565: 	    foreach my $url (keys %newhash) {
                   6566: 		next if ($url eq 'last_known'
                   6567: 			 && $env{'form.no_update_last_known'});
                   6568: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6569: 						    $newhash{$url}->[1],
                   6570: 						    $newhash{$url}->[0]);
1.191     harris41 6571:             }
1.31      www      6572:             if (untie(%hash)) {
                   6573: 		return 'ok';
                   6574:             }
                   6575:         }
                   6576:     }
                   6577:     return 'error';
1.212     www      6578: }
                   6579: 
                   6580: # --------------------------------------------------------------- Verify a symb
                   6581: 
                   6582: sub symbverify {
1.510     www      6583:     my ($symb,$thisurl)=@_;
                   6584:     my $thisfn=$thisurl;
1.439     www      6585:     $thisfn=&declutter($thisfn);
1.215     www      6586: # direct jump to resource in page or to a sequence - will construct own symbs
                   6587:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6588: # check URL part
1.409     www      6589:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6590: 
1.431     www      6591:     unless ($url eq $thisfn) { return 0; }
1.213     www      6592: 
1.216     www      6593:     $symb=&symbclean($symb);
1.510     www      6594:     $thisurl=&deversion($thisurl);
1.439     www      6595:     $thisfn=&deversion($thisfn);
1.213     www      6596: 
                   6597:     my %bighash;
                   6598:     my $okay=0;
1.431     www      6599: 
1.620     albertel 6600:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6601:                             &GDBM_READER(),0640)) {
1.510     www      6602:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6603:         unless ($ids) { 
1.510     www      6604:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6605:         }
                   6606:         if ($ids) {
                   6607: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6608: 	    foreach my $id (split(/\,/,$ids)) {
                   6609: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6610:                if (
                   6611:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6612:    eq $symb) { 
1.620     albertel 6613: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6614: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6615: 		       $okay=1; 
                   6616: 		   }
                   6617: 	       }
1.216     www      6618: 	   }
                   6619:         }
1.213     www      6620: 	untie(%bighash);
                   6621:     }
                   6622:     return $okay;
1.31      www      6623: }
                   6624: 
1.210     www      6625: # --------------------------------------------------------------- Clean-up symb
                   6626: 
                   6627: sub symbclean {
                   6628:     my $symb=shift;
1.568     albertel 6629:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6630: # remove version from map
                   6631:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6632: 
1.210     www      6633: # remove version from URL
                   6634:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6635: 
1.507     www      6636: # remove wrapper
                   6637: 
1.510     www      6638:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6639:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6640:     return $symb;
1.409     www      6641: }
                   6642: 
                   6643: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6644: 
                   6645: sub encode_symb {
                   6646:     my ($map,$resid,$url)=@_;
                   6647:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6648: }
1.409     www      6649: 
                   6650: sub decode_symb {
1.568     albertel 6651:     my $symb=shift;
                   6652:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6653:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6654:     return (&fixversion($map),$resid,&fixversion($url));
                   6655: }
                   6656: 
                   6657: sub fixversion {
                   6658:     my $fn=shift;
1.609     banghart 6659:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6660:     my %bighash;
                   6661:     my $uri=&clutter($fn);
1.620     albertel 6662:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6663: # is this cached?
1.599     albertel 6664:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6665:     if (defined($cached)) { return $result; }
                   6666: # unfortunately not cached, or expired
1.620     albertel 6667:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6668: 	    &GDBM_READER(),0640)) {
                   6669:  	if ($bighash{'version_'.$uri}) {
                   6670:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6671:  	    unless (($version eq 'mostrecent') || 
                   6672: 		    ($version==&getversion($uri))) {
1.440     www      6673:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6674:  	    }
                   6675:  	}
                   6676:  	untie %bighash;
1.413     www      6677:     }
1.599     albertel 6678:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6679: }
                   6680: 
                   6681: sub deversion {
                   6682:     my $url=shift;
                   6683:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6684:     return $url;
1.210     www      6685: }
                   6686: 
1.31      www      6687: # ------------------------------------------------------ Return symb list entry
                   6688: 
                   6689: sub symbread {
1.249     www      6690:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6691:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6692:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6693: # no filename provided? try from environment
1.44      www      6694:     unless ($thisfn) {
1.620     albertel 6695:         if ($env{'request.symb'}) {
                   6696: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6697: 	}
1.620     albertel 6698: 	$thisfn=$env{'request.filename'};
1.44      www      6699:     }
1.569     albertel 6700:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6701: # is that filename actually a symb? Verify, clean, and return
                   6702:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6703: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6704: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6705: 	}
1.242     www      6706:     }
1.44      www      6707:     $thisfn=declutter($thisfn);
1.31      www      6708:     my %hash;
1.37      www      6709:     my %bighash;
                   6710:     my $syval='';
1.620     albertel 6711:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6712:         my $targetfn = $thisfn;
1.609     banghart 6713:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6714:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6715:         }
1.687     albertel 6716: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6717: 	    $targetfn=$1;
                   6718: 	}
1.620     albertel 6719:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6720:                       &GDBM_READER(),0640)) {
1.481     raeburn  6721: 	    $syval=$hash{$targetfn};
1.37      www      6722:             untie(%hash);
                   6723:         }
                   6724: # ---------------------------------------------------------- There was an entry
                   6725:         if ($syval) {
1.601     albertel 6726: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6727: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6728: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6729: 		    #return $env{$cache_str}='';
1.601     albertel 6730: 		#}    
                   6731: 		#$syval.=$1;
                   6732: 	    #}
1.37      www      6733:         } else {
                   6734: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6735:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6736:                             &GDBM_READER(),0640)) {
1.37      www      6737: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6738:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6739:               unless ($ids) { 
                   6740:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6741:               }
                   6742:               unless ($ids) {
                   6743: # alias?
                   6744: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6745:               }
1.37      www      6746:               if ($ids) {
                   6747: # ------------------------------------------------------------------- Has ID(s)
                   6748:                  my @possibilities=split(/\,/,$ids);
1.39      www      6749:                  if ($#possibilities==0) {
                   6750: # ----------------------------------------------- There is only one possibility
1.37      www      6751: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6752: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6753: 						    $resid,$thisfn);
1.249     www      6754:                  } elsif (!$donotrecurse) {
1.39      www      6755: # ------------------------------------------ There is more than one possibility
                   6756:                      my $realpossible=0;
1.800     albertel 6757:                      foreach my $id (@possibilities) {
                   6758: 			 my $file=$bighash{'src_'.$id};
1.39      www      6759:                          if (&allowed('bre',$file)) {
1.800     albertel 6760:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6761:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6762: 				$realpossible++;
1.626     albertel 6763:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6764: 						    $resid,$thisfn);
1.39      www      6765:                             }
                   6766: 			 }
1.191     harris41 6767:                      }
1.39      www      6768: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6769:                  } else {
                   6770:                      $syval='';
1.37      www      6771:                  }
                   6772: 	      }
                   6773:               untie(%bighash)
1.481     raeburn  6774:            }
1.31      www      6775:         }
1.62      www      6776:         if ($syval) {
1.620     albertel 6777: 	    return $env{$cache_str}=$syval;
1.62      www      6778:         }
1.31      www      6779:     }
1.44      www      6780:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6781:     return $env{$cache_str}='';
1.31      www      6782: }
                   6783: 
                   6784: # ---------------------------------------------------------- Return random seed
                   6785: 
1.32      www      6786: sub numval {
                   6787:     my $txt=shift;
                   6788:     $txt=~tr/A-J/0-9/;
                   6789:     $txt=~tr/a-j/0-9/;
                   6790:     $txt=~tr/K-T/0-9/;
                   6791:     $txt=~tr/k-t/0-9/;
                   6792:     $txt=~tr/U-Z/0-5/;
                   6793:     $txt=~tr/u-z/0-5/;
                   6794:     $txt=~s/\D//g;
1.564     albertel 6795:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6796:     return int($txt);
1.368     albertel 6797: }
                   6798: 
1.484     albertel 6799: sub numval2 {
                   6800:     my $txt=shift;
                   6801:     $txt=~tr/A-J/0-9/;
                   6802:     $txt=~tr/a-j/0-9/;
                   6803:     $txt=~tr/K-T/0-9/;
                   6804:     $txt=~tr/k-t/0-9/;
                   6805:     $txt=~tr/U-Z/0-5/;
                   6806:     $txt=~tr/u-z/0-5/;
                   6807:     $txt=~s/\D//g;
                   6808:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6809:     my $total;
                   6810:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6811:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6812:     return int($total);
                   6813: }
                   6814: 
1.575     albertel 6815: sub numval3 {
                   6816:     use integer;
                   6817:     my $txt=shift;
                   6818:     $txt=~tr/A-J/0-9/;
                   6819:     $txt=~tr/a-j/0-9/;
                   6820:     $txt=~tr/K-T/0-9/;
                   6821:     $txt=~tr/k-t/0-9/;
                   6822:     $txt=~tr/U-Z/0-5/;
                   6823:     $txt=~tr/u-z/0-5/;
                   6824:     $txt=~s/\D//g;
                   6825:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6826:     my $total;
                   6827:     foreach my $val (@txts) { $total+=$val; }
                   6828:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6829:     return $total;
                   6830: }
                   6831: 
1.675     albertel 6832: sub digest {
                   6833:     my ($data)=@_;
                   6834:     my $digest=&Digest::MD5::md5($data);
                   6835:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6836:     my ($e,$f);
                   6837:     {
                   6838:         use integer;
                   6839:         $e=($a+$b);
                   6840:         $f=($c+$d);
                   6841:         if ($_64bit) {
                   6842:             $e=(($e<<32)>>32);
                   6843:             $f=(($f<<32)>>32);
                   6844:         }
                   6845:     }
                   6846:     if (wantarray) {
                   6847: 	return ($e,$f);
                   6848:     } else {
                   6849: 	my $g;
                   6850: 	{
                   6851: 	    use integer;
                   6852: 	    $g=($e+$f);
                   6853: 	    if ($_64bit) {
                   6854: 		$g=(($g<<32)>>32);
                   6855: 	    }
                   6856: 	}
                   6857: 	return $g;
                   6858:     }
                   6859: }
                   6860: 
1.368     albertel 6861: sub latest_rnd_algorithm_id {
1.675     albertel 6862:     return '64bit5';
1.366     albertel 6863: }
1.32      www      6864: 
1.503     albertel 6865: sub get_rand_alg {
                   6866:     my ($courseid)=@_;
1.790     albertel 6867:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6868:     if ($courseid) {
1.620     albertel 6869: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6870:     }
                   6871:     return &latest_rnd_algorithm_id();
                   6872: }
                   6873: 
1.562     albertel 6874: sub validCODE {
                   6875:     my ($CODE)=@_;
                   6876:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6877:     return 0;
                   6878: }
                   6879: 
1.491     albertel 6880: sub getCODE {
1.620     albertel 6881:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6882:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6883: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6884: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6885: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6886:     }
                   6887:     return undef;
                   6888: }
                   6889: 
1.31      www      6890: sub rndseed {
1.155     albertel 6891:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6892: 
1.790     albertel 6893:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6894:     if (!$symb) {
1.366     albertel 6895: 	unless ($symb=$wsymb) { return time; }
                   6896:     }
                   6897:     if (!$courseid) { $courseid=$wcourseid; }
                   6898:     if (!$domain) { $domain=$wdomain; }
                   6899:     if (!$username) { $username=$wusername }
1.503     albertel 6900:     my $which=&get_rand_alg();
1.803     albertel 6901: 
1.491     albertel 6902:     if (defined(&getCODE())) {
1.675     albertel 6903: 	if ($which eq '64bit5') {
                   6904: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6905: 	} elsif ($which eq '64bit4') {
1.575     albertel 6906: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6907: 	} else {
                   6908: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6909: 	}
1.675     albertel 6910:     } elsif ($which eq '64bit5') {
                   6911: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6912:     } elsif ($which eq '64bit4') {
                   6913: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6914:     } elsif ($which eq '64bit3') {
                   6915: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6916:     } elsif ($which eq '64bit2') {
                   6917: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6918:     } elsif ($which eq '64bit') {
                   6919: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6920:     }
                   6921:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6922: }
                   6923: 
                   6924: sub rndseed_32bit {
                   6925:     my ($symb,$courseid,$domain,$username)=@_;
                   6926:     {
                   6927: 	use integer;
                   6928: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6929: 	my $symbseed=numval($symb) << 22;
                   6930: 	my $namechck=unpack("%32C*",$username) << 17;
                   6931: 	my $nameseed=numval($username) << 12;
                   6932: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6933: 	my $courseseed=unpack("%32C*",$courseid);
                   6934: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6935: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6936: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6937: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6938: 	return $num;
                   6939:     }
                   6940: }
                   6941: 
                   6942: sub rndseed_64bit {
                   6943:     my ($symb,$courseid,$domain,$username)=@_;
                   6944:     {
                   6945: 	use integer;
                   6946: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6947: 	my $symbseed=numval($symb) << 10;
                   6948: 	my $namechck=unpack("%32S*",$username);
                   6949: 	
                   6950: 	my $nameseed=numval($username) << 21;
                   6951: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6952: 	my $courseseed=unpack("%32S*",$courseid);
                   6953: 	
                   6954: 	my $num1=$symbchck+$symbseed+$namechck;
                   6955: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6956: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6957: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6958: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6959: 	return "$num1,$num2";
1.155     albertel 6960:     }
1.366     albertel 6961: }
                   6962: 
1.443     albertel 6963: sub rndseed_64bit2 {
                   6964:     my ($symb,$courseid,$domain,$username)=@_;
                   6965:     {
                   6966: 	use integer;
                   6967: 	# strings need to be an even # of cahracters long, it it is odd the
                   6968:         # last characters gets thrown away
                   6969: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6970: 	my $symbseed=numval($symb) << 10;
                   6971: 	my $namechck=unpack("%32S*",$username.' ');
                   6972: 	
                   6973: 	my $nameseed=numval($username) << 21;
1.501     albertel 6974: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6975: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6976: 	
                   6977: 	my $num1=$symbchck+$symbseed+$namechck;
                   6978: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6979: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6980: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6981: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6982: 	return "$num1,$num2";
                   6983:     }
                   6984: }
                   6985: 
                   6986: sub rndseed_64bit3 {
                   6987:     my ($symb,$courseid,$domain,$username)=@_;
                   6988:     {
                   6989: 	use integer;
                   6990: 	# strings need to be an even # of cahracters long, it it is odd the
                   6991:         # last characters gets thrown away
                   6992: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6993: 	my $symbseed=numval2($symb) << 10;
                   6994: 	my $namechck=unpack("%32S*",$username.' ');
                   6995: 	
                   6996: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6997: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6998: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6999: 	
                   7000: 	my $num1=$symbchck+$symbseed+$namechck;
                   7001: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7002: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7003: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7004: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7005: 	
1.503     albertel 7006: 	return "$num1:$num2";
1.443     albertel 7007:     }
                   7008: }
                   7009: 
1.575     albertel 7010: sub rndseed_64bit4 {
                   7011:     my ($symb,$courseid,$domain,$username)=@_;
                   7012:     {
                   7013: 	use integer;
                   7014: 	# strings need to be an even # of cahracters long, it it is odd the
                   7015:         # last characters gets thrown away
                   7016: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7017: 	my $symbseed=numval3($symb) << 10;
                   7018: 	my $namechck=unpack("%32S*",$username.' ');
                   7019: 	
                   7020: 	my $nameseed=numval3($username) << 21;
                   7021: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7022: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7023: 	
                   7024: 	my $num1=$symbchck+$symbseed+$namechck;
                   7025: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7026: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7027: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7028: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7029: 	
                   7030: 	return "$num1:$num2";
                   7031:     }
                   7032: }
                   7033: 
1.675     albertel 7034: sub rndseed_64bit5 {
                   7035:     my ($symb,$courseid,$domain,$username)=@_;
                   7036:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7037:     return "$num1:$num2";
                   7038: }
                   7039: 
1.366     albertel 7040: sub rndseed_CODE_64bit {
                   7041:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7042:     {
1.366     albertel 7043: 	use integer;
1.443     albertel 7044: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7045: 	my $symbseed=numval2($symb);
1.491     albertel 7046: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7047: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7048: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7049: 	my $num1=$symbseed+$CODEchck;
                   7050: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7051: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7052: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7053: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7054: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7055: 	return "$num1:$num2";
1.366     albertel 7056:     }
                   7057: }
                   7058: 
1.575     albertel 7059: sub rndseed_CODE_64bit4 {
                   7060:     my ($symb,$courseid,$domain,$username)=@_;
                   7061:     {
                   7062: 	use integer;
                   7063: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7064: 	my $symbseed=numval3($symb);
                   7065: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7066: 	my $CODEseed=numval3(&getCODE());
                   7067: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7068: 	my $num1=$symbseed+$CODEchck;
                   7069: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7070: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7071: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7072: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7073: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7074: 	return "$num1:$num2";
                   7075:     }
                   7076: }
                   7077: 
1.675     albertel 7078: sub rndseed_CODE_64bit5 {
                   7079:     my ($symb,$courseid,$domain,$username)=@_;
                   7080:     my $code = &getCODE();
                   7081:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7082:     return "$num1:$num2";
                   7083: }
                   7084: 
1.366     albertel 7085: sub setup_random_from_rndseed {
                   7086:     my ($rndseed)=@_;
1.503     albertel 7087:     if ($rndseed =~/([,:])/) {
                   7088: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7089: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7090:     } else {
                   7091: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7092:     }
1.36      albertel 7093: }
                   7094: 
1.474     albertel 7095: sub latest_receipt_algorithm_id {
1.835     albertel 7096:     return 'receipt3';
1.474     albertel 7097: }
                   7098: 
1.480     www      7099: sub recunique {
                   7100:     my $fucourseid=shift;
                   7101:     my $unique;
1.835     albertel 7102:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7103: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7104: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7105:     } else {
                   7106: 	$unique=$perlvar{'lonReceipt'};
                   7107:     }
                   7108:     return unpack("%32C*",$unique);
                   7109: }
                   7110: 
                   7111: sub recprefix {
                   7112:     my $fucourseid=shift;
                   7113:     my $prefix;
1.835     albertel 7114:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7115: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7116: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7117:     } else {
                   7118: 	$prefix=$perlvar{'lonHostID'};
                   7119:     }
                   7120:     return unpack("%32C*",$prefix);
                   7121: }
                   7122: 
1.76      www      7123: sub ireceipt {
1.474     albertel 7124:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7125: 
                   7126:     my $return =&recprefix($fucourseid).'-';
                   7127: 
                   7128:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7129: 	$env{'request.state'} eq 'construct') {
                   7130: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7131: 	return $return;
                   7132:     }
                   7133: 
1.76      www      7134:     my $cuname=unpack("%32C*",$funame);
                   7135:     my $cudom=unpack("%32C*",$fudom);
                   7136:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7137:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7138:     my $cunique=&recunique($fucourseid);
1.474     albertel 7139:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7140:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7141: 
1.790     albertel 7142: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7143: 			       
                   7144: 	$return.= ($cunique%$cuname+
                   7145: 		   $cunique%$cudom+
                   7146: 		   $cusymb%$cuname+
                   7147: 		   $cusymb%$cudom+
                   7148: 		   $cucourseid%$cuname+
                   7149: 		   $cucourseid%$cudom+
                   7150: 		   $cpart%$cuname+
                   7151: 		   $cpart%$cudom);
                   7152:     } else {
                   7153: 	$return.= ($cunique%$cuname+
                   7154: 		   $cunique%$cudom+
                   7155: 		   $cusymb%$cuname+
                   7156: 		   $cusymb%$cudom+
                   7157: 		   $cucourseid%$cuname+
                   7158: 		   $cucourseid%$cudom);
                   7159:     }
                   7160:     return $return;
1.76      www      7161: }
                   7162: 
                   7163: sub receipt {
1.474     albertel 7164:     my ($part)=@_;
1.790     albertel 7165:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7166:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7167: }
1.260     ng       7168: 
1.790     albertel 7169: sub whichuser {
                   7170:     my ($passedsymb)=@_;
                   7171:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7172:     if (defined($env{'form.grade_symb'})) {
                   7173: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7174: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7175: 	if (!$allowed &&
                   7176: 	    exists($env{'request.course.sec'}) &&
                   7177: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7178: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7179: 			      '/'.$env{'request.course.sec'});
                   7180: 	}
                   7181: 	if ($allowed) {
                   7182: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7183: 	    $courseid=$tmp_courseid;
                   7184: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7185: 	    ($name)=&get_env_multiple('form.grade_username');
                   7186: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7187: 	}
                   7188:     }
                   7189:     if (!$passedsymb) {
                   7190: 	$symb=&symbread();
                   7191:     } else {
                   7192: 	$symb=$passedsymb;
                   7193:     }
                   7194:     $courseid=$env{'request.course.id'};
                   7195:     $domain=$env{'user.domain'};
                   7196:     $name=$env{'user.name'};
                   7197:     if ($name eq 'public' && $domain eq 'public') {
                   7198: 	if (!defined($env{'form.username'})) {
                   7199: 	    $env{'form.username'}.=time.rand(10000000);
                   7200: 	}
                   7201: 	$name.=$env{'form.username'};
                   7202:     }
                   7203:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7204: 
                   7205: }
                   7206: 
1.36      albertel 7207: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7208: # returns either the contents of the file or 
                   7209: # -1 if the file doesn't exist
1.481     raeburn  7210: #
                   7211: # if the target is a file that was uploaded via DOCS, 
                   7212: # a check will be made to see if a current copy exists on the local server,
                   7213: # if it does this will be served, otherwise a copy will be retrieved from
                   7214: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7215: # the local server.   
1.472     albertel 7216: 
1.36      albertel 7217: sub getfile {
1.538     albertel 7218:     my ($file) = @_;
1.609     banghart 7219:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7220:     &repcopy($file);
                   7221:     return &readfile($file);
                   7222: }
                   7223: 
                   7224: sub repcopy_userfile {
                   7225:     my ($file)=@_;
1.609     banghart 7226:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7227:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7228:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7229: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7230:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7231:     if (-e "$file") {
1.828     www      7232: # we already have a local copy, check it out
1.538     albertel 7233: 	my @fileinfo = stat($file);
1.828     www      7234: 	my $rtncode;
                   7235: 	my $info;
1.538     albertel 7236: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7237: 	if ($lwpresp ne 'ok') {
1.828     www      7238: # there is no such file anymore, even though we had a local copy
1.482     albertel 7239: 	    if ($rtncode eq '404') {
1.538     albertel 7240: 		unlink($file);
1.482     albertel 7241: 	    }
                   7242: 	    return -1;
                   7243: 	}
                   7244: 	if ($info < $fileinfo[9]) {
1.828     www      7245: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7246: 	    return 'ok';
1.828     www      7247: 	} else {
                   7248: # the file is outdated, get rid of it
                   7249: 	    unlink($file);
1.482     albertel 7250: 	}
1.828     www      7251:     }
                   7252: # one way or the other, at this point, we don't have the file
                   7253: # construct the correct path for the file
                   7254:     my @parts = ($cdom,$cnum); 
                   7255:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7256: 	push @parts, split(/\//,$1);
                   7257:     }
                   7258:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7259:     foreach my $part (@parts) {
                   7260: 	$path .= '/'.$part;
                   7261: 	if (!-e $path) {
                   7262: 	    mkdir($path,0770);
1.482     albertel 7263: 	}
                   7264:     }
1.828     www      7265: # now the path exists for sure
                   7266: # get a user agent
                   7267:     my $ua=new LWP::UserAgent;
                   7268:     my $transferfile=$file.'.in.transfer';
                   7269: # FIXME: this should flock
                   7270:     if (-e $transferfile) { return 'ok'; }
                   7271:     my $request;
                   7272:     $uri=~s/^\///;
1.838     albertel 7273:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7274:     my $response=$ua->request($request,$transferfile);
                   7275: # did it work?
                   7276:     if ($response->is_error()) {
                   7277: 	unlink($transferfile);
                   7278: 	&logthis("Userfile repcopy failed for $uri");
                   7279: 	return -1;
                   7280:     }
                   7281: # worked, rename the transfer file
                   7282:     rename($transferfile,$file);
1.607     raeburn  7283:     return 'ok';
1.481     raeburn  7284: }
                   7285: 
1.517     albertel 7286: sub tokenwrapper {
                   7287:     my $uri=shift;
1.552     albertel 7288:     $uri=~s|^http\://([^/]+)||;
                   7289:     $uri=~s|^/||;
1.620     albertel 7290:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7291:     my $token=$1;
1.552     albertel 7292:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7293:     if ($udom && $uname && $file) {
                   7294: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7295:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7296:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7297:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7298:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7299:     } else {
                   7300:         return '/adm/notfound.html';
                   7301:     }
                   7302: }
                   7303: 
1.828     www      7304: # call with reqtype HEAD: get last modification time
                   7305: # call with reqtype GET: get the file contents
                   7306: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7307: #
1.481     raeburn  7308: sub getuploaded {
                   7309:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7310:     $uri=~s/^\///;
1.838     albertel 7311:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7312:     my $ua=new LWP::UserAgent;
                   7313:     my $request=new HTTP::Request($reqtype,$uri);
                   7314:     my $response=$ua->request($request);
                   7315:     $$rtncode = $response->code;
1.482     albertel 7316:     if (! $response->is_success()) {
                   7317: 	return 'failed';
                   7318:     }      
                   7319:     if ($reqtype eq 'HEAD') {
1.486     www      7320: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7321:     } elsif ($reqtype eq 'GET') {
                   7322: 	$$info = $response->content;
1.472     albertel 7323:     }
1.482     albertel 7324:     return 'ok';
1.36      albertel 7325: }
                   7326: 
1.481     raeburn  7327: sub readfile {
                   7328:     my $file = shift;
                   7329:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7330:     my $fh;
                   7331:     open($fh,"<$file");
                   7332:     my $a='';
1.800     albertel 7333:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7334:     return $a;
                   7335: }
                   7336: 
1.36      albertel 7337: sub filelocation {
1.590     banghart 7338:     my ($dir,$file) = @_;
                   7339:     my $location;
                   7340:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7341: 
                   7342:     if ($file =~ m-^/adm/-) {
                   7343: 	$file=~s-^/adm/wrapper/-/-;
                   7344: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7345:     }
1.590     banghart 7346:     if ($file=~m:^/~:) { # is a contruction space reference
                   7347:         $location = $file;
                   7348:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7349:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7350: 	# is a correct contruction space reference
                   7351:         $location = $file;
1.609     banghart 7352:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7353:         my ($udom,$uname,$filename)=
1.811     albertel 7354:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7355:         my $home=&homeserver($uname,$udom);
                   7356:         my $is_me=0;
                   7357:         my @ids=&current_machine_ids();
                   7358:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7359:         if ($is_me) {
1.740     www      7360:   	    $location=&propath($udom,$uname).
1.590     banghart 7361:   	      '/userfiles/'.$filename;
                   7362:         } else {
                   7363:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7364:   	      $udom.'/'.$uname.'/'.$filename;
                   7365:         }
                   7366:     } else {
                   7367:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7368:         $file=~s:^/res/:/:;
                   7369:         if ( !( $file =~ m:^/:) ) {
                   7370:             $location = $dir. '/'.$file;
                   7371:         } else {
                   7372:             $location = '/home/httpd/html/res'.$file;
                   7373:         }
1.59      albertel 7374:     }
1.590     banghart 7375:     $location=~s://+:/:g; # remove duplicate /
                   7376:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7377:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7378:     return $location;
1.46      www      7379: }
1.36      albertel 7380: 
1.46      www      7381: sub hreflocation {
                   7382:     my ($dir,$file)=@_;
1.460     albertel 7383:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7384: 	$file=filelocation($dir,$file);
1.700     albertel 7385:     } elsif ($file=~m-^/adm/-) {
                   7386: 	$file=~s-^/adm/wrapper/-/-;
                   7387: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7388:     }
                   7389:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7390: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7391:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7392: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7393:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7394: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7395: 	    -/uploaded/$1/$2/-x;
1.46      www      7396:     }
1.462     albertel 7397:     return $file;
1.465     albertel 7398: }
                   7399: 
                   7400: sub current_machine_domains {
1.838     albertel 7401:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7402:     my @domains;
1.838     albertel 7403:     my %hostname = &all_hostnames();
1.465     albertel 7404:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7405: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7406: 	if ($hostname eq $name) {
1.844   ! albertel 7407: 	    push(@domains,&host_domain($id));
1.465     albertel 7408: 	}
                   7409:     }
                   7410:     return @domains;
                   7411: }
                   7412: 
                   7413: sub current_machine_ids {
1.838     albertel 7414:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7415:     my @ids;
1.838     albertel 7416:     my %hostname = &all_hostnames();
1.465     albertel 7417:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7418: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7419: 	if ($hostname eq $name) {
                   7420: 	    push(@ids,$id);
                   7421: 	}
                   7422:     }
                   7423:     return @ids;
1.31      www      7424: }
                   7425: 
1.824     raeburn  7426: sub additional_machine_domains {
                   7427:     my @domains;
                   7428:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7429:     while( my $line = <$fh>) {
                   7430:         $line =~ s/\s//g;
                   7431:         push(@domains,$line);
                   7432:     }
                   7433:     return @domains;
                   7434: }
                   7435: 
                   7436: sub default_login_domain {
                   7437:     my $domain = $perlvar{'lonDefDomain'};
                   7438:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7439:     foreach my $posdom (&current_machine_domains(),
                   7440:                         &additional_machine_domains()) {
                   7441:         if (lc($posdom) eq lc($testdomain)) {
                   7442:             $domain=$posdom;
                   7443:             last;
                   7444:         }
                   7445:     }
                   7446:     return $domain;
                   7447: }
                   7448: 
1.31      www      7449: # ------------------------------------------------------------- Declutters URLs
                   7450: 
                   7451: sub declutter {
                   7452:     my $thisfn=shift;
1.569     albertel 7453:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7454:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7455:     $thisfn=~s/^\///;
1.697     albertel 7456:     $thisfn=~s|^adm/wrapper/||;
                   7457:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7458:     $thisfn=~s/^res\///;
1.235     www      7459:     $thisfn=~s/\?.+$//;
1.268     www      7460:     return $thisfn;
                   7461: }
                   7462: 
                   7463: # ------------------------------------------------------------- Clutter up URLs
                   7464: 
                   7465: sub clutter {
                   7466:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7467:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7468:        $thisfn='/res'.$thisfn; 
                   7469:     }
1.694     albertel 7470:     if ($thisfn !~m|/adm|) {
1.695     albertel 7471: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7472: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7473: 	} else {
                   7474: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7475: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7476: 	    if ($embstyle eq 'ssi'
                   7477: 		|| ($embstyle eq 'hdn')
                   7478: 		|| ($embstyle eq 'rat')
                   7479: 		|| ($embstyle eq 'prv')
                   7480: 		|| ($embstyle eq 'ign')) {
                   7481: 		#do nothing with these
                   7482: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7483: 		|| ($embstyle eq 'emb')
                   7484: 		|| ($embstyle eq 'wrp')) {
                   7485: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7486: 	    } elsif ($embstyle eq 'unk'
                   7487: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7488: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7489: 	    } else {
1.718     www      7490: #		&logthis("Got a blank emb style");
1.695     albertel 7491: 	    }
1.694     albertel 7492: 	}
                   7493:     }
1.31      www      7494:     return $thisfn;
1.12      www      7495: }
                   7496: 
1.787     albertel 7497: sub clutter_with_no_wrapper {
                   7498:     my $uri = &clutter(shift);
                   7499:     if ($uri =~ m-^/adm/-) {
                   7500: 	$uri =~ s-^/adm/wrapper/-/-;
                   7501: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7502:     }
                   7503:     return $uri;
                   7504: }
                   7505: 
1.557     albertel 7506: sub freeze_escape {
                   7507:     my ($value)=@_;
                   7508:     if (ref($value)) {
                   7509: 	$value=&nfreeze($value);
                   7510: 	return '__FROZEN__'.&escape($value);
                   7511:     }
                   7512:     return &escape($value);
                   7513: }
                   7514: 
1.11      www      7515: 
1.557     albertel 7516: sub thaw_unescape {
                   7517:     my ($value)=@_;
                   7518:     if ($value =~ /^__FROZEN__/) {
                   7519: 	substr($value,0,10,undef);
                   7520: 	$value=&unescape($value);
                   7521: 	return &thaw($value);
                   7522:     }
                   7523:     return &unescape($value);
                   7524: }
                   7525: 
1.436     albertel 7526: sub correct_line_ends {
                   7527:     my ($result)=@_;
                   7528:     $$result =~s/\r\n/\n/mg;
                   7529:     $$result =~s/\r/\n/mg;
1.415     albertel 7530: }
1.1       albertel 7531: # ================================================================ Main Program
                   7532: 
1.184     www      7533: sub goodbye {
1.204     albertel 7534:    &logthis("Starting Shut down");
1.443     albertel 7535: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7536:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7537: #converted
1.599     albertel 7538: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7539:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7540: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7541: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7542: #1.1 only
1.599     albertel 7543: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7544: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7545: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7546: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7547:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7548:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7549:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7550:    &flushcourselogs();
                   7551:    &logthis("Shutting down");
                   7552: }
                   7553: 
1.179     www      7554: BEGIN {
1.228     harris41 7555: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7556:     unless ($readit) {
1.217     harris41 7557: {
1.781     raeburn  7558:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7559:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7560: }
1.1       albertel 7561: 
1.327     albertel 7562: # ------------------------------------------------------------ Read domain file
                   7563: {
                   7564:     %domaindescription = ();
                   7565:     %domain_auth_def = ();
                   7566:     %domain_auth_arg_def = ();
1.448     albertel 7567:     my $fh;
                   7568:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7569: 	while (my $line = <$fh>) {
                   7570:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7571: #           next if /^\#/;
1.801     foxr     7572:            chomp $line;
1.403     www      7573:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7574: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7575: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7576:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7577: 	   $domaindescription{$domain}=$domain_description;
                   7578: 	   $domain_lang_def{$domain}=$def_lang;
                   7579: 	   $domain_city{$domain}=$city;
                   7580: 	   $domain_longi{$domain}=$longi;
                   7581: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7582:            $domain_primary{$domain}=$primary;
1.403     www      7583: 
1.448     albertel 7584:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7585: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7586: 	}
1.327     albertel 7587:     }
1.448     albertel 7588:     close ($fh);
1.327     albertel 7589: }
                   7590: 
                   7591: 
1.1       albertel 7592: # ------------------------------------------------------------- Read hosts file
                   7593: {
1.838     albertel 7594:     my %hostname;
1.844   ! albertel 7595:     my %hostdom;
1.448     albertel 7596:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7597: 
                   7598:     while (my $configline=<$config>) {
1.303     matthew  7599:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7600:        chomp($configline);
1.595     albertel 7601:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7602:        $name=~s/\s//g;
1.595     albertel 7603:        if ($id && $domain && $role && $name) {
1.252     albertel 7604: 	 $hostname{$id}=$name;
                   7605: 	 $hostdom{$id}=$domain;
                   7606: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7607:        }
1.1       albertel 7608:     }
1.448     albertel 7609:     close($config);
1.619     albertel 7610:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7611:     #&get_iphost();
1.838     albertel 7612: 
                   7613:     sub hostname {
                   7614: 	my ($lonid) = @_;
                   7615: 	return $hostname{$lonid};
                   7616:     }
                   7617:     sub all_hostnames {
                   7618: 	return %hostname;
                   7619:     }
1.841     albertel 7620:     sub get_servers {
                   7621: 	my ($domain,$type) = @_;
                   7622: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7623: 	                                          : %hostname;
                   7624: 	my %result;
1.842     albertel 7625: 	if (ref($domain) eq 'ARRAY') {
                   7626: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7627: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7628: 		    $result{$host} = $hostname;
                   7629: 		}
                   7630: 	    }
                   7631: 	} else {
                   7632: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7633: 		if ($hostdom{$host} eq $domain) {
                   7634: 		    $result{$host} = $hostname;
                   7635: 		}
1.841     albertel 7636: 	    }
                   7637: 	}
                   7638: 	return %result;
                   7639:     }
1.844   ! albertel 7640:     sub host_domain {
        !          7641: 	my ($lonid) = @_;
        !          7642: 	return $hostdom{$lonid};
        !          7643:     }
        !          7644: 
1.841     albertel 7645:     sub all_domains {
                   7646: 	my %seen;
                   7647: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7648: 	return @uniq;
                   7649:     }
1.1       albertel 7650: }
                   7651: 
1.839     albertel 7652: sub get_hosts_from_ip {
                   7653:     my ($ip) = @_;
                   7654:     my %iphosts = &get_iphost();
                   7655:     if (ref($iphosts{$ip})) {
                   7656: 	return @{$iphosts{$ip}};
                   7657:     }
                   7658:     return;
                   7659: }
                   7660: 
1.598     albertel 7661: sub get_iphost {
                   7662:     if (%iphost) { return %iphost; }
1.653     albertel 7663:     my %name_to_ip;
1.838     albertel 7664:     my %hostname = &all_hostnames();
1.598     albertel 7665:     foreach my $id (keys(%hostname)) {
                   7666: 	my $name=$hostname{$id};
1.653     albertel 7667: 	my $ip;
                   7668: 	if (!exists($name_to_ip{$name})) {
                   7669: 	    $ip = gethostbyname($name);
                   7670: 	    if (!$ip || length($ip) ne 4) {
1.826     www      7671: 		&logthis("Skipping host $id name $name no IP found");
1.653     albertel 7672: 		next;
                   7673: 	    }
                   7674: 	    $ip=inet_ntoa($ip);
                   7675: 	    $name_to_ip{$name} = $ip;
                   7676: 	} else {
                   7677: 	    $ip = $name_to_ip{$name};
1.598     albertel 7678: 	}
                   7679: 	push(@{$iphost{$ip}},$id);
                   7680:     }
                   7681:     return %iphost;
                   7682: }
                   7683: 
1.1       albertel 7684: # ------------------------------------------------------ Read spare server file
                   7685: {
1.448     albertel 7686:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7687: 
                   7688:     while (my $configline=<$config>) {
                   7689:        chomp($configline);
1.284     matthew  7690:        if ($configline) {
1.784     albertel 7691: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7692: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7693: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7694:        }
                   7695:     }
1.448     albertel 7696:     close($config);
1.1       albertel 7697: }
1.11      www      7698: # ------------------------------------------------------------ Read permissions
                   7699: {
1.448     albertel 7700:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7701: 
                   7702:     while (my $configline=<$config>) {
1.448     albertel 7703: 	chomp($configline);
                   7704: 	if ($configline) {
                   7705: 	    my ($role,$perm)=split(/ /,$configline);
                   7706: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7707: 	}
1.11      www      7708:     }
1.448     albertel 7709:     close($config);
1.11      www      7710: }
                   7711: 
                   7712: # -------------------------------------------- Read plain texts for permissions
                   7713: {
1.448     albertel 7714:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7715: 
                   7716:     while (my $configline=<$config>) {
1.448     albertel 7717: 	chomp($configline);
                   7718: 	if ($configline) {
1.742     raeburn  7719: 	    my ($short,@plain)=split(/:/,$configline);
                   7720:             %{$prp{$short}} = ();
                   7721: 	    if (@plain > 0) {
                   7722:                 $prp{$short}{'std'} = $plain[0];
                   7723:                 for (my $i=1; $i<@plain; $i++) {
                   7724:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7725:                 }
                   7726:             }
1.448     albertel 7727: 	}
1.135     www      7728:     }
1.448     albertel 7729:     close($config);
1.135     www      7730: }
                   7731: 
                   7732: # ---------------------------------------------------------- Read package table
                   7733: {
1.448     albertel 7734:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7735: 
                   7736:     while (my $configline=<$config>) {
1.483     albertel 7737: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7738: 	chomp($configline);
                   7739: 	my ($short,$plain)=split(/:/,$configline);
                   7740: 	my ($pack,$name)=split(/\&/,$short);
                   7741: 	if ($plain ne '') {
                   7742: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7743: 	    $packagetab{$short}=$plain; 
                   7744: 	}
1.11      www      7745:     }
1.448     albertel 7746:     close($config);
1.329     matthew  7747: }
                   7748: 
                   7749: # ------------- set up temporary directory
                   7750: {
                   7751:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7752: 
1.11      www      7753: }
                   7754: 
1.794     albertel 7755: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7756: 				'compress_threshold'=> 20_000,
                   7757:  			        });
1.185     www      7758: 
1.281     www      7759: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7760: $dumpcount=0;
1.22      www      7761: 
1.163     harris41 7762: &logtouch();
1.672     albertel 7763: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7764: $readit=1;
1.564     albertel 7765:     {
                   7766: 	use integer;
                   7767: 	my $test=(2**32)+1;
1.568     albertel 7768: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7769: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7770:     }
1.195     www      7771: }
1.1       albertel 7772: }
1.179     www      7773: 
1.1       albertel 7774: 1;
1.191     harris41 7775: __END__
                   7776: 
1.243     albertel 7777: =pod
                   7778: 
1.191     harris41 7779: =head1 NAME
                   7780: 
1.243     albertel 7781: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7782: 
                   7783: =head1 SYNOPSIS
                   7784: 
1.243     albertel 7785: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7786: 
                   7787:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7788: 
1.243     albertel 7789: Common parameters:
                   7790: 
                   7791: =over 4
                   7792: 
                   7793: =item *
                   7794: 
                   7795: $uname : an internal username (if $cname expecting a course Id specifically)
                   7796: 
                   7797: =item *
                   7798: 
                   7799: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7800: 
                   7801: =item *
                   7802: 
                   7803: $symb : a resource instance identifier
                   7804: 
                   7805: =item *
                   7806: 
                   7807: $namespace : the name of a .db file that contains the data needed or
                   7808: being set.
                   7809: 
                   7810: =back
                   7811: 
1.394     bowersj2 7812: =head1 OVERVIEW
1.191     harris41 7813: 
1.394     bowersj2 7814: lonnet provides subroutines which interact with the
                   7815: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7816: about classes, users, and resources.
1.243     albertel 7817: 
                   7818: For many of these objects you can also use this to store data about
                   7819: them or modify them in various ways.
1.191     harris41 7820: 
1.394     bowersj2 7821: =head2 Symbs
1.191     harris41 7822: 
1.394     bowersj2 7823: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7824: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7825: map, the resource number of the resource in the map, and the URL of
                   7826: the resource itself. The latter is somewhat redundant, but might help
                   7827: if maps change.
                   7828: 
                   7829: An example is
                   7830: 
                   7831:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7832: 
                   7833: The respective map entry is
                   7834: 
                   7835:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7836:   title="Problem 2">
                   7837:  </resource>
                   7838: 
                   7839: Symbs are used by the random number generator, as well as to store and
                   7840: restore data specific to a certain instance of for example a problem.
                   7841: 
                   7842: =head2 Storing And Retrieving Data
                   7843: 
                   7844: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7845: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7846: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7847: is is the non-critical message twin of cstore. These functions are for
                   7848: handlers to store a perl hash to a user's permanent data space in an
                   7849: easy manner, and to retrieve it again on another call. It is expected
                   7850: that a handler would use this once at the beginning to retrieve data,
                   7851: and then again once at the end to send only the new data back.
                   7852: 
                   7853: The data is stored in the user's data directory on the user's
                   7854: homeserver under the ID of the course.
                   7855: 
                   7856: The hash that is returned by restore will have all of the previous
                   7857: value for all of the elements of the hash.
                   7858: 
                   7859: Example:
                   7860: 
                   7861:  #creating a hash
                   7862:  my %hash;
                   7863:  $hash{'foo'}='bar';
                   7864: 
                   7865:  #storing it
                   7866:  &Apache::lonnet::cstore(\%hash);
                   7867: 
                   7868:  #changing a value
                   7869:  $hash{'foo'}='notbar';
                   7870: 
                   7871:  #adding a new value
                   7872:  $hash{'bar'}='foo';
                   7873:  &Apache::lonnet::cstore(\%hash);
                   7874: 
                   7875:  #retrieving the hash
                   7876:  my %history=&Apache::lonnet::restore();
                   7877: 
                   7878:  #print the hash
                   7879:  foreach my $key (sort(keys(%history))) {
                   7880:    print("\%history{$key} = $history{$key}");
                   7881:  }
                   7882: 
                   7883: Will print out:
1.191     harris41 7884: 
1.394     bowersj2 7885:  %history{1:foo} = bar
                   7886:  %history{1:keys} = foo:timestamp
                   7887:  %history{1:timestamp} = 990455579
                   7888:  %history{2:bar} = foo
                   7889:  %history{2:foo} = notbar
                   7890:  %history{2:keys} = foo:bar:timestamp
                   7891:  %history{2:timestamp} = 990455580
                   7892:  %history{bar} = foo
                   7893:  %history{foo} = notbar
                   7894:  %history{timestamp} = 990455580
                   7895:  %history{version} = 2
                   7896: 
                   7897: Note that the special hash entries C<keys>, C<version> and
                   7898: C<timestamp> were added to the hash. C<version> will be equal to the
                   7899: total number of versions of the data that have been stored. The
                   7900: C<timestamp> attribute will be the UNIX time the hash was
                   7901: stored. C<keys> is available in every historical section to list which
                   7902: keys were added or changed at a specific historical revision of a
                   7903: hash.
                   7904: 
                   7905: B<Warning>: do not store the hash that restore returns directly. This
                   7906: will cause a mess since it will restore the historical keys as if the
                   7907: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7908: 
1.394     bowersj2 7909: Calling convention:
1.191     harris41 7910: 
1.394     bowersj2 7911:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7912:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7913: 
1.394     bowersj2 7914: For more detailed information, see lonnet specific documentation.
1.191     harris41 7915: 
1.394     bowersj2 7916: =head1 RETURN MESSAGES
1.191     harris41 7917: 
1.394     bowersj2 7918: =over 4
1.191     harris41 7919: 
1.394     bowersj2 7920: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7921: 
1.394     bowersj2 7922: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7923: when the connection is brought back up
1.191     harris41 7924: 
1.394     bowersj2 7925: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7926: for later delivery
1.191     harris41 7927: 
1.394     bowersj2 7928: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7929: 
1.394     bowersj2 7930: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7931: that was requested
1.191     harris41 7932: 
1.243     albertel 7933: =back
1.191     harris41 7934: 
1.243     albertel 7935: =head1 PUBLIC SUBROUTINES
1.191     harris41 7936: 
1.243     albertel 7937: =head2 Session Environment Functions
1.191     harris41 7938: 
1.243     albertel 7939: =over 4
1.191     harris41 7940: 
1.394     bowersj2 7941: =item * 
                   7942: X<appenv()>
                   7943: B<appenv(%hash)>: the value of %hash is written to
                   7944: the user envirnoment file, and will be restored for each access this
1.620     albertel 7945: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7946: process
1.191     harris41 7947: 
                   7948: =item *
1.394     bowersj2 7949: X<delenv()>
                   7950: B<delenv($regexp)>: removes all items from the session
                   7951: environment file that matches the regular expression in $regexp. The
1.620     albertel 7952: values are also delted from the current processes %env.
1.191     harris41 7953: 
1.795     albertel 7954: =item * get_env_multiple($name) 
                   7955: 
                   7956: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7957: values may be defined and end up as an array ref.
                   7958: 
                   7959: returns an array of values
                   7960: 
1.243     albertel 7961: =back
                   7962: 
                   7963: =head2 User Information
1.191     harris41 7964: 
1.243     albertel 7965: =over 4
1.191     harris41 7966: 
                   7967: =item *
1.394     bowersj2 7968: X<queryauthenticate()>
                   7969: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7970: authentication scheme
                   7971: 
                   7972: =item *
1.394     bowersj2 7973: X<authenticate()>
                   7974: B<authenticate($uname,$upass,$udom)>: try to
                   7975: authenticate user from domain's lib servers (first use the current
                   7976: one). C<$upass> should be the users password.
1.191     harris41 7977: 
                   7978: =item *
1.394     bowersj2 7979: X<homeserver()>
                   7980: B<homeserver($uname,$udom)>: find the server which has
                   7981: the user's directory and files (there must be only one), this caches
                   7982: the answer, and also caches if there is a borken connection.
1.191     harris41 7983: 
                   7984: =item *
1.394     bowersj2 7985: X<idget()>
                   7986: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7987: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7988: username, and only 1 username per ID in a specific domain) (returns
                   7989: hash: id=>name,id=>name)
1.191     harris41 7990: 
                   7991: =item *
1.394     bowersj2 7992: X<idrget()>
                   7993: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7994: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7995: 
                   7996: =item *
1.394     bowersj2 7997: X<idput()>
                   7998: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7999: 
                   8000: =item *
1.394     bowersj2 8001: X<rolesinit()>
                   8002: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8003: 
                   8004: =item *
1.551     albertel 8005: X<getsection()>
                   8006: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8007: course $cname, return section name/number or '' for "not in course"
                   8008: and '-1' for "no section"
                   8009: 
                   8010: =item *
1.394     bowersj2 8011: X<userenvironment()>
                   8012: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8013: passed in @what from the requested user's environment, returns a hash
                   8014: 
                   8015: =back
                   8016: 
                   8017: =head2 User Roles
                   8018: 
                   8019: =over 4
                   8020: 
                   8021: =item *
                   8022: 
1.810     raeburn  8023: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8024:  F: full access
                   8025:  U,I,K: authentication modes (cxx only)
                   8026:  '': forbidden
                   8027:  1: user needs to choose course
                   8028:  2: browse allowed
1.766     albertel 8029:  A: passphrase authentication needed
1.243     albertel 8030: 
                   8031: =item *
                   8032: 
                   8033: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8034: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8035: and course level
                   8036: 
                   8037: =item *
                   8038: 
                   8039: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8040: explanation of a user role term
                   8041: 
1.832     raeburn  8042: =item *
                   8043: 
1.834     albertel 8044: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
                   8045: optional.  Returns a hash of a user's roles, with keys set to
                   8046: colon-sparated $uname,$udom,and $role, and value set to
                   8047: colon-separated start and end times for the role. If no username and
                   8048: domain are specified, will default to current user/domain. Types,
                   8049: roles, and roledoms are references to arrays, of role statuses
                   8050: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
                   8051: of the roles which can be used to restrict the list if roles
                   8052: reported. If no array ref is provided for types, will default to
                   8053: return only active roles.
                   8054: 
1.243     albertel 8055: =back
                   8056: 
                   8057: =head2 User Modification
                   8058: 
                   8059: =over 4
                   8060: 
                   8061: =item *
                   8062: 
                   8063: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8064: user for the level given by URL.  Optional start and end dates (leave empty
                   8065: string or zero for "no date")
1.191     harris41 8066: 
                   8067: =item *
                   8068: 
1.243     albertel 8069: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8070: change a users, password, possible return values are: ok,
                   8071: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8072: refused
1.191     harris41 8073: 
                   8074: =item *
                   8075: 
1.243     albertel 8076: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8077: 
                   8078: =item *
                   8079: 
1.243     albertel 8080: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8081: modify user
1.191     harris41 8082: 
                   8083: =item *
                   8084: 
1.286     matthew  8085: modifystudent
                   8086: 
                   8087: modify a students enrollment and identification information.
                   8088: The course id is resolved based on the current users environment.  
                   8089: This means the envoking user must be a course coordinator or otherwise
                   8090: associated with a course.
                   8091: 
1.297     matthew  8092: This call is essentially a wrapper for lonnet::modifyuser and
                   8093: lonnet::modify_student_enrollment
1.286     matthew  8094: 
                   8095: Inputs: 
                   8096: 
                   8097: =over 4
                   8098: 
                   8099: =item B<$udom> Students loncapa domain
                   8100: 
                   8101: =item B<$uname> Students loncapa login name
                   8102: 
                   8103: =item B<$uid> Students id/student number
                   8104: 
                   8105: =item B<$umode> Students authentication mode
                   8106: 
                   8107: =item B<$upass> Students password
                   8108: 
                   8109: =item B<$first> Students first name
                   8110: 
                   8111: =item B<$middle> Students middle name
                   8112: 
                   8113: =item B<$last> Students last name
                   8114: 
                   8115: =item B<$gene> Students generation
                   8116: 
                   8117: =item B<$usec> Students section in course
                   8118: 
                   8119: =item B<$end> Unix time of the roles expiration
                   8120: 
                   8121: =item B<$start> Unix time of the roles start date
                   8122: 
                   8123: =item B<$forceid> If defined, allow $uid to be changed
                   8124: 
                   8125: =item B<$desiredhome> server to use as home server for student
                   8126: 
                   8127: =back
1.297     matthew  8128: 
                   8129: =item *
                   8130: 
                   8131: modify_student_enrollment
                   8132: 
                   8133: Change a students enrollment status in a class.  The environment variable
                   8134: 'role.request.course' must be defined for this function to proceed.
                   8135: 
                   8136: Inputs:
                   8137: 
                   8138: =over 4
                   8139: 
                   8140: =item $udom, students domain
                   8141: 
                   8142: =item $uname, students name
                   8143: 
                   8144: =item $uid, students user id
                   8145: 
                   8146: =item $first, students first name
                   8147: 
                   8148: =item $middle
                   8149: 
                   8150: =item $last
                   8151: 
                   8152: =item $gene
                   8153: 
                   8154: =item $usec
                   8155: 
                   8156: =item $end
                   8157: 
                   8158: =item $start
                   8159: 
                   8160: =back
                   8161: 
1.191     harris41 8162: 
                   8163: =item *
                   8164: 
1.243     albertel 8165: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8166: custom role; give a custom role to a user for the level given by URL.  Specify
                   8167: name and domain of role author, and role name
1.191     harris41 8168: 
                   8169: =item *
                   8170: 
1.243     albertel 8171: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8172: 
                   8173: =item *
                   8174: 
1.243     albertel 8175: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8176: 
                   8177: =back
                   8178: 
                   8179: =head2 Course Infomation
                   8180: 
                   8181: =over 4
1.191     harris41 8182: 
                   8183: =item *
                   8184: 
1.631     albertel 8185: coursedescription($courseid) : returns a hash of information about the
                   8186: specified course id, including all environment settings for the
                   8187: course, the description of the course will be in the hash under the
                   8188: key 'description'
1.191     harris41 8189: 
                   8190: =item *
                   8191: 
1.624     albertel 8192: resdata($name,$domain,$type,@which) : request for current parameter
                   8193: setting for a specific $type, where $type is either 'course' or 'user',
                   8194: @what should be a list of parameters to ask about. This routine caches
                   8195: answers for 5 minutes.
1.243     albertel 8196: 
                   8197: =back
                   8198: 
                   8199: =head2 Course Modification
                   8200: 
                   8201: =over 4
1.191     harris41 8202: 
                   8203: =item *
                   8204: 
1.243     albertel 8205: writecoursepref($courseid,%prefs) : write preferences (environment
                   8206: database) for a course
1.191     harris41 8207: 
                   8208: =item *
                   8209: 
1.243     albertel 8210: createcourse($udom,$description,$url) : make/modify course
                   8211: 
                   8212: =back
                   8213: 
                   8214: =head2 Resource Subroutines
                   8215: 
                   8216: =over 4
1.191     harris41 8217: 
                   8218: =item *
                   8219: 
1.243     albertel 8220: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8221: 
                   8222: =item *
                   8223: 
1.243     albertel 8224: repcopy($filename) : subscribes to the requested file, and attempts to
                   8225: replicate from the owning library server, Might return
1.607     raeburn  8226: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8227: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8228: resource. Expects the local filesystem pathname
                   8229: (/home/httpd/html/res/....)
                   8230: 
                   8231: =back
                   8232: 
                   8233: =head2 Resource Information
                   8234: 
                   8235: =over 4
1.191     harris41 8236: 
                   8237: =item *
                   8238: 
1.243     albertel 8239: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8240: a vairety of different possible values, $varname should be a request
                   8241: string, and the other parameters can be used to specify who and what
                   8242: one is asking about.
                   8243: 
                   8244: Possible values for $varname are environment.lastname (or other item
                   8245: from the envirnment hash), user.name (or someother aspect about the
                   8246: user), resource.0.maxtries (or some other part and parameter of a
                   8247: resource)
1.204     albertel 8248: 
                   8249: =item *
                   8250: 
1.243     albertel 8251: directcondval($number) : get current value of a condition; reads from a state
                   8252: string
1.204     albertel 8253: 
                   8254: =item *
                   8255: 
1.243     albertel 8256: condval($condidx) : value of condition index based on state
1.204     albertel 8257: 
                   8258: =item *
                   8259: 
1.243     albertel 8260: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8261: resource's metadata, $what should be either a specific key, or either
                   8262: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8263: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8264: 
                   8265: this function automatically caches all requests
1.191     harris41 8266: 
                   8267: =item *
                   8268: 
1.243     albertel 8269: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8270: network of library servers; returns file handle of where SQL and regex results
                   8271: will be stored for query
1.191     harris41 8272: 
                   8273: =item *
                   8274: 
1.243     albertel 8275: symbread($filename) : return symbolic list entry (filename argument optional);
                   8276: returns the data handle
1.191     harris41 8277: 
                   8278: =item *
                   8279: 
1.243     albertel 8280: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8281: a possible symb for the URL in $thisfn, and if is an encryypted
                   8282: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8283: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8284: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8285: 
1.191     harris41 8286: 
                   8287: =item *
                   8288: 
1.243     albertel 8289: symbclean($symb) : removes versions numbers from a symb, returns the
                   8290: cleaned symb
1.191     harris41 8291: 
                   8292: =item *
                   8293: 
1.243     albertel 8294: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8295: course map, user must be in a course for it to work.
1.191     harris41 8296: 
                   8297: =item *
                   8298: 
1.243     albertel 8299: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8300: 
                   8301: =item *
                   8302: 
1.243     albertel 8303: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8304: a random seed, all arguments are optional, if they aren't sent it uses the
                   8305: environment to derive them. Note: if symb isn't sent and it can't get one
                   8306: from &symbread it will use the current time as its return value
1.191     harris41 8307: 
                   8308: =item *
                   8309: 
1.243     albertel 8310: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8311: unfakeable, receipt
1.191     harris41 8312: 
                   8313: =item *
                   8314: 
1.620     albertel 8315: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8316: 
                   8317: =item *
                   8318: 
1.243     albertel 8319: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8320: 
                   8321: =item *
                   8322: 
1.243     albertel 8323: 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 8324: 
                   8325: =item *
                   8326: 
1.243     albertel 8327: 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 8328: 
                   8329: =item *
                   8330: 
1.243     albertel 8331: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8332: 
                   8333: =item *
                   8334: 
1.243     albertel 8335: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8336: forcing spreadsheet to reevaluate the resource scores next time.
                   8337: 
                   8338: =back
                   8339: 
                   8340: =head2 Storing/Retreiving Data
                   8341: 
                   8342: =over 4
1.191     harris41 8343: 
                   8344: =item *
                   8345: 
1.243     albertel 8346: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8347: for this url; hashref needs to be given and should be a \%hashname; the
                   8348: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8349: be derived from the env
1.191     harris41 8350: 
                   8351: =item *
                   8352: 
1.243     albertel 8353: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8354: uses critical subroutine
1.191     harris41 8355: 
                   8356: =item *
                   8357: 
1.243     albertel 8358: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8359: all args are optional
1.191     harris41 8360: 
                   8361: =item *
                   8362: 
1.717     albertel 8363: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8364: dumps the complete (or key matching regexp) namespace into a hash
                   8365: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8366: normally &store()ed into
                   8367: 
                   8368: $range should be either an integer '100' (give me the first 100
                   8369:                                            matching records)
                   8370:               or be  two integers sperated by a - with no spaces
                   8371:                  '30-50' (give me the 30th through the 50th matching
                   8372:                           records)
                   8373: 
                   8374: 
                   8375: =item *
                   8376: 
                   8377: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8378: replaces a &store() version of data with a replacement set of data
                   8379: for a particular resource in a namespace passed in the $storehash hash 
                   8380: reference
                   8381: 
                   8382: =item *
                   8383: 
1.243     albertel 8384: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8385: works very similar to store/cstore, but all data is stored in a
                   8386: temporary location and can be reset using tmpreset, $storehash should
                   8387: be a hash reference, returns nothing on success
1.191     harris41 8388: 
                   8389: =item *
                   8390: 
1.243     albertel 8391: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8392: similar to restore, but all data is stored in a temporary location and
                   8393: can be reset using tmpreset. Returns a hash of values on success,
                   8394: error string otherwise.
1.191     harris41 8395: 
                   8396: =item *
                   8397: 
1.243     albertel 8398: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8399: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8400: 
                   8401: =item *
                   8402: 
1.243     albertel 8403: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8404: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8405: 
                   8406: =item *
                   8407: 
1.243     albertel 8408: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8409: namesp ($udom and $uname are optional)
1.191     harris41 8410: 
                   8411: =item *
                   8412: 
1.702     albertel 8413: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8414: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8415: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8416: 
1.702     albertel 8417: $range should be either an integer '100' (give me the first 100
                   8418:                                            matching records)
                   8419:               or be  two integers sperated by a - with no spaces
                   8420:                  '30-50' (give me the 30th through the 50th matching
                   8421:                           records)
1.449     matthew  8422: =item *
                   8423: 
                   8424: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8425: $store can be a scalar, an array reference, or if the amount to be 
                   8426: incremented is > 1, a hash reference.
                   8427: 
                   8428: ($udom and $uname are optional)
1.191     harris41 8429: 
                   8430: =item *
                   8431: 
1.243     albertel 8432: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8433: ($udom and $uname are optional)
1.191     harris41 8434: 
                   8435: =item *
                   8436: 
1.243     albertel 8437: cput($namespace,$storehash,$udom,$uname) : critical put
                   8438: ($udom and $uname are optional)
1.191     harris41 8439: 
                   8440: =item *
                   8441: 
1.748     albertel 8442: newput($namespace,$storehash,$udom,$uname) :
                   8443: 
                   8444: Attempts to store the items in the $storehash, but only if they don't
                   8445: currently exist, if this succeeds you can be certain that you have 
                   8446: successfully created a new key value pair in the $namespace db.
                   8447: 
                   8448: 
                   8449: Args:
                   8450:  $namespace: name of database to store values to
                   8451:  $storehash: hashref to store to the db
                   8452:  $udom: (optional) domain of user containing the db
                   8453:  $uname: (optional) name of user caontaining the db
                   8454: 
                   8455: Returns:
                   8456:  'ok' -> succeeded in storing all keys of $storehash
                   8457:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8458:                         least <key> already existed in the db (other
                   8459:                         requested keys may also already exist)
                   8460:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8461:  'con_lost' -> unable to contact request server
                   8462:  'refused' -> action was not allowed by remote machine
                   8463: 
                   8464: 
                   8465: =item *
                   8466: 
1.243     albertel 8467: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8468: reference filled in from namesp (encrypts the return communication)
                   8469: ($udom and $uname are optional)
1.191     harris41 8470: 
                   8471: =item *
                   8472: 
1.243     albertel 8473: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8474: critical subroutine
                   8475: 
1.806     raeburn  8476: =item *
                   8477: 
                   8478: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8479: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8480: 
                   8481: =item *
                   8482: 
                   8483: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8484: 
1.243     albertel 8485: =back
                   8486: 
                   8487: =head2 Network Status Functions
                   8488: 
                   8489: =over 4
1.191     harris41 8490: 
                   8491: =item *
                   8492: 
                   8493: dirlist($uri) : return directory list based on URI
                   8494: 
                   8495: =item *
                   8496: 
1.243     albertel 8497: spareserver() : find server with least workload from spare.tab
                   8498: 
                   8499: =back
                   8500: 
                   8501: =head2 Apache Request
                   8502: 
                   8503: =over 4
1.191     harris41 8504: 
                   8505: =item *
                   8506: 
1.243     albertel 8507: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8508: localhost, posts hash
                   8509: 
                   8510: =back
                   8511: 
                   8512: =head2 Data to String to Data
                   8513: 
                   8514: =over 4
1.191     harris41 8515: 
                   8516: =item *
                   8517: 
1.243     albertel 8518: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8519: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8520: 
                   8521: =item *
                   8522: 
1.243     albertel 8523: hashref2str($hashref) : convert a hashref into a string complete with
                   8524: escaping and '=' and '&' separators, supports elements that are
                   8525: arrayrefs and hashrefs
1.191     harris41 8526: 
                   8527: =item *
                   8528: 
1.243     albertel 8529: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8530: with escaping and '&' separators, supports elements that are arrayrefs
                   8531: and hashrefs
1.191     harris41 8532: 
                   8533: =item *
                   8534: 
1.243     albertel 8535: str2hash($string) : convert string to hash using unescaping and
                   8536: splitting on '=' and '&', supports elements that are arrayrefs and
                   8537: hashrefs
1.191     harris41 8538: 
                   8539: =item *
                   8540: 
1.243     albertel 8541: str2array($string) : convert string to hash using unescaping and
                   8542: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8543: 
                   8544: =back
                   8545: 
                   8546: =head2 Logging Routines
                   8547: 
                   8548: =over 4
                   8549: 
                   8550: These routines allow one to make log messages in the lonnet.log and
                   8551: lonnet.perm logfiles.
1.191     harris41 8552: 
                   8553: =item *
                   8554: 
1.243     albertel 8555: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8556: 
                   8557: =item *
                   8558: 
1.243     albertel 8559: logthis() : append message to the normal lonnet.log file, it gets
                   8560: preiodically rolled over and deleted.
1.191     harris41 8561: 
                   8562: =item *
                   8563: 
1.243     albertel 8564: logperm() : append a permanent message to lonnet.perm.log, this log
                   8565: file never gets deleted by any automated portion of the system, only
                   8566: messages of critical importance should go in here.
                   8567: 
                   8568: =back
                   8569: 
                   8570: =head2 General File Helper Routines
                   8571: 
                   8572: =over 4
1.191     harris41 8573: 
                   8574: =item *
                   8575: 
1.481     raeburn  8576: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8577: (a) files in /uploaded
                   8578:   (i) If a local copy of the file exists - 
                   8579:       compares modification date of local copy with last-modified date for 
                   8580:       definitive version stored on home server for course. If local copy is 
                   8581:       stale, requests a new version from the home server and stores it. 
                   8582:       If the original has been removed from the home server, then local copy 
                   8583:       is unlinked.
                   8584:   (ii) If local copy does not exist -
                   8585:       requests the file from the home server and stores it. 
                   8586:   
                   8587:   If $caller is 'uploadrep':  
                   8588:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8589:     for request for files originally uploaded via DOCS. 
                   8590:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8591:   
                   8592:   Otherwise:
                   8593:      This indicates a call from the content generation phase of the request.
                   8594:      -  returns the entire contents of the file or -1.
                   8595:      
                   8596: (b) files in /res
                   8597:    - returns the entire contents of a file or -1; 
                   8598:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8599: 
1.712     albertel 8600: 
                   8601: =item *
                   8602: 
                   8603: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8604:                   reference
                   8605: 
                   8606: returns either a stat() list of data about the file or an empty list
                   8607: if the file doesn't exist or couldn't find out about it (connection
                   8608: problems or user unknown)
                   8609: 
1.191     harris41 8610: =item *
                   8611: 
1.243     albertel 8612: filelocation($dir,$file) : returns file system location of a file
                   8613: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8614: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8615: and a file of ../bob will become /a/bob)
1.191     harris41 8616: 
                   8617: =item *
                   8618: 
                   8619: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8620: filelocation except for hrefs
                   8621: 
                   8622: =item *
                   8623: 
                   8624: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8625: 
1.243     albertel 8626: =back
                   8627: 
1.608     albertel 8628: =head2 Usererfile file routines (/uploaded*)
                   8629: 
                   8630: =over 4
                   8631: 
                   8632: =item *
                   8633: 
                   8634: userfileupload(): main rotine for putting a file in a user or course's
                   8635:                   filespace, arguments are,
                   8636: 
1.620     albertel 8637:  formname - required - this is the name of the element in $env where the
1.608     albertel 8638:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8639:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8640:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8641:  coursedoc - if true, store the file in the course of the active role
                   8642:              of the current user
                   8643:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8644:          if undefined, it will be placed in "unknown"
                   8645: 
                   8646:  (This routine calls clean_filename() to remove any dangerous
                   8647:  characters from the filename, and then calls finuserfileupload() to
                   8648:  complete the transaction)
                   8649: 
                   8650:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8651:  and /adm/notfound.html if unsuccessful
                   8652: 
                   8653: =item *
                   8654: 
                   8655: clean_filename(): routine for cleaing a filename up for storage in
                   8656:                  userfile space, argument is:
                   8657: 
                   8658:  filename - proposed filename
                   8659: 
                   8660: returns: the new clean filename
                   8661: 
                   8662: =item *
                   8663: 
                   8664: finishuserfileupload(): routine that creaes and sends the file to
                   8665: userspace, probably shouldn't be called directly
                   8666: 
                   8667:   docuname: username or courseid of destination for the file
                   8668:   docudom: domain of user/course of destination for the file
                   8669:   formname: same as for userfileupload()
                   8670:   fname: filename (inculding subdirectories) for the file
                   8671: 
                   8672:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8673:  and /adm/notfound.html if unsuccessful
                   8674: 
                   8675: =item *
                   8676: 
                   8677: renameuserfile(): renames an existing userfile to a new name
                   8678: 
                   8679:   Args:
                   8680:    docuname: username or courseid of destination for the file
                   8681:    docudom: domain of user/course of destination for the file
                   8682:    old: current file name (including any subdirs under userfiles)
                   8683:    new: desired file name (including any subdirs under userfiles)
                   8684: 
                   8685: =item *
                   8686: 
                   8687: mkdiruserfile(): creates a directory is a userfiles dir
                   8688: 
                   8689:   Args:
                   8690:    docuname: username or courseid of destination for the file
                   8691:    docudom: domain of user/course of destination for the file
                   8692:    dir: dir to create (including any subdirs under userfiles)
                   8693: 
                   8694: =item *
                   8695: 
                   8696: removeuserfile(): removes a file that exists in userfiles
                   8697: 
                   8698:   Args:
                   8699:    docuname: username or courseid of destination for the file
                   8700:    docudom: domain of user/course of destination for the file
                   8701:    fname: filname to delete (including any subdirs under userfiles)
                   8702: 
                   8703: =item *
                   8704: 
                   8705: removeuploadedurl(): convience function for removeuserfile()
                   8706: 
                   8707:   Args:
                   8708:    url:  a full /uploaded/... url to delete
                   8709: 
1.747     albertel 8710: =item * 
                   8711: 
                   8712: get_portfile_permissions():
                   8713:   Args:
                   8714:     domain: domain of user or course contain the portfolio files
                   8715:     user: name of user or num of course contain the portfolio files
                   8716:   Returns:
                   8717:     hashref of a dump of the proper file_permissions.db
                   8718:    
                   8719: 
                   8720: =item * 
                   8721: 
                   8722: get_access_controls():
                   8723: 
                   8724: Args:
                   8725:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8726:   group: (optional) the group you want the files associated with
                   8727:   file: (optional) the file you want access info on
                   8728: 
                   8729: Returns:
1.749     raeburn  8730:     a hash (keys are file names) of hashes containing
                   8731:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8732:         values are XML containing access control settings (see below) 
1.747     albertel 8733: 
                   8734: Internal notes:
                   8735: 
1.749     raeburn  8736:  access controls are stored in file_permissions.db as key=value pairs.
                   8737:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8738:         where scope -> public,guest,course,group,domains or users.
                   8739:               end -> UNIX time for end of access (0 -> no end date)
                   8740:               start -> UNIX time for start of access
                   8741: 
                   8742:     value -> XML description of access control
                   8743:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8744:             <start></start>
                   8745:             <end></end>
                   8746: 
                   8747:             <password></password>  for scope type = guest
                   8748: 
                   8749:             <domain></domain>     for scope type = course or group
                   8750:             <number></number>
                   8751:             <roles id="">
                   8752:              <role></role>
                   8753:              <access></access>
                   8754:              <section></section>
                   8755:              <group></group>
                   8756:             </roles>
                   8757: 
                   8758:             <dom></dom>         for scope type = domains
                   8759: 
                   8760:             <users>             for scope type = users
                   8761:              <user>
                   8762:               <uname></uname>
                   8763:               <udom></udom>
                   8764:              </user>
                   8765:             </users>
                   8766:            </scope> 
                   8767:               
                   8768:  Access data is also aggregated for each file in an additional key=value pair:
                   8769:  key -> path to file/file_name\0accesscontrol 
                   8770:  value -> reference to hash
                   8771:           hash contains key = value pairs
                   8772:           where key = uniqueID:scope_end_start
                   8773:                 value = UNIX time record was last updated
                   8774: 
                   8775:           Used to improve speed of look-ups of access controls for each file.  
                   8776:  
                   8777:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8778: 
                   8779: modify_access_controls():
                   8780: 
                   8781: Modifies access controls for a portfolio file
                   8782: Args
                   8783: 1. file name
                   8784: 2. reference to hash of required changes,
                   8785: 3. domain
                   8786: 4. username
                   8787:   where domain,username are the domain of the portfolio owner 
                   8788:   (either a user or a course) 
                   8789: 
                   8790: Returns:
                   8791: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8792: 2. result of deletions ('ok' or 'error', with error message).
                   8793: 3. reference to hash of any new or updated access controls.
                   8794: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8795:    key = integer (inbound ID)
                   8796:    value = uniqueID  
1.747     albertel 8797: 
1.608     albertel 8798: =back
                   8799: 
1.243     albertel 8800: =head2 HTTP Helper Routines
                   8801: 
                   8802: =over 4
                   8803: 
1.191     harris41 8804: =item *
                   8805: 
                   8806: escape() : unpack non-word characters into CGI-compatible hex codes
                   8807: 
                   8808: =item *
                   8809: 
                   8810: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8811: 
1.243     albertel 8812: =back
                   8813: 
                   8814: =head1 PRIVATE SUBROUTINES
                   8815: 
                   8816: =head2 Underlying communication routines (Shouldn't call)
                   8817: 
                   8818: =over 4
                   8819: 
                   8820: =item *
                   8821: 
                   8822: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8823: 
                   8824: =item *
                   8825: 
                   8826: reply() : uses subreply to send a message to remote machine, logs all failures
                   8827: 
                   8828: =item *
                   8829: 
                   8830: critical() : passes a critical message to another server; if cannot
                   8831: get through then place message in connection buffer directory and
                   8832: returns con_delayed, if incapable of saving message, returns
                   8833: con_failed
                   8834: 
                   8835: =item *
                   8836: 
                   8837: reconlonc() : tries to reconnect lonc client processes.
                   8838: 
                   8839: =back
                   8840: 
                   8841: =head2 Resource Access Logging
                   8842: 
                   8843: =over 4
                   8844: 
                   8845: =item *
                   8846: 
                   8847: flushcourselogs() : flush (save) buffer logs and access logs
                   8848: 
                   8849: =item *
                   8850: 
                   8851: courselog($what) : save message for course in hash
                   8852: 
                   8853: =item *
                   8854: 
                   8855: courseacclog($what) : save message for course using &courselog().  Perform
                   8856: special processing for specific resource types (problems, exams, quizzes, etc).
                   8857: 
1.191     harris41 8858: =item *
                   8859: 
                   8860: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8861: as a PerlChildExitHandler
1.243     albertel 8862: 
                   8863: =back
                   8864: 
                   8865: =head2 Other
                   8866: 
                   8867: =over 4
                   8868: 
                   8869: =item *
                   8870: 
                   8871: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8872: 
                   8873: =back
                   8874: 
                   8875: =cut

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