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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.845   ! albertel    4: # $Id: lonnet.pm,v 1.844 2007/03/03 02:16:10 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.844     albertel   38: qw(%perlvar %badServerCache %iphost %spareid 
1.845   ! albertel   39:    %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.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.845   ! albertel 2136:     my %libserv = &all_library();
        !          2137:     foreach my $tryserver (keys(%libserv)) {
        !          2138:         if ( (  $hostidflag == 1 
        !          2139: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
        !          2140: 	     || (!defined($hostidflag)) ) {
        !          2141: 
        !          2142: 	    if ($domfilter eq ''
        !          2143: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2144: 	        foreach my $line (
1.844     albertel 2145:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2146: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2147:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2148:                                $tryserver))) {
1.800     albertel 2149: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2150:                     if (($key) && ($value)) {
1.516     raeburn  2151: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2152:                     }
1.353     www      2153:                 }
                   2154:             }
                   2155:         }
                   2156:     }
                   2157:     return %returnhash;
                   2158: }
                   2159: 
1.658     raeburn  2160: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2161: 
                   2162: sub dcmailput {
1.685     raeburn  2163:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2164:     my $status = &Apache::lonnet::critical(
1.740     www      2165:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2166:        &escape($message),$server);
1.662     raeburn  2167:     return $status;
                   2168: }
                   2169: 
1.658     raeburn  2170: sub dcmaildump {
                   2171:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2172:     my %returnhash=();
                   2173:     if (exists($domain_primary{$dom})) {
                   2174:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2175:                                                          &escape($enddate).':';
                   2176: 	my @esc_senders=map { &escape($_)} @$senders;
                   2177: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2178: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2179:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2180:             if (($key) && ($value)) {
                   2181:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2182:             }
                   2183:         }
                   2184:     }
                   2185:     return %returnhash;
                   2186: }
1.662     raeburn  2187: # ---------------------------------------------------------- Domain roles
                   2188: 
                   2189: sub get_domain_roles {
                   2190:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2191:     if (undef($startdate) || $startdate eq '') {
                   2192:         $startdate = '.';
                   2193:     }
                   2194:     if (undef($enddate) || $enddate eq '') {
                   2195:         $enddate = '.';
                   2196:     }
                   2197:     my $rolelist = join(':',@{$roles});
                   2198:     my %personnel = ();
1.841     albertel 2199: 
                   2200:     my %servers = &get_servers($dom,'library');
                   2201:     foreach my $tryserver (keys(%servers)) {
                   2202: 	%{$personnel{$tryserver}}=();
                   2203: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2204: 					    &escape($startdate).':'.
                   2205: 					    &escape($enddate).':'.
                   2206: 					    &escape($rolelist), $tryserver))) {
                   2207: 	    my ($key,$value) = split(/\=/,$line,2);
                   2208: 	    if (($key) && ($value)) {
                   2209: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2210: 	    }
                   2211: 	}
1.662     raeburn  2212:     }
                   2213:     return %personnel;
                   2214: }
1.658     raeburn  2215: 
1.149     www      2216: # ----------------------------------------------------------- Check out an item
                   2217: 
1.504     albertel 2218: sub get_first_access {
                   2219:     my ($type,$argsymb)=@_;
1.790     albertel 2220:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2221:     if ($argsymb) { $symb=$argsymb; }
                   2222:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2223:     if ($type eq 'map') {
                   2224: 	$res=&symbread($map);
                   2225:     } else {
                   2226: 	$res=$symb;
                   2227:     }
                   2228:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2229:     return $times{"$courseid\0$res"};
1.504     albertel 2230: }
                   2231: 
                   2232: sub set_first_access {
                   2233:     my ($type)=@_;
1.790     albertel 2234:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2235:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2236:     if ($type eq 'map') {
                   2237: 	$res=&symbread($map);
                   2238:     } else {
                   2239: 	$res=$symb;
                   2240:     }
                   2241:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2242:     if (!$firstaccess) {
1.588     albertel 2243: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2244:     }
                   2245:     return 'already_set';
1.504     albertel 2246: }
                   2247: 
1.149     www      2248: sub checkout {
                   2249:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2250:     my $now=time;
                   2251:     my $lonhost=$perlvar{'lonHostID'};
                   2252:     my $infostr=&escape(
1.234     www      2253:                  'CHECKOUTTOKEN&'.
1.149     www      2254:                  $tuname.'&'.
                   2255:                  $tudom.'&'.
                   2256:                  $tcrsid.'&'.
                   2257:                  $symb.'&'.
                   2258: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2259:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2260:     if ($token=~/^error\:/) { 
1.672     albertel 2261:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2262:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2263:                  "</font>");
                   2264:         return ''; 
                   2265:     }
                   2266: 
1.149     www      2267:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2268:     $token=~tr/a-z/A-Z/;
                   2269: 
1.153     www      2270:     my %infohash=('resource.0.outtoken' => $token,
                   2271:                   'resource.0.checkouttime' => $now,
                   2272:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2273: 
                   2274:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2275:        return '';
1.151     www      2276:     } else {
1.672     albertel 2277:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2278:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2279:                  "</font>");
1.149     www      2280:     }    
                   2281: 
                   2282:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2283:                          &escape('Checkout '.$infostr.' - '.
                   2284:                                                  $token)) ne 'ok') {
                   2285: 	return '';
1.151     www      2286:     } else {
1.672     albertel 2287:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2288:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2289:                  "</font>");
1.149     www      2290:     }
1.151     www      2291:     return $token;
1.149     www      2292: }
                   2293: 
                   2294: # ------------------------------------------------------------ Check in an item
                   2295: 
                   2296: sub checkin {
                   2297:     my $token=shift;
1.150     www      2298:     my $now=time;
                   2299:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2300:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2301:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2302:     $dtoken=~s/\W/\_/g;
1.234     www      2303:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2304:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2305: 
1.154     www      2306:     unless (($tuname) && ($tudom)) {
                   2307:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2308:         return '';
                   2309:     }
                   2310:     
                   2311:     unless (&allowed('mgr',$tcrsid)) {
                   2312:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2313:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2314:         return '';
                   2315:     }
                   2316: 
1.153     www      2317:     my %infohash=('resource.0.intoken' => $token,
                   2318:                   'resource.0.checkintime' => $now,
                   2319:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2320: 
                   2321:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2322:        return '';
                   2323:     }    
                   2324: 
                   2325:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2326:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2327: 	return '';
                   2328:     }
                   2329: 
                   2330:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2331: }
                   2332: 
                   2333: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2334: 
                   2335: sub expirespread {
                   2336:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2337:     my $cid=$env{'request.course.id'}; 
1.110     www      2338:     if ($cid) {
                   2339:        my $now=time;
                   2340:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2341:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2342:                             $env{'course.'.$cid.'.num'}.
1.110     www      2343: 	        	    ':nohist_expirationdates:'.
                   2344:                             &escape($key).'='.$now,
1.620     albertel 2345:                             $env{'course.'.$cid.'.home'})
1.110     www      2346:     }
                   2347:     return 'ok';
1.14      www      2348: }
                   2349: 
1.109     www      2350: # ----------------------------------------------------- Devalidate Spreadsheets
                   2351: 
                   2352: sub devalidate {
1.325     www      2353:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2354:     my $cid=$env{'request.course.id'}; 
1.109     www      2355:     if ($cid) {
1.391     matthew  2356:         # delete the stored spreadsheets for
                   2357:         # - the student level sheet of this user in course's homespace
                   2358:         # - the assessment level sheet for this resource 
                   2359:         #   for this user in user's homespace
1.553     albertel 2360: 	# - current conditional state info
1.325     www      2361: 	my $key=$uname.':'.$udom.':';
1.109     www      2362:         my $status=
1.299     matthew  2363: 	    &del('nohist_calculatedsheets',
1.391     matthew  2364: 		 [$key.'studentcalc:'],
1.620     albertel 2365: 		 $env{'course.'.$cid.'.domain'},
                   2366: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2367: 		.' '.
                   2368: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2369: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2370:         unless ($status eq 'ok ok') {
                   2371:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2372:                     $uname.' at '.$udom.' for '.
1.109     www      2373: 		    $symb.': '.$status);
1.133     albertel 2374:         }
1.553     albertel 2375: 	&delenv('user.state.'.$cid);
1.109     www      2376:     }
                   2377: }
                   2378: 
1.265     albertel 2379: sub get_scalar {
                   2380:     my ($string,$end) = @_;
                   2381:     my $value;
                   2382:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2383: 	$value = $1;
                   2384:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2385: 	$value = $1;
                   2386:     }
                   2387:     return &unescape($value);
                   2388: }
                   2389: 
                   2390: sub array2str {
                   2391:   my (@array) = @_;
                   2392:   my $result=&arrayref2str(\@array);
                   2393:   $result=~s/^__ARRAY_REF__//;
                   2394:   $result=~s/__END_ARRAY_REF__$//;
                   2395:   return $result;
                   2396: }
                   2397: 
1.204     albertel 2398: sub arrayref2str {
                   2399:   my ($arrayref) = @_;
1.265     albertel 2400:   my $result='__ARRAY_REF__';
1.204     albertel 2401:   foreach my $elem (@$arrayref) {
1.265     albertel 2402:     if(ref($elem) eq 'ARRAY') {
                   2403:       $result.=&arrayref2str($elem).'&';
                   2404:     } elsif(ref($elem) eq 'HASH') {
                   2405:       $result.=&hashref2str($elem).'&';
                   2406:     } elsif(ref($elem)) {
                   2407:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2408:     } else {
                   2409:       $result.=&escape($elem).'&';
                   2410:     }
                   2411:   }
                   2412:   $result=~s/\&$//;
1.265     albertel 2413:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2414:   return $result;
                   2415: }
                   2416: 
1.168     albertel 2417: sub hash2str {
1.204     albertel 2418:   my (%hash) = @_;
                   2419:   my $result=&hashref2str(\%hash);
1.265     albertel 2420:   $result=~s/^__HASH_REF__//;
                   2421:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2422:   return $result;
                   2423: }
                   2424: 
                   2425: sub hashref2str {
                   2426:   my ($hashref)=@_;
1.265     albertel 2427:   my $result='__HASH_REF__';
1.800     albertel 2428:   foreach my $key (sort(keys(%$hashref))) {
                   2429:     if (ref($key) eq 'ARRAY') {
                   2430:       $result.=&arrayref2str($key).'=';
                   2431:     } elsif (ref($key) eq 'HASH') {
                   2432:       $result.=&hashref2str($key).'=';
                   2433:     } elsif (ref($key)) {
1.265     albertel 2434:       $result.='=';
1.800     albertel 2435:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2436:     } else {
1.800     albertel 2437: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2438:     }
                   2439: 
1.800     albertel 2440:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2441:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2442:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2443:       $result.=&hashref2str($hashref->{$key}).'&';
                   2444:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2445:        $result.='&';
1.800     albertel 2446:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2447:     } else {
1.800     albertel 2448:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2449:     }
                   2450:   }
1.168     albertel 2451:   $result=~s/\&$//;
1.265     albertel 2452:   $result .= '__END_HASH_REF__';
1.168     albertel 2453:   return $result;
                   2454: }
                   2455: 
                   2456: sub str2hash {
1.265     albertel 2457:     my ($string)=@_;
                   2458:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2459:     return %$hash;
                   2460: }
                   2461: 
                   2462: sub str2hashref {
1.168     albertel 2463:   my ($string) = @_;
1.265     albertel 2464: 
                   2465:   my %hash;
                   2466: 
                   2467:   if($string !~ /^__HASH_REF__/) {
                   2468:       if (! ($string eq '' || !defined($string))) {
                   2469: 	  $hash{'error'}='Not hash reference';
                   2470:       }
                   2471:       return (\%hash, $string);
                   2472:   }
                   2473: 
                   2474:   $string =~ s/^__HASH_REF__//;
                   2475: 
                   2476:   while($string !~ /^__END_HASH_REF__/) {
                   2477:       #key
                   2478:       my $key='';
                   2479:       if($string =~ /^__HASH_REF__/) {
                   2480:           ($key, $string)=&str2hashref($string);
                   2481:           if(defined($key->{'error'})) {
                   2482:               $hash{'error'}='Bad data';
                   2483:               return (\%hash, $string);
                   2484:           }
                   2485:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2486:           ($key, $string)=&str2arrayref($string);
                   2487:           if($key->[0] eq 'Array reference error') {
                   2488:               $hash{'error'}='Bad data';
                   2489:               return (\%hash, $string);
                   2490:           }
                   2491:       } else {
                   2492:           $string =~ s/^(.*?)=//;
1.267     albertel 2493: 	  $key=&unescape($1);
1.265     albertel 2494:       }
                   2495:       $string =~ s/^=//;
                   2496: 
                   2497:       #value
                   2498:       my $value='';
                   2499:       if($string =~ /^__HASH_REF__/) {
                   2500:           ($value, $string)=&str2hashref($string);
                   2501:           if(defined($value->{'error'})) {
                   2502:               $hash{'error'}='Bad data';
                   2503:               return (\%hash, $string);
                   2504:           }
                   2505:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2506:           ($value, $string)=&str2arrayref($string);
                   2507:           if($value->[0] eq 'Array reference error') {
                   2508:               $hash{'error'}='Bad data';
                   2509:               return (\%hash, $string);
                   2510:           }
                   2511:       } else {
                   2512: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2513:       }
                   2514:       $string =~ s/^&//;
                   2515: 
                   2516:       $hash{$key}=$value;
1.204     albertel 2517:   }
1.265     albertel 2518: 
                   2519:   $string =~ s/^__END_HASH_REF__//;
                   2520: 
                   2521:   return (\%hash, $string);
1.204     albertel 2522: }
                   2523: 
                   2524: sub str2array {
1.265     albertel 2525:     my ($string)=@_;
                   2526:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2527:     return @$array;
                   2528: }
                   2529: 
                   2530: sub str2arrayref {
1.204     albertel 2531:   my ($string) = @_;
1.265     albertel 2532:   my @array;
                   2533: 
                   2534:   if($string !~ /^__ARRAY_REF__/) {
                   2535:       if (! ($string eq '' || !defined($string))) {
                   2536: 	  $array[0]='Array reference error';
                   2537:       }
                   2538:       return (\@array, $string);
                   2539:   }
                   2540: 
                   2541:   $string =~ s/^__ARRAY_REF__//;
                   2542: 
                   2543:   while($string !~ /^__END_ARRAY_REF__/) {
                   2544:       my $value='';
                   2545:       if($string =~ /^__HASH_REF__/) {
                   2546:           ($value, $string)=&str2hashref($string);
                   2547:           if(defined($value->{'error'})) {
                   2548:               $array[0] ='Array reference error';
                   2549:               return (\@array, $string);
                   2550:           }
                   2551:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2552:           ($value, $string)=&str2arrayref($string);
                   2553:           if($value->[0] eq 'Array reference error') {
                   2554:               $array[0] ='Array reference error';
                   2555:               return (\@array, $string);
                   2556:           }
                   2557:       } else {
                   2558: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2559:       }
                   2560:       $string =~ s/^&//;
                   2561: 
                   2562:       push(@array, $value);
1.191     harris41 2563:   }
1.265     albertel 2564: 
                   2565:   $string =~ s/^__END_ARRAY_REF__//;
                   2566: 
                   2567:   return (\@array, $string);
1.168     albertel 2568: }
                   2569: 
1.167     albertel 2570: # -------------------------------------------------------------------Temp Store
                   2571: 
1.168     albertel 2572: sub tmpreset {
                   2573:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2574:   if (!$symb) {
                   2575:     $symb=&symbread();
1.620     albertel 2576:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2577:   }
                   2578:   $symb=escape($symb);
                   2579: 
1.620     albertel 2580:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2581:   $namespace=~s/\//\_/g;
                   2582:   $namespace=~s/\W//g;
                   2583: 
1.620     albertel 2584:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2585:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2586:   if ($domain eq 'public' && $stuname eq 'public') {
                   2587:       $stuname=$ENV{'REMOTE_ADDR'};
                   2588:   }
1.168     albertel 2589:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2590:   my %hash;
                   2591:   if (tie(%hash,'GDBM_File',
                   2592: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2593: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2594:     foreach my $key (keys %hash) {
1.180     albertel 2595:       if ($key=~ /:$symb/) {
1.168     albertel 2596: 	delete($hash{$key});
                   2597:       }
                   2598:     }
                   2599:   }
                   2600: }
                   2601: 
1.167     albertel 2602: sub tmpstore {
1.168     albertel 2603:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2604: 
                   2605:   if (!$symb) {
                   2606:     $symb=&symbread();
1.620     albertel 2607:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2608:   }
                   2609:   $symb=escape($symb);
                   2610: 
                   2611:   if (!$namespace) {
                   2612:     # I don't think we would ever want to store this for a course.
                   2613:     # it seems this will only be used if we don't have a course.
1.620     albertel 2614:     #$namespace=$env{'request.course.id'};
1.168     albertel 2615:     #if (!$namespace) {
1.620     albertel 2616:       $namespace=$env{'request.state'};
1.168     albertel 2617:     #}
                   2618:   }
                   2619:   $namespace=~s/\//\_/g;
                   2620:   $namespace=~s/\W//g;
1.620     albertel 2621:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2622:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2623:   if ($domain eq 'public' && $stuname eq 'public') {
                   2624:       $stuname=$ENV{'REMOTE_ADDR'};
                   2625:   }
1.168     albertel 2626:   my $now=time;
                   2627:   my %hash;
                   2628:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2629:   if (tie(%hash,'GDBM_File',
                   2630: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2631: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2632:     $hash{"version:$symb"}++;
                   2633:     my $version=$hash{"version:$symb"};
                   2634:     my $allkeys=''; 
                   2635:     foreach my $key (keys(%$storehash)) {
                   2636:       $allkeys.=$key.':';
1.591     albertel 2637:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2638:     }
                   2639:     $hash{"$version:$symb:timestamp"}=$now;
                   2640:     $allkeys.='timestamp';
                   2641:     $hash{"$version:keys:$symb"}=$allkeys;
                   2642:     if (untie(%hash)) {
                   2643:       return 'ok';
                   2644:     } else {
                   2645:       return "error:$!";
                   2646:     }
                   2647:   } else {
                   2648:     return "error:$!";
                   2649:   }
                   2650: }
1.167     albertel 2651: 
1.168     albertel 2652: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2653: 
1.168     albertel 2654: sub tmprestore {
                   2655:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2656: 
1.168     albertel 2657:   if (!$symb) {
                   2658:     $symb=&symbread();
1.620     albertel 2659:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2660:   }
                   2661:   $symb=escape($symb);
                   2662: 
1.620     albertel 2663:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2664: 
1.620     albertel 2665:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2666:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2667:   if ($domain eq 'public' && $stuname eq 'public') {
                   2668:       $stuname=$ENV{'REMOTE_ADDR'};
                   2669:   }
1.168     albertel 2670:   my %returnhash;
                   2671:   $namespace=~s/\//\_/g;
                   2672:   $namespace=~s/\W//g;
                   2673:   my %hash;
                   2674:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2675:   if (tie(%hash,'GDBM_File',
                   2676: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2677: 	  &GDBM_READER(),0640)) {
1.168     albertel 2678:     my $version=$hash{"version:$symb"};
                   2679:     $returnhash{'version'}=$version;
                   2680:     my $scope;
                   2681:     for ($scope=1;$scope<=$version;$scope++) {
                   2682:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2683:       my @keys=split(/:/,$vkeys);
                   2684:       my $key;
                   2685:       $returnhash{"$scope:keys"}=$vkeys;
                   2686:       foreach $key (@keys) {
1.591     albertel 2687: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2688: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2689:       }
                   2690:     }
1.168     albertel 2691:     if (!(untie(%hash))) {
                   2692:       return "error:$!";
                   2693:     }
                   2694:   } else {
                   2695:     return "error:$!";
                   2696:   }
                   2697:   return %returnhash;
1.167     albertel 2698: }
                   2699: 
1.9       www      2700: # ----------------------------------------------------------------------- Store
                   2701: 
                   2702: sub store {
1.124     www      2703:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2704:     my $home='';
                   2705: 
1.168     albertel 2706:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2707: 
1.213     www      2708:     $symb=&symbclean($symb);
1.122     albertel 2709:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2710: 
1.620     albertel 2711:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2712:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2713: 
                   2714:     &devalidate($symb,$stuname,$domain);
1.109     www      2715: 
                   2716:     $symb=escape($symb);
1.187     www      2717:     if (!$namespace) { 
1.620     albertel 2718:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2719:           return ''; 
                   2720:        } 
                   2721:     }
1.620     albertel 2722:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2723: 
                   2724:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2725:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2726: 
1.12      www      2727:     my $namevalue='';
1.800     albertel 2728:     foreach my $key (keys(%$storehash)) {
                   2729:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2730:     }
1.12      www      2731:     $namevalue=~s/\&$//;
1.187     www      2732:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2733:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2734: }
                   2735: 
1.47      www      2736: # -------------------------------------------------------------- Critical Store
                   2737: 
                   2738: sub cstore {
1.124     www      2739:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2740:     my $home='';
                   2741: 
1.168     albertel 2742:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2743: 
1.213     www      2744:     $symb=&symbclean($symb);
1.122     albertel 2745:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2746: 
1.620     albertel 2747:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2748:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2749: 
                   2750:     &devalidate($symb,$stuname,$domain);
1.109     www      2751: 
                   2752:     $symb=escape($symb);
1.187     www      2753:     if (!$namespace) { 
1.620     albertel 2754:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2755:           return ''; 
                   2756:        } 
                   2757:     }
1.620     albertel 2758:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2759: 
                   2760:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2761:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2762: 
1.47      www      2763:     my $namevalue='';
1.800     albertel 2764:     foreach my $key (keys(%$storehash)) {
                   2765:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2766:     }
1.47      www      2767:     $namevalue=~s/\&$//;
1.187     www      2768:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2769:     return critical
                   2770:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2771: }
                   2772: 
1.9       www      2773: # --------------------------------------------------------------------- Restore
                   2774: 
                   2775: sub restore {
1.124     www      2776:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2777:     my $home='';
                   2778: 
1.168     albertel 2779:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2780: 
1.122     albertel 2781:     if (!$symb) {
                   2782:       unless ($symb=escape(&symbread())) { return ''; }
                   2783:     } else {
1.213     www      2784:       $symb=&escape(&symbclean($symb));
1.122     albertel 2785:     }
1.188     www      2786:     if (!$namespace) { 
1.620     albertel 2787:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2788:           return ''; 
                   2789:        } 
                   2790:     }
1.620     albertel 2791:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2792:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2793:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2794:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2795: 
1.12      www      2796:     my %returnhash=();
1.800     albertel 2797:     foreach my $line (split(/\&/,$answer)) {
                   2798: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2799:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2800:     }
1.75      www      2801:     my $version;
                   2802:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2803:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2804:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2805:        }
1.75      www      2806:     }
1.13      www      2807:     return %returnhash;
1.34      www      2808: }
                   2809: 
                   2810: # ---------------------------------------------------------- Course Description
                   2811: 
                   2812: sub coursedescription {
1.731     albertel 2813:     my ($courseid,$args)=@_;
1.34      www      2814:     $courseid=~s/^\///;
1.49      www      2815:     $courseid=~s/\_/\//g;
1.34      www      2816:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2817:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2818:     my $normalid=$cdomain.'_'.$cnum;
                   2819:     # need to always cache even if we get errors otherwise we keep 
                   2820:     # trying and trying and trying to get the course description.
                   2821:     my %envhash=();
                   2822:     my %returnhash=();
1.731     albertel 2823:     
                   2824:     my $expiretime=600;
                   2825:     if ($env{'request.course.id'} eq $normalid) {
                   2826: 	$expiretime=120;
                   2827:     }
                   2828: 
                   2829:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2830:     if (!$args->{'freshen_cache'}
                   2831: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2832: 	foreach my $key (keys(%env)) {
                   2833: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2834: 	    my ($setting) = $1;
                   2835: 	    $returnhash{$setting} = $env{$key};
                   2836: 	}
                   2837: 	return %returnhash;
                   2838:     }
                   2839: 
                   2840:     # get the data agin
                   2841:     if (!$args->{'one_time'}) {
                   2842: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2843:     }
1.811     albertel 2844: 
1.34      www      2845:     if ($chome ne 'no_host') {
1.302     albertel 2846:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2847:        if (!exists($returnhash{'con_lost'})) {
                   2848:            $returnhash{'home'}= $chome;
                   2849: 	   $returnhash{'domain'} = $cdomain;
                   2850: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2851:            if (!defined($returnhash{'type'})) {
                   2852:                $returnhash{'type'} = 'Course';
                   2853:            }
1.130     albertel 2854:            while (my ($name,$value) = each %returnhash) {
1.53      www      2855:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2856:            }
1.270     www      2857:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2858:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2859: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2860:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2861:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2862:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2863:        }
                   2864:     }
1.731     albertel 2865:     if (!$args->{'one_time'}) {
                   2866: 	&appenv(%envhash);
                   2867:     }
1.302     albertel 2868:     return %returnhash;
1.461     www      2869: }
                   2870: 
                   2871: # -------------------------------------------------See if a user is privileged
                   2872: 
                   2873: sub privileged {
                   2874:     my ($username,$domain)=@_;
                   2875:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2876: 			&homeserver($username,$domain));
                   2877:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2878:     my $now=time;
                   2879:     if ($rolesdump ne '') {
1.800     albertel 2880:         foreach my $entry (split(/&/,$rolesdump)) {
                   2881: 	    if ($entry!~/^rolesdef_/) {
                   2882: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2883: 		$area=~s/\_\w\w$//;
                   2884: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2885: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2886: 		    my $active=1;
                   2887: 		    if ($tend) {
                   2888: 			if ($tend<$now) { $active=0; }
                   2889: 		    }
                   2890: 		    if ($tstart) {
                   2891: 			if ($tstart>$now) { $active=0; }
                   2892: 		    }
                   2893: 		    if ($active) { return 1; }
                   2894: 		}
                   2895: 	    }
                   2896: 	}
                   2897:     }
                   2898:     return 0;
1.9       www      2899: }
1.1       albertel 2900: 
1.103     harris41 2901: # -------------------------------------------------------- Get user privileges
1.11      www      2902: 
                   2903: sub rolesinit {
                   2904:     my ($domain,$username,$authhost)=@_;
                   2905:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2906:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2907:     my %allroles=();
1.678     raeburn  2908:     my %allgroups=();   
1.11      www      2909:     my $now=time;
1.743     albertel 2910:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2911:     my $group_privs;
1.11      www      2912: 
                   2913:     if ($rolesdump ne '') {
1.800     albertel 2914:         foreach my $entry (split(/&/,$rolesdump)) {
                   2915: 	  if ($entry!~/^rolesdef_/) {
                   2916:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2917: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2918:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2919: 	    if ($role=~/^cr/) { 
1.807     albertel 2920: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2921: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2922: 		    ($tend,$tstart)=split('_',$trest);
                   2923: 		} else {
                   2924: 		    $trole=$role;
                   2925: 		}
1.678     raeburn  2926:             } elsif ($role =~ m|^gr/|) {
                   2927:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2928:                 ($trole,$group_privs) = split(/\//,$trole);
                   2929:                 $group_privs = &unescape($group_privs);
1.587     albertel 2930: 	    } else {
                   2931: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2932: 	    }
1.743     albertel 2933: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2934: 					 $username);
                   2935: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2936:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2937:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2938:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2939: 		my $spec=$trole.'.'.$area;
                   2940: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2941: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2942:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2943:                 } elsif ($trole eq 'gr') {
                   2944:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2945: 		} else {
1.567     raeburn  2946:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2947: 		}
1.12      www      2948:             }
1.662     raeburn  2949:           }
1.191     harris41 2950:         }
1.743     albertel 2951:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2952:         $userroles{'user.adv'}    = $adv;
                   2953: 	$userroles{'user.author'} = $author;
1.620     albertel 2954:         $env{'user.adv'}=$adv;
1.11      www      2955:     }
1.743     albertel 2956:     return \%userroles;  
1.11      www      2957: }
                   2958: 
1.567     raeburn  2959: sub set_arearole {
                   2960:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2961: # log the associated role with the area
                   2962:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2963:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2964: }
                   2965: 
                   2966: sub custom_roleprivs {
                   2967:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2968:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2969:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 2970:     if (&hostname($homsvr) ne '') {
1.567     raeburn  2971:         my ($rdummy,$roledef)=
                   2972:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2973:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2974:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2975:             if (defined($syspriv)) {
                   2976:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2977:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2978:             }
                   2979:             if ($tdomain ne '') {
                   2980:                 if (defined($dompriv)) {
                   2981:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2982:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2983:                 }
                   2984:                 if (($trest ne '') && (defined($coursepriv))) {
                   2985:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2986:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2987:                 }
                   2988:             }
                   2989:         }
                   2990:     }
                   2991: }
                   2992: 
1.678     raeburn  2993: sub group_roleprivs {
                   2994:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2995:     my $access = 1;
                   2996:     my $now = time;
                   2997:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2998:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2999:     if ($access) {
1.811     albertel 3000:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3001:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3002:     }
                   3003: }
1.567     raeburn  3004: 
                   3005: sub standard_roleprivs {
                   3006:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3007:     if (defined($pr{$trole.':s'})) {
                   3008:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3009:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3010:     }
                   3011:     if ($tdomain ne '') {
                   3012:         if (defined($pr{$trole.':d'})) {
                   3013:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3014:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3015:         }
                   3016:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3017:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3018:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3019:         }
                   3020:     }
                   3021: }
                   3022: 
                   3023: sub set_userprivs {
1.678     raeburn  3024:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3025:     my $author=0;
                   3026:     my $adv=0;
1.678     raeburn  3027:     my %grouproles = ();
                   3028:     if (keys(%{$allgroups}) > 0) {
                   3029:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3030:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3031:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3032:                 $trole = $1;
                   3033:                 $area = $2;
1.681     raeburn  3034:                 $sec = $3;
                   3035:                 $extendedarea = $area.$sec;
                   3036:                 if (exists($$allgroups{$area})) {
                   3037:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3038:                         my $spec = $trole.'.'.$extendedarea;
                   3039:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3040:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3041:                     }
                   3042:                 }
                   3043:             }
                   3044:         }
                   3045:     }
1.800     albertel 3046:     foreach my $group (keys(%grouproles)) {
                   3047:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3048:     }
1.800     albertel 3049:     foreach my $role (keys(%{$allroles})) {
                   3050:         my %thesepriv;
                   3051:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3052:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3053:             if ($item ne '') {
                   3054:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3055:                 if ($restrictions eq '') {
                   3056:                     $thesepriv{$privilege}='F';
                   3057:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3058:                     $thesepriv{$privilege}.=$restrictions;
                   3059:                 }
                   3060:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3061:             }
                   3062:         }
                   3063:         my $thesestr='';
1.800     albertel 3064:         foreach my $priv (keys(%thesepriv)) {
                   3065: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3066: 	}
                   3067:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3068:     }
                   3069:     return ($author,$adv);
                   3070: }
                   3071: 
1.12      www      3072: # --------------------------------------------------------------- get interface
                   3073: 
                   3074: sub get {
1.131     albertel 3075:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3076:    my $items='';
1.800     albertel 3077:    foreach my $item (@$storearr) {
                   3078:        $items.=&escape($item).'&';
1.191     harris41 3079:    }
1.12      www      3080:    $items=~s/\&$//;
1.620     albertel 3081:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3082:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3083:    my $uhome=&homeserver($uname,$udomain);
                   3084: 
1.133     albertel 3085:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3086:    my @pairs=split(/\&/,$rep);
1.273     albertel 3087:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3088:      return @pairs;
                   3089:    }
1.15      www      3090:    my %returnhash=();
1.42      www      3091:    my $i=0;
1.800     albertel 3092:    foreach my $item (@$storearr) {
                   3093:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3094:       $i++;
1.191     harris41 3095:    }
1.15      www      3096:    return %returnhash;
1.27      www      3097: }
                   3098: 
                   3099: # --------------------------------------------------------------- del interface
                   3100: 
                   3101: sub del {
1.133     albertel 3102:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3103:    my $items='';
1.800     albertel 3104:    foreach my $item (@$storearr) {
                   3105:        $items.=&escape($item).'&';
1.191     harris41 3106:    }
1.27      www      3107:    $items=~s/\&$//;
1.620     albertel 3108:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3109:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3110:    my $uhome=&homeserver($uname,$udomain);
                   3111: 
                   3112:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3113: }
                   3114: 
                   3115: # -------------------------------------------------------------- dump interface
                   3116: 
                   3117: sub dump {
1.755     albertel 3118:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3119:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3120:     if (!$uname) { $uname=$env{'user.name'}; }
                   3121:     my $uhome=&homeserver($uname,$udomain);
                   3122:     if ($regexp) {
                   3123: 	$regexp=&escape($regexp);
                   3124:     } else {
                   3125: 	$regexp='.';
                   3126:     }
                   3127:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3128:     my @pairs=split(/\&/,$rep);
                   3129:     my %returnhash=();
                   3130:     foreach my $item (@pairs) {
                   3131: 	my ($key,$value)=split(/=/,$item,2);
                   3132: 	$key = &unescape($key);
                   3133: 	next if ($key =~ /^error: 2 /);
                   3134: 	$returnhash{$key}=&thaw_unescape($value);
                   3135:     }
                   3136:     return %returnhash;
1.407     www      3137: }
                   3138: 
1.717     albertel 3139: # --------------------------------------------------------- dumpstore interface
                   3140: 
                   3141: sub dumpstore {
                   3142:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3143:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3144:    if (!$uname) { $uname=$env{'user.name'}; }
                   3145:    my $uhome=&homeserver($uname,$udomain);
                   3146:    if ($regexp) {
                   3147:        $regexp=&escape($regexp);
                   3148:    } else {
                   3149:        $regexp='.';
                   3150:    }
                   3151:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3152:    my @pairs=split(/\&/,$rep);
                   3153:    my %returnhash=();
                   3154:    foreach my $item (@pairs) {
                   3155:        my ($key,$value)=split(/=/,$item,2);
                   3156:        next if ($key =~ /^error: 2 /);
                   3157:        $returnhash{$key}=&thaw_unescape($value);
                   3158:    }
                   3159:    return %returnhash;
1.717     albertel 3160: }
                   3161: 
1.407     www      3162: # -------------------------------------------------------------- keys interface
                   3163: 
                   3164: sub getkeys {
                   3165:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3166:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3167:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3168:    my $uhome=&homeserver($uname,$udomain);
                   3169:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3170:    my @keyarray=();
1.800     albertel 3171:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3172:       next if ($key =~ /^error: 2 /);
1.800     albertel 3173:       push(@keyarray,&unescape($key));
1.407     www      3174:    }
                   3175:    return @keyarray;
1.318     matthew  3176: }
                   3177: 
1.319     matthew  3178: # --------------------------------------------------------------- currentdump
                   3179: sub currentdump {
1.328     matthew  3180:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3181:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3182:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3183:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3184:    my $uhome = &homeserver($sname,$sdom);
                   3185:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3186:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3187:    #
1.318     matthew  3188:    my %returnhash=();
1.319     matthew  3189:    #
                   3190:    if ($rep eq "unknown_cmd") { 
                   3191:        # an old lond will not know currentdump
                   3192:        # Do a dump and make it look like a currentdump
1.822     albertel 3193:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3194:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3195:        my %hash = @tmp;
                   3196:        @tmp=();
1.424     matthew  3197:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3198:    } else {
                   3199:        my @pairs=split(/\&/,$rep);
1.800     albertel 3200:        foreach my $pair (@pairs) {
                   3201:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3202:            my ($symb,$param) = split(/:/,$key);
                   3203:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3204:                                                         &thaw_unescape($value);
1.319     matthew  3205:        }
1.191     harris41 3206:    }
1.12      www      3207:    return %returnhash;
1.424     matthew  3208: }
                   3209: 
                   3210: sub convert_dump_to_currentdump{
                   3211:     my %hash = %{shift()};
                   3212:     my %returnhash;
                   3213:     # Code ripped from lond, essentially.  The only difference
                   3214:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3215:     # we might run in to problems with parameter names =~ /^v\./
                   3216:     while (my ($key,$value) = each(%hash)) {
                   3217:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3218: 	$symb  = &unescape($symb);
                   3219: 	$param = &unescape($param);
1.424     matthew  3220:         next if ($v eq 'version' || $symb eq 'keys');
                   3221:         next if (exists($returnhash{$symb}) &&
                   3222:                  exists($returnhash{$symb}->{$param}) &&
                   3223:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3224:         $returnhash{$symb}->{$param}=$value;
                   3225:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3226:     }
                   3227:     #
                   3228:     # Remove all of the keys in the hashes which keep track of
                   3229:     # the version of the parameter.
                   3230:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3231:         # use a foreach because we are going to delete from the hash.
                   3232:         foreach my $key (keys(%$param_hash)) {
                   3233:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3234:         }
                   3235:     }
                   3236:     return \%returnhash;
1.12      www      3237: }
                   3238: 
1.627     albertel 3239: # ------------------------------------------------------ critical inc interface
                   3240: 
                   3241: sub cinc {
                   3242:     return &inc(@_,'critical');
                   3243: }
                   3244: 
1.449     matthew  3245: # --------------------------------------------------------------- inc interface
                   3246: 
                   3247: sub inc {
1.627     albertel 3248:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3249:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3250:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3251:     my $uhome=&homeserver($uname,$udomain);
                   3252:     my $items='';
                   3253:     if (! ref($store)) {
                   3254:         # got a single value, so use that instead
                   3255:         $items = &escape($store).'=&';
                   3256:     } elsif (ref($store) eq 'SCALAR') {
                   3257:         $items = &escape($$store).'=&';        
                   3258:     } elsif (ref($store) eq 'ARRAY') {
                   3259:         $items = join('=&',map {&escape($_);} @{$store});
                   3260:     } elsif (ref($store) eq 'HASH') {
                   3261:         while (my($key,$value) = each(%{$store})) {
                   3262:             $items.= &escape($key).'='.&escape($value).'&';
                   3263:         }
                   3264:     }
                   3265:     $items=~s/\&$//;
1.627     albertel 3266:     if ($critical) {
                   3267: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3268:     } else {
                   3269: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3270:     }
1.449     matthew  3271: }
                   3272: 
1.12      www      3273: # --------------------------------------------------------------- put interface
                   3274: 
                   3275: sub put {
1.134     albertel 3276:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3277:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3278:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3279:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3280:    my $items='';
1.800     albertel 3281:    foreach my $item (keys(%$storehash)) {
                   3282:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3283:    }
1.12      www      3284:    $items=~s/\&$//;
1.134     albertel 3285:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3286: }
                   3287: 
1.631     albertel 3288: # ------------------------------------------------------------ newput interface
                   3289: 
                   3290: sub newput {
                   3291:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3292:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3293:    if (!$uname) { $uname=$env{'user.name'}; }
                   3294:    my $uhome=&homeserver($uname,$udomain);
                   3295:    my $items='';
                   3296:    foreach my $key (keys(%$storehash)) {
                   3297:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3298:    }
                   3299:    $items=~s/\&$//;
                   3300:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3301: }
                   3302: 
                   3303: # ---------------------------------------------------------  putstore interface
                   3304: 
1.524     raeburn  3305: sub putstore {
1.715     albertel 3306:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3307:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3308:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3309:    my $uhome=&homeserver($uname,$udomain);
                   3310:    my $items='';
1.715     albertel 3311:    foreach my $key (keys(%$storehash)) {
                   3312:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3313:    }
1.715     albertel 3314:    $items=~s/\&$//;
1.716     albertel 3315:    my $esc_symb=&escape($symb);
                   3316:    my $esc_v=&escape($version);
1.715     albertel 3317:    my $reply =
1.716     albertel 3318:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3319: 	      $uhome);
                   3320:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3321:        # gfall back to way things use to be done
1.715     albertel 3322:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3323: 			    $uname);
1.524     raeburn  3324:    }
1.715     albertel 3325:    return $reply;
                   3326: }
                   3327: 
                   3328: sub old_putstore {
1.716     albertel 3329:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3330:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3331:     if (!$uname) { $uname=$env{'user.name'}; }
                   3332:     my $uhome=&homeserver($uname,$udomain);
                   3333:     my %newstorehash;
1.800     albertel 3334:     foreach my $item (keys(%$storehash)) {
                   3335: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3336: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3337:     }
                   3338:     my $items='';
                   3339:     my %allitems = ();
1.800     albertel 3340:     foreach my $item (keys(%newstorehash)) {
                   3341: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3342: 	    my $key = $1.':keys:'.$2;
                   3343: 	    $allitems{$key} .= $3.':';
                   3344: 	}
1.800     albertel 3345: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3346:     }
1.800     albertel 3347:     foreach my $item (keys(%allitems)) {
                   3348: 	$allitems{$item} =~ s/\:$//;
                   3349: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3350:     }
                   3351:     $items=~s/\&$//;
                   3352:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3353: }
                   3354: 
1.47      www      3355: # ------------------------------------------------------ critical put interface
                   3356: 
                   3357: sub cput {
1.134     albertel 3358:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3359:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3360:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3361:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3362:    my $items='';
1.800     albertel 3363:    foreach my $item (keys(%$storehash)) {
                   3364:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3365:    }
1.47      www      3366:    $items=~s/\&$//;
1.134     albertel 3367:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3368: }
                   3369: 
                   3370: # -------------------------------------------------------------- eget interface
                   3371: 
                   3372: sub eget {
1.133     albertel 3373:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3374:    my $items='';
1.800     albertel 3375:    foreach my $item (@$storearr) {
                   3376:        $items.=&escape($item).'&';
1.191     harris41 3377:    }
1.12      www      3378:    $items=~s/\&$//;
1.620     albertel 3379:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3380:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3381:    my $uhome=&homeserver($uname,$udomain);
                   3382:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3383:    my @pairs=split(/\&/,$rep);
                   3384:    my %returnhash=();
1.42      www      3385:    my $i=0;
1.800     albertel 3386:    foreach my $item (@$storearr) {
                   3387:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3388:       $i++;
1.191     harris41 3389:    }
1.12      www      3390:    return %returnhash;
                   3391: }
                   3392: 
1.667     albertel 3393: # ------------------------------------------------------------ tmpput interface
                   3394: sub tmpput {
1.802     raeburn  3395:     my ($storehash,$server,$context)=@_;
1.667     albertel 3396:     my $items='';
1.800     albertel 3397:     foreach my $item (keys(%$storehash)) {
                   3398: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3399:     }
                   3400:     $items=~s/\&$//;
1.802     raeburn  3401:     if (defined($context)) {
                   3402:         $items .= ':'.&escape($context);
                   3403:     }
1.667     albertel 3404:     return &reply("tmpput:$items",$server);
                   3405: }
                   3406: 
                   3407: # ------------------------------------------------------------ tmpget interface
                   3408: sub tmpget {
1.688     albertel 3409:     my ($token,$server)=@_;
                   3410:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3411:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3412:     my %returnhash;
                   3413:     foreach my $item (split(/\&/,$rep)) {
                   3414: 	my ($key,$value)=split(/=/,$item);
                   3415: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3416:     }
                   3417:     return %returnhash;
                   3418: }
                   3419: 
1.688     albertel 3420: # ------------------------------------------------------------ tmpget interface
                   3421: sub tmpdel {
                   3422:     my ($token,$server)=@_;
                   3423:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3424:     return &reply("tmpdel:$token",$server);
                   3425: }
                   3426: 
1.765     albertel 3427: # -------------------------------------------------- portfolio access checking
                   3428: 
                   3429: sub portfolio_access {
1.766     albertel 3430:     my ($requrl) = @_;
1.765     albertel 3431:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3432:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3433:     if ($result) {
                   3434:         my %setters;
                   3435:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3436:             my ($startblock,$endblock) =
                   3437:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3438:             if ($startblock && $endblock) {
                   3439:                 return 'B';
                   3440:             }
                   3441:         } else {
                   3442:             my ($startblock,$endblock) =
                   3443:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3444:             if ($startblock && $endblock) {
                   3445:                 return 'B';
                   3446:             }
                   3447:         }
                   3448:     }
1.765     albertel 3449:     if ($result eq 'ok') {
1.766     albertel 3450:        return 'F';
1.765     albertel 3451:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3452:        return 'A';
1.765     albertel 3453:     }
1.766     albertel 3454:     return '';
1.765     albertel 3455: }
                   3456: 
                   3457: sub get_portfolio_access {
1.767     albertel 3458:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3459: 
                   3460:     if (!ref($access_hash)) {
                   3461: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3462: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3463: 						   $file_name);
                   3464: 	$access_hash = $access_controls{$file_name};
                   3465:     }
                   3466: 
1.765     albertel 3467:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3468:     my $now = time;
                   3469:     if (ref($access_hash) eq 'HASH') {
                   3470:         foreach my $key (keys(%{$access_hash})) {
                   3471:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3472:             if ($start > $now) {
                   3473:                 next;
                   3474:             }
                   3475:             if ($end && $end<$now) {
                   3476:                 next;
                   3477:             }
                   3478:             if ($scope eq 'public') {
                   3479:                 $public = $key;
                   3480:                 last;
                   3481:             } elsif ($scope eq 'guest') {
                   3482:                 $guest = $key;
                   3483:             } elsif ($scope eq 'domains') {
                   3484:                 push(@domains,$key);
                   3485:             } elsif ($scope eq 'users') {
                   3486:                 push(@users,$key);
                   3487:             } elsif ($scope eq 'course') {
                   3488:                 push(@courses,$key);
                   3489:             } elsif ($scope eq 'group') {
                   3490:                 push(@groups,$key);
                   3491:             }
                   3492:         }
                   3493:         if ($public) {
                   3494:             return 'ok';
                   3495:         }
                   3496:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3497:             if ($guest) {
                   3498:                 return $guest;
                   3499:             }
                   3500:         } else {
                   3501:             if (@domains > 0) {
                   3502:                 foreach my $domkey (@domains) {
                   3503:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3504:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3505:                             return 'ok';
                   3506:                         }
                   3507:                     }
                   3508:                 }
                   3509:             }
                   3510:             if (@users > 0) {
                   3511:                 foreach my $userkey (@users) {
                   3512:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3513:                         return 'ok';
                   3514:                     }
                   3515:                 }
                   3516:             }
                   3517:             my %roleshash;
                   3518:             my @courses_and_groups = @courses;
                   3519:             push(@courses_and_groups,@groups); 
                   3520:             if (@courses_and_groups > 0) {
                   3521:                 my (%allgroups,%allroles); 
                   3522:                 my ($start,$end,$role,$sec,$group);
                   3523:                 foreach my $envkey (%env) {
1.811     albertel 3524:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3525:                         my $cid = $2.'_'.$3; 
                   3526:                         if ($1 eq 'gr') {
                   3527:                             $group = $4;
                   3528:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3529:                         } else {
                   3530:                             if ($4 eq '') {
                   3531:                                 $sec = 'none';
                   3532:                             } else {
                   3533:                                 $sec = $4;
                   3534:                             }
                   3535:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3536:                         }
1.811     albertel 3537:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3538:                         my $cid = $2.'_'.$3;
                   3539:                         if ($4 eq '') {
                   3540:                             $sec = 'none';
                   3541:                         } else {
                   3542:                             $sec = $4;
                   3543:                         }
                   3544:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3545:                     }
                   3546:                 }
                   3547:                 if (keys(%allroles) == 0) {
                   3548:                     return;
                   3549:                 }
                   3550:                 foreach my $key (@courses_and_groups) {
                   3551:                     my %content = %{$$access_hash{$key}};
                   3552:                     my $cnum = $content{'number'};
                   3553:                     my $cdom = $content{'domain'};
                   3554:                     my $cid = $cdom.'_'.$cnum;
                   3555:                     if (!exists($allroles{$cid})) {
                   3556:                         next;
                   3557:                     }    
                   3558:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3559:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3560:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3561:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3562:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3563:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3564:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3565:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3566:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3567:                                         if (grep/^all$/,@sections) {
                   3568:                                             return 'ok';
                   3569:                                         } else {
                   3570:                                             if (grep/^$sec$/,@sections) {
                   3571:                                                 return 'ok';
                   3572:                                             }
                   3573:                                         }
                   3574:                                     }
                   3575:                                 }
                   3576:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3577:                                     if (grep/^none$/,@groups) {
                   3578:                                         return 'ok';
                   3579:                                     }
                   3580:                                 } else {
                   3581:                                     if (grep/^all$/,@groups) {
                   3582:                                         return 'ok';
                   3583:                                     } 
                   3584:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3585:                                         if (grep/^$group$/,@groups) {
                   3586:                                             return 'ok';
                   3587:                                         }
                   3588:                                     }
                   3589:                                 } 
                   3590:                             }
                   3591:                         }
                   3592:                     }
                   3593:                 }
                   3594:             }
                   3595:             if ($guest) {
                   3596:                 return $guest;
                   3597:             }
                   3598:         }
                   3599:     }
                   3600:     return;
                   3601: }
                   3602: 
                   3603: sub course_group_datechecker {
                   3604:     my ($dates,$now,$status) = @_;
                   3605:     my ($start,$end) = split(/\./,$dates);
                   3606:     if (!$start && !$end) {
                   3607:         return 'ok';
                   3608:     }
                   3609:     if (grep/^active$/,@{$status}) {
                   3610:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3611:             return 'ok';
                   3612:         }
                   3613:     }
                   3614:     if (grep/^previous$/,@{$status}) {
                   3615:         if ($end > $now ) {
                   3616:             return 'ok';
                   3617:         }
                   3618:     }
                   3619:     if (grep/^future$/,@{$status}) {
                   3620:         if ($start > $now) {
                   3621:             return 'ok';
                   3622:         }
                   3623:     }
                   3624:     return; 
                   3625: }
                   3626: 
                   3627: sub parse_portfolio_url {
                   3628:     my ($url) = @_;
                   3629: 
                   3630:     my ($type,$udom,$unum,$group,$file_name);
                   3631:     
1.823     albertel 3632:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3633: 	$type = 1;
                   3634:         $udom = $1;
                   3635:         $unum = $2;
                   3636:         $file_name = $3;
1.823     albertel 3637:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3638: 	$type = 2;
                   3639:         $udom = $1;
                   3640:         $unum = $2;
                   3641:         $group = $3;
                   3642:         $file_name = $3.'/'.$4;
                   3643:     }
                   3644:     if (wantarray) {
                   3645: 	return ($type,$udom,$unum,$file_name,$group);
                   3646:     }
                   3647:     return $type;
                   3648: }
                   3649: 
                   3650: sub is_portfolio_url {
                   3651:     my ($url) = @_;
                   3652:     return scalar(&parse_portfolio_url($url));
                   3653: }
                   3654: 
1.798     raeburn  3655: sub is_portfolio_file {
                   3656:     my ($file) = @_;
1.820     raeburn  3657:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3658:         return 1;
                   3659:     }
                   3660:     return;
                   3661: }
                   3662: 
                   3663: 
1.341     www      3664: # ---------------------------------------------- Custom access rule evaluation
                   3665: 
                   3666: sub customaccess {
                   3667:     my ($priv,$uri)=@_;
1.807     albertel 3668:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3669:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3670:     $udom = &LONCAPA::clean_domain($udom);
                   3671:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3672:     my $access=0;
1.800     albertel 3673:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3674: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3675:         if ($role) {
                   3676: 	   if ($role ne $urole) { next; }
                   3677:         }
1.800     albertel 3678:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3679:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3680:             if ($tdom) {
                   3681: 		if ($tdom ne $udom) { next; }
                   3682:             }
                   3683:             if ($tcrs) {
                   3684: 		if ($tcrs ne $ucrs) { next; }
                   3685:             }
                   3686:             if ($tsec) {
                   3687: 		if ($tsec ne $usec) { next; }
                   3688:             }
                   3689:             $access=($effect eq 'allow');
                   3690:             last;
1.342     www      3691:         }
1.402     bowersj2 3692: 	if ($realm eq '' && $role eq '') {
                   3693:             $access=($effect eq 'allow');
                   3694: 	}
1.341     www      3695:     }
                   3696:     return $access;
                   3697: }
                   3698: 
1.103     harris41 3699: # ------------------------------------------------- Check for a user privilege
1.12      www      3700: 
                   3701: sub allowed {
1.810     raeburn  3702:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3703:     my $ver_orguri=$uri;
1.439     www      3704:     $uri=&deversion($uri);
1.152     www      3705:     my $orguri=$uri;
1.52      www      3706:     $uri=&declutter($uri);
1.809     raeburn  3707: 
1.810     raeburn  3708:     if ($priv eq 'evb') {
                   3709: # Evade communication block restrictions for specified role in a course
                   3710:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3711:             return $1;
                   3712:         } else {
                   3713:             return;
                   3714:         }
                   3715:     }
                   3716: 
1.620     albertel 3717:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3718: # Free bre access to adm and meta resources
1.775     albertel 3719:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3720: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3721: 	&& ($priv eq 'bre')) {
1.14      www      3722: 	return 'F';
1.159     www      3723:     }
                   3724: 
1.545     banghart 3725: # Free bre access to user's own portfolio contents
1.714     raeburn  3726:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3727:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3728: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3729:         my %setters;
                   3730:         my ($startblock,$endblock) = 
                   3731:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3732:         if ($startblock && $endblock) {
                   3733:             return 'B';
                   3734:         } else {
                   3735:             return 'F';
                   3736:         }
1.545     banghart 3737:     }
                   3738: 
1.762     raeburn  3739: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3740:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3741:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3742:         if (exists($env{'request.course.id'})) {
                   3743:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3744:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3745:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3746:                 my $courseprivid=$env{'request.course.id'};
                   3747:                 $courseprivid=~s/\_/\//;
                   3748:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3749:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3750:                     return $1; 
1.762     raeburn  3751:                 } else {
                   3752:                     if ($env{'request.course.sec'}) {
                   3753:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3754:                     }
                   3755:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3756:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3757:                         return $2;
                   3758:                     }
1.714     raeburn  3759:                 }
                   3760:             }
                   3761:         }
                   3762:     }
                   3763: 
1.159     www      3764: # Free bre to public access
                   3765: 
                   3766:     if ($priv eq 'bre') {
1.238     www      3767:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3768: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3769:            return 'F'; 
                   3770:         }
1.238     www      3771:         if ($copyright eq 'priv') {
                   3772:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3773: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3774: 		return '';
                   3775:             }
                   3776:         }
                   3777:         if ($copyright eq 'domain') {
                   3778:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3779: 	    unless (($env{'user.domain'} eq $1) ||
                   3780:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3781: 		return '';
                   3782:             }
1.262     matthew  3783:         }
1.620     albertel 3784:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3785:             # Library role, so allow browsing of resources in this domain.
                   3786:             return 'F';
1.238     www      3787:         }
1.341     www      3788:         if ($copyright eq 'custom') {
                   3789: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3790:         }
1.14      www      3791:     }
1.264     matthew  3792:     # Domain coordinator is trying to create a course
1.620     albertel 3793:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3794:         # uri is the requested domain in this case.
                   3795:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3796:         # a role of dc for the domain in question.
1.620     albertel 3797:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3798:     }
1.29      www      3799: 
1.52      www      3800:     my $thisallowed='';
                   3801:     my $statecond=0;
                   3802:     my $courseprivid='';
                   3803: 
                   3804: # Course
                   3805: 
1.620     albertel 3806:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3807:        $thisallowed.=$1;
                   3808:     }
1.29      www      3809: 
1.52      www      3810: # Domain
                   3811: 
1.620     albertel 3812:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3813:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3814:        $thisallowed.=$1;
                   3815:     }
1.52      www      3816: 
                   3817: # Course: uri itself is a course
1.66      www      3818:     my $courseuri=$uri;
                   3819:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3820:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3821: 
1.620     albertel 3822:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3823:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3824:        $thisallowed.=$1;
                   3825:     }
1.29      www      3826: 
1.665     albertel 3827: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3828: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3829:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3830: 	$thisallowed='';
1.671     raeburn  3831:         my ($match)=&is_on_map($uri);
                   3832:         if ($match) {
                   3833:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3834:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3835:                 $thisallowed.=$1;
                   3836:             }
                   3837:         } else {
1.705     albertel 3838:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3839:             if ($refuri) {
                   3840:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3841:                     $thisallowed='F';
1.671     raeburn  3842:                 } else {
                   3843:                     $refuri=&declutter($refuri);
                   3844:                     my ($match) = &is_on_map($refuri);
                   3845:                     if ($match) {
                   3846:                         $thisallowed='F';
                   3847:                     }
1.669     raeburn  3848:                 }
1.671     raeburn  3849:             }
                   3850:         }
1.314     www      3851:     }
1.492     albertel 3852: 
1.766     albertel 3853:     if ($priv eq 'bre'
                   3854: 	&& $thisallowed ne 'F' 
                   3855: 	&& $thisallowed ne '2'
                   3856: 	&& &is_portfolio_url($uri)) {
                   3857: 	$thisallowed = &portfolio_access($uri);
                   3858:     }
                   3859:     
1.52      www      3860: # Full access at system, domain or course-wide level? Exit.
1.29      www      3861: 
                   3862:     if ($thisallowed=~/F/) {
                   3863: 	return 'F';
                   3864:     }
                   3865: 
1.52      www      3866: # If this is generating or modifying users, exit with special codes
1.29      www      3867: 
1.643     www      3868:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3869: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3870: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3871: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3872: 	    unless ($auname) { return $thisallowed; }
                   3873: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3874: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3875: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3876: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3877: 	}
1.52      www      3878: 	return $thisallowed;
                   3879:     }
                   3880: #
1.103     harris41 3881: # Gathered so far: system, domain and course wide privileges
1.52      www      3882: #
                   3883: # Course: See if uri or referer is an individual resource that is part of 
                   3884: # the course
                   3885: 
1.620     albertel 3886:     if ($env{'request.course.id'}) {
1.232     www      3887: 
1.620     albertel 3888:        $courseprivid=$env{'request.course.id'};
                   3889:        if ($env{'request.course.sec'}) {
                   3890:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3891:        }
                   3892:        $courseprivid=~s/\_/\//;
                   3893:        my $checkreferer=1;
1.232     www      3894:        my ($match,$cond)=&is_on_map($uri);
                   3895:        if ($match) {
                   3896:            $statecond=$cond;
1.620     albertel 3897:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3898:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3899:                $thisallowed.=$1;
                   3900:                $checkreferer=0;
                   3901:            }
1.29      www      3902:        }
1.83      www      3903:        
1.148     www      3904:        if ($checkreferer) {
1.620     albertel 3905: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3906:             unless ($refuri) {
1.800     albertel 3907:                 foreach my $key (keys(%env)) {
                   3908: 		    if ($key=~/^httpref\..*\*/) {
                   3909: 			my $pattern=$key;
1.156     www      3910:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3911:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3912:                         $pattern=~s/\//\\\//g;
1.152     www      3913:                         if ($orguri=~/$pattern/) {
1.800     albertel 3914: 			    $refuri=$env{$key};
1.148     www      3915:                         }
                   3916:                     }
1.191     harris41 3917:                 }
1.148     www      3918:             }
1.232     www      3919: 
1.148     www      3920:          if ($refuri) { 
1.152     www      3921: 	  $refuri=&declutter($refuri);
1.232     www      3922:           my ($match,$cond)=&is_on_map($refuri);
                   3923:             if ($match) {
                   3924:               my $refstatecond=$cond;
1.620     albertel 3925:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3926:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3927:                   $thisallowed.=$1;
1.53      www      3928:                   $uri=$refuri;
                   3929:                   $statecond=$refstatecond;
1.52      www      3930:               }
                   3931:           }
1.148     www      3932:         }
1.29      www      3933:        }
1.52      www      3934:    }
1.29      www      3935: 
1.52      www      3936: #
1.103     harris41 3937: # Gathered now: all privileges that could apply, and condition number
1.52      www      3938: # 
                   3939: #
                   3940: # Full or no access?
                   3941: #
1.29      www      3942: 
1.52      www      3943:     if ($thisallowed=~/F/) {
                   3944: 	return 'F';
                   3945:     }
1.29      www      3946: 
1.52      www      3947:     unless ($thisallowed) {
                   3948:         return '';
                   3949:     }
1.29      www      3950: 
1.52      www      3951: # Restrictions exist, deal with them
                   3952: #
                   3953: #   C:according to course preferences
                   3954: #   R:according to resource settings
                   3955: #   L:unless locked
                   3956: #   X:according to user session state
                   3957: #
                   3958: 
                   3959: # Possibly locked functionality, check all courses
1.54      www      3960: # Locks might take effect only after 10 minutes cache expiration for other
                   3961: # courses, and 2 minutes for current course
1.52      www      3962: 
                   3963:     my $envkey;
                   3964:     if ($thisallowed=~/L/) {
1.620     albertel 3965:         foreach $envkey (keys %env) {
1.54      www      3966:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3967:                my $courseid=$2;
                   3968:                my $roleid=$1.'.'.$2;
1.92      www      3969:                $courseid=~s/^\///;
1.54      www      3970:                my $expiretime=600;
1.620     albertel 3971:                if ($env{'request.role'} eq $roleid) {
1.54      www      3972: 		  $expiretime=120;
                   3973:                }
                   3974: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3975:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3976:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3977: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3978:                }
1.620     albertel 3979:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3980:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3981: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3982:                        &log($env{'user.domain'},$env{'user.name'},
                   3983:                             $env{'user.home'},
1.57      www      3984:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3985:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3986:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3987: 		       return '';
                   3988:                    }
                   3989:                }
1.620     albertel 3990:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3991:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3992: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3993:                        &log($env{'user.domain'},$env{'user.name'},
                   3994:                             $env{'user.home'},
1.57      www      3995:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3996:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3997:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3998: 		       return '';
                   3999:                    }
                   4000:                }
                   4001: 	   }
1.29      www      4002:        }
1.52      www      4003:     }
                   4004:    
                   4005: #
                   4006: # Rest of the restrictions depend on selected course
                   4007: #
                   4008: 
1.620     albertel 4009:     unless ($env{'request.course.id'}) {
1.766     albertel 4010: 	if ($thisallowed eq 'A') {
                   4011: 	    return 'A';
1.814     raeburn  4012:         } elsif ($thisallowed eq 'B') {
                   4013:             return 'B';
1.766     albertel 4014: 	} else {
                   4015: 	    return '1';
                   4016: 	}
1.52      www      4017:     }
1.29      www      4018: 
1.52      www      4019: #
                   4020: # Now user is definitely in a course
                   4021: #
1.53      www      4022: 
                   4023: 
                   4024: # Course preferences
                   4025: 
                   4026:    if ($thisallowed=~/C/) {
1.620     albertel 4027:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4028:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4029:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4030: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4031: 	   if ($priv ne 'pch') { 
                   4032: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4033: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4034: 			$env{'request.course.id'});
                   4035: 	   }
1.237     www      4036:            return '';
                   4037:        }
                   4038: 
1.620     albertel 4039:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4040: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4041: 	   if ($priv ne 'pch') { 
                   4042: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4043: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4044: 			$env{'request.course.id'});
                   4045: 	   }
1.54      www      4046:            return '';
                   4047:        }
1.53      www      4048:    }
                   4049: 
                   4050: # Resource preferences
                   4051: 
                   4052:    if ($thisallowed=~/R/) {
1.620     albertel 4053:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4054:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4055: 	   if ($priv ne 'pch') { 
                   4056: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4057: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4058: 	   }
                   4059: 	   return '';
1.54      www      4060:        }
1.53      www      4061:    }
1.30      www      4062: 
1.246     www      4063: # Restricted by state or randomout?
1.30      www      4064: 
1.52      www      4065:    if ($thisallowed=~/X/) {
1.620     albertel 4066:       if ($env{'acc.randomout'}) {
1.579     albertel 4067: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4068:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4069:             return ''; 
                   4070:          }
1.247     www      4071:       }
                   4072:       if (&condval($statecond)) {
1.52      www      4073: 	 return '2';
                   4074:       } else {
                   4075:          return '';
                   4076:       }
                   4077:    }
1.30      www      4078: 
1.766     albertel 4079:     if ($thisallowed eq 'A') {
                   4080: 	return 'A';
1.814     raeburn  4081:     } elsif ($thisallowed eq 'B') {
                   4082:         return 'B';
1.766     albertel 4083:     }
1.52      www      4084:    return 'F';
1.232     www      4085: }
                   4086: 
1.710     albertel 4087: sub split_uri_for_cond {
                   4088:     my $uri=&deversion(&declutter(shift));
                   4089:     my @uriparts=split(/\//,$uri);
                   4090:     my $filename=pop(@uriparts);
                   4091:     my $pathname=join('/',@uriparts);
                   4092:     return ($pathname,$filename);
                   4093: }
1.232     www      4094: # --------------------------------------------------- Is a resource on the map?
                   4095: 
                   4096: sub is_on_map {
1.710     albertel 4097:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4098:     #Trying to find the conditional for the file
1.620     albertel 4099:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4100: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4101:     if ($match) {
1.289     bowersj2 4102: 	return (1,$1);
                   4103:     } else {
1.434     www      4104: 	return (0,0);
1.289     bowersj2 4105:     }
1.12      www      4106: }
                   4107: 
1.427     www      4108: # --------------------------------------------------------- Get symb from alias
                   4109: 
                   4110: sub get_symb_from_alias {
                   4111:     my $symb=shift;
                   4112:     my ($map,$resid,$url)=&decode_symb($symb);
                   4113: # Already is a symb
                   4114:     if ($url) { return $symb; }
                   4115: # Must be an alias
                   4116:     my $aliassymb='';
                   4117:     my %bighash;
1.620     albertel 4118:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4119:                             &GDBM_READER(),0640)) {
                   4120:         my $rid=$bighash{'mapalias_'.$symb};
                   4121: 	if ($rid) {
                   4122: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4123: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4124: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4125: 	}
                   4126:         untie %bighash;
                   4127:     }
                   4128:     return $aliassymb;
                   4129: }
                   4130: 
1.12      www      4131: # ----------------------------------------------------------------- Define Role
                   4132: 
                   4133: sub definerole {
                   4134:   if (allowed('mcr','/')) {
                   4135:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4136:     foreach my $role (split(':',$sysrole)) {
                   4137: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4138:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4139:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4140: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4141:                return "refused:s:$crole&$cqual"; 
                   4142:             }
                   4143:         }
1.191     harris41 4144:     }
1.800     albertel 4145:     foreach my $role (split(':',$domrole)) {
                   4146: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4147:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4148:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4149: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4150:                return "refused:d:$crole&$cqual"; 
                   4151:             }
                   4152:         }
1.191     harris41 4153:     }
1.800     albertel 4154:     foreach my $role (split(':',$courole)) {
                   4155: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4156:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4157:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4158: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4159:                return "refused:c:$crole&$cqual"; 
                   4160:             }
                   4161:         }
1.191     harris41 4162:     }
1.620     albertel 4163:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4164:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4165: 	        "rolesdef_$rolename=".
                   4166:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4167:     return reply($command,$env{'user.home'});
1.12      www      4168:   } else {
                   4169:     return 'refused';
                   4170:   }
1.105     harris41 4171: }
                   4172: 
                   4173: # ---------------- Make a metadata query against the network of library servers
                   4174: 
                   4175: sub metadata_query {
1.244     matthew  4176:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4177:     my %rhash;
1.845   ! albertel 4178:     my %libserv = &all_library();
1.244     matthew  4179:     my @server_list = (defined($server_array) ? @$server_array
                   4180:                                               : keys(%libserv) );
                   4181:     for my $server (@server_list) {
1.118     harris41 4182: 	unless ($custom or $customshow) {
                   4183: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4184: 	    $rhash{$server}=$reply;
                   4185: 	}
                   4186: 	else {
                   4187: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4188: 			     &escape($custom).':'.&escape($customshow),
                   4189: 			     $server);
                   4190: 	    $rhash{$server}=$reply;
                   4191: 	}
1.112     harris41 4192:     }
1.118     harris41 4193:     return \%rhash;
1.240     www      4194: }
                   4195: 
                   4196: # ----------------------------------------- Send log queries and wait for reply
                   4197: 
                   4198: sub log_query {
                   4199:     my ($uname,$udom,$query,%filters)=@_;
                   4200:     my $uhome=&homeserver($uname,$udom);
                   4201:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4202:     my $uhost=&hostname($uhome);
1.800     albertel 4203:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4204:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4205:                        $uhome);
1.479     albertel 4206:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4207:     return get_query_reply($queryid);
                   4208: }
                   4209: 
1.818     raeburn  4210: # -------------------------- Update MySQL table for portfolio file
                   4211: 
                   4212: sub update_portfolio_table {
1.821     raeburn  4213:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4214:     my $homeserver = &homeserver($uname,$udom);
                   4215:     my $queryid=
1.821     raeburn  4216:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4217:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4218:     my $reply = &get_query_reply($queryid);
                   4219:     return $reply;
                   4220: }
                   4221: 
1.508     raeburn  4222: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4223: 
                   4224: sub fetch_enrollment_query {
1.511     raeburn  4225:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4226:     my $homeserver;
1.547     raeburn  4227:     my $maxtries = 1;
1.508     raeburn  4228:     if ($context eq 'automated') {
                   4229:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4230:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4231:     } else {
                   4232:         $homeserver = &homeserver($cnum,$dom);
                   4233:     }
1.838     albertel 4234:     my $host=&hostname($homeserver);
1.506     raeburn  4235:     my $cmd = '';
1.800     albertel 4236:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4237:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4238:     }
                   4239:     $cmd =~ s/%%$//;
                   4240:     $cmd = &escape($cmd);
                   4241:     my $query = 'fetchenrollment';
1.620     albertel 4242:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4243:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4244:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4245:         return 'error: '.$queryid;
                   4246:     }
1.506     raeburn  4247:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4248:     my $tries = 1;
                   4249:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4250:         $reply = &get_query_reply($queryid);
                   4251:         $tries ++;
                   4252:     }
1.526     raeburn  4253:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4254:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4255:     } else {
1.515     raeburn  4256:         my @responses = split/:/,$reply;
                   4257:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4258:             foreach my $line (@responses) {
                   4259:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4260:                 $$replyref{$key} = $value;
                   4261:             }
                   4262:         } else {
1.506     raeburn  4263:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4264:             foreach my $line (@responses) {
                   4265:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4266:                 $$replyref{$key} = $value;
                   4267:                 if ($value > 0) {
1.800     albertel 4268:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4269:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4270:                         my $destname = $pathname.'/'.$filename;
                   4271:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4272:                         if ($xml_classlist =~ /^error/) {
                   4273:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4274:                         } else {
1.506     raeburn  4275:                             if ( open(FILE,">$destname") ) {
                   4276:                                 print FILE &unescape($xml_classlist);
                   4277:                                 close(FILE);
1.526     raeburn  4278:                             } else {
                   4279:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4280:                             }
                   4281:                         }
                   4282:                     }
                   4283:                 }
                   4284:             }
                   4285:         }
                   4286:         return 'ok';
                   4287:     }
                   4288:     return 'error';
                   4289: }
                   4290: 
1.242     www      4291: sub get_query_reply {
                   4292:     my $queryid=shift;
1.240     www      4293:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4294:     my $reply='';
                   4295:     for (1..100) {
                   4296: 	sleep 2;
                   4297:         if (-e $replyfile.'.end') {
1.448     albertel 4298: 	    if (open(my $fh,$replyfile)) {
1.240     www      4299:                $reply.=<$fh>;
1.448     albertel 4300:                close($fh);
1.240     www      4301: 	   } else { return 'error: reply_file_error'; }
1.242     www      4302:            return &unescape($reply);
                   4303: 	}
1.240     www      4304:     }
1.242     www      4305:     return 'timeout:'.$queryid;
1.240     www      4306: }
                   4307: 
                   4308: sub courselog_query {
1.241     www      4309: #
                   4310: # possible filters:
                   4311: # url: url or symb
                   4312: # username
                   4313: # domain
                   4314: # action: view, submit, grade
                   4315: # start: timestamp
                   4316: # end: timestamp
                   4317: #
1.240     www      4318:     my (%filters)=@_;
1.620     albertel 4319:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4320:     if ($filters{'url'}) {
                   4321: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4322:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4323:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4324:     }
1.620     albertel 4325:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4326:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4327:     return &log_query($cname,$cdom,'courselog',%filters);
                   4328: }
                   4329: 
                   4330: sub userlog_query {
                   4331:     my ($uname,$udom,%filters)=@_;
                   4332:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4333: }
                   4334: 
1.506     raeburn  4335: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4336: 
                   4337: sub auto_run {
1.508     raeburn  4338:     my ($cnum,$cdom) = @_;
                   4339:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4340:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4341:     return $response;
                   4342: }
1.776     albertel 4343: 
1.506     raeburn  4344: sub auto_get_sections {
1.508     raeburn  4345:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4346:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4347:     my @secs = ();
1.511     raeburn  4348:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4349:     unless ($response eq 'refused') {
                   4350:         @secs = split/:/,$response;
                   4351:     }
                   4352:     return @secs;
                   4353: }
1.776     albertel 4354: 
1.506     raeburn  4355: sub auto_new_course {
1.508     raeburn  4356:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4357:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4358:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4359:     return $response;
                   4360: }
1.776     albertel 4361: 
1.506     raeburn  4362: sub auto_validate_courseID {
1.508     raeburn  4363:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4364:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4365:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4366:     return $response;
                   4367: }
1.776     albertel 4368: 
1.506     raeburn  4369: sub auto_create_password {
1.508     raeburn  4370:     my ($cnum,$cdom,$authparam) = @_;
                   4371:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4372:     my $create_passwd = 0;
                   4373:     my $authchk = '';
1.511     raeburn  4374:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4375:     if ($response eq 'refused') {
                   4376:         $authchk = 'refused';
                   4377:     } else {
                   4378:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4379:     }
                   4380:     return ($authparam,$create_passwd,$authchk);
                   4381: }
                   4382: 
1.706     raeburn  4383: sub auto_photo_permission {
                   4384:     my ($cnum,$cdom,$students) = @_;
                   4385:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4386:     my ($outcome,$perm_reqd,$conditions) = 
                   4387: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4388:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4389: 	return (undef,undef);
                   4390:     }
1.706     raeburn  4391:     return ($outcome,$perm_reqd,$conditions);
                   4392: }
                   4393: 
                   4394: sub auto_checkphotos {
                   4395:     my ($uname,$udom,$pid) = @_;
                   4396:     my $homeserver = &homeserver($uname,$udom);
                   4397:     my ($result,$resulttype);
                   4398:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4399: 				   &escape($uname).':'.&escape($pid),
                   4400: 				   $homeserver));
1.709     albertel 4401:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4402: 	return (undef,undef);
                   4403:     }
1.706     raeburn  4404:     if ($outcome) {
                   4405:         ($result,$resulttype) = split(/:/,$outcome);
                   4406:     } 
                   4407:     return ($result,$resulttype);
                   4408: }
                   4409: 
                   4410: sub auto_photochoice {
                   4411:     my ($cnum,$cdom) = @_;
                   4412:     my $homeserver = &homeserver($cnum,$cdom);
                   4413:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4414: 						       &escape($cdom),
                   4415: 						       $homeserver)));
1.709     albertel 4416:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4417: 	return (undef,undef);
                   4418:     }
1.706     raeburn  4419:     return ($update,$comment);
                   4420: }
                   4421: 
                   4422: sub auto_photoupdate {
                   4423:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4424:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4425:     my $host=&hostname($homeserver);
1.706     raeburn  4426:     my $cmd = '';
                   4427:     my $maxtries = 1;
1.800     albertel 4428:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4429:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4430:     }
                   4431:     $cmd =~ s/%%$//;
                   4432:     $cmd = &escape($cmd);
                   4433:     my $query = 'institutionalphotos';
                   4434:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4435:     unless ($queryid=~/^\Q$host\E\_/) {
                   4436:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4437:         return 'error: '.$queryid;
                   4438:     }
                   4439:     my $reply = &get_query_reply($queryid);
                   4440:     my $tries = 1;
                   4441:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4442:         $reply = &get_query_reply($queryid);
                   4443:         $tries ++;
                   4444:     }
                   4445:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4446:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4447:     } else {
                   4448:         my @responses = split(/:/,$reply);
                   4449:         my $outcome = shift(@responses); 
                   4450:         foreach my $item (@responses) {
                   4451:             my ($key,$value) = split(/=/,$item);
                   4452:             $$photo{$key} = $value;
                   4453:         }
                   4454:         return $outcome;
                   4455:     }
                   4456:     return 'error';
                   4457: }
                   4458: 
1.521     raeburn  4459: sub auto_instcode_format {
1.793     albertel 4460:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4461: 	$cat_order) = @_;
1.521     raeburn  4462:     my $courses = '';
1.772     raeburn  4463:     my @homeservers;
1.521     raeburn  4464:     if ($caller eq 'global') {
1.841     albertel 4465: 	my %servers = &get_servers($codedom,'library');
                   4466: 	foreach my $tryserver (keys(%servers)) {
                   4467: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4468: 		push(@homeservers,$tryserver);
                   4469: 	    }
1.584     raeburn  4470:         }
1.521     raeburn  4471:     } else {
1.772     raeburn  4472:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4473:     }
1.793     albertel 4474:     foreach my $code (keys(%{$instcodes})) {
                   4475:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4476:     }
                   4477:     chop($courses);
1.772     raeburn  4478:     my $ok_response = 0;
                   4479:     my $response;
                   4480:     while (@homeservers > 0 && $ok_response == 0) {
                   4481:         my $server = shift(@homeservers); 
                   4482:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4483:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4484:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4485: 		split/:/,$response;
1.772     raeburn  4486:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4487:             push(@{$codetitles},&str2array($codetitles_str));
                   4488:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4489:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4490:             $ok_response = 1;
                   4491:         }
                   4492:     }
                   4493:     if ($ok_response) {
1.521     raeburn  4494:         return 'ok';
1.772     raeburn  4495:     } else {
                   4496:         return $response;
1.521     raeburn  4497:     }
                   4498: }
                   4499: 
1.792     raeburn  4500: sub auto_instcode_defaults {
                   4501:     my ($domain,$returnhash,$code_order) = @_;
                   4502:     my @homeservers;
1.841     albertel 4503: 
                   4504:     my %servers = &get_servers($domain,'library');
                   4505:     foreach my $tryserver (keys(%servers)) {
                   4506: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4507: 	    push(@homeservers,$tryserver);
                   4508: 	}
1.792     raeburn  4509:     }
1.841     albertel 4510: 
1.792     raeburn  4511:     my $response;
1.841     albertel 4512:     foreach my $server (@homeservers) {
1.792     raeburn  4513:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4514:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4515: 	
                   4516: 	foreach my $pair (split(/\&/,$response)) {
                   4517: 	    my ($name,$value)=split(/\=/,$pair);
                   4518: 	    if ($name eq 'code_order') {
                   4519: 		@{$code_order} = split(/\&/,&unescape($value));
                   4520: 	    } else {
                   4521: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4522: 	    }
                   4523: 	}
                   4524: 	return 'ok';
1.792     raeburn  4525:     }
1.841     albertel 4526: 
                   4527:     return $response;
1.792     raeburn  4528: } 
                   4529: 
1.777     albertel 4530: sub auto_validate_class_sec {
1.773     raeburn  4531:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4532:     my $homeserver = &homeserver($cnum,$cdom);
                   4533:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4534:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4535:     return $response;
                   4536: }
                   4537: 
1.679     raeburn  4538: # ------------------------------------------------------- Course Group routines
                   4539: 
                   4540: sub get_coursegroups {
1.809     raeburn  4541:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4542:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4543: }
                   4544: 
1.679     raeburn  4545: sub modify_coursegroup {
                   4546:     my ($cdom,$cnum,$groupsettings) = @_;
                   4547:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4548: }
                   4549: 
1.809     raeburn  4550: sub toggle_coursegroup_status {
                   4551:     my ($cdom,$cnum,$group,$action) = @_;
                   4552:     my ($from_namespace,$to_namespace);
                   4553:     if ($action eq 'delete') {
                   4554:         $from_namespace = 'coursegroups';
                   4555:         $to_namespace = 'deleted_groups';
                   4556:     } else {
                   4557:         $from_namespace = 'deleted_groups';
                   4558:         $to_namespace = 'coursegroups';
                   4559:     }
                   4560:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4561:     if (my $tmp = &error(%curr_group)) {
                   4562:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4563:         return ('read error',$tmp);
                   4564:     } else {
                   4565:         my %savedsettings = %curr_group; 
1.809     raeburn  4566:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4567:         my $deloutcome;
                   4568:         if ($result eq 'ok') {
1.809     raeburn  4569:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4570:         } else {
                   4571:             return ('write error',$result);
                   4572:         }
                   4573:         if ($deloutcome eq 'ok') {
                   4574:             return 'ok';
                   4575:         } else {
                   4576:             return ('delete error',$deloutcome);
                   4577:         }
                   4578:     }
                   4579: }
                   4580: 
1.679     raeburn  4581: sub modify_group_roles {
                   4582:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4583:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4584:     my $role = 'gr/'.&escape($userprivs);
                   4585:     my ($uname,$udom) = split(/:/,$user);
                   4586:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4587:     if ($result eq 'ok') {
                   4588:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4589:     }
1.679     raeburn  4590:     return $result;
                   4591: }
                   4592: 
                   4593: sub modify_coursegroup_membership {
                   4594:     my ($cdom,$cnum,$membership) = @_;
                   4595:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4596:     return $result;
                   4597: }
                   4598: 
1.682     raeburn  4599: sub get_active_groups {
                   4600:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4601:     my $now = time;
                   4602:     my %groups = ();
                   4603:     foreach my $key (keys(%env)) {
1.811     albertel 4604:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4605:             my ($start,$end) = split(/\./,$env{$key});
                   4606:             if (($end!=0) && ($end<$now)) { next; }
                   4607:             if (($start!=0) && ($start>$now)) { next; }
                   4608:             if ($1 eq $cdom && $2 eq $cnum) {
                   4609:                 $groups{$3} = $env{$key} ;
                   4610:             }
                   4611:         }
                   4612:     }
                   4613:     return %groups;
                   4614: }
                   4615: 
1.683     raeburn  4616: sub get_group_membership {
                   4617:     my ($cdom,$cnum,$group) = @_;
                   4618:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4619: }
                   4620: 
                   4621: sub get_users_groups {
                   4622:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4623:     my @usersgroups;
1.683     raeburn  4624:     my $cachetime=1800;
                   4625: 
                   4626:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4627:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4628:     if (defined($cached)) {
1.734     albertel 4629:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4630:     } else {  
                   4631:         $grouplist = '';
1.816     raeburn  4632:         my $courseurl = &courseid_to_courseurl($courseid);
                   4633:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4634:         my $access_end = $env{'course.'.$courseid.
                   4635:                               '.default_enrollment_end_date'};
                   4636:         my $now = time;
                   4637:         foreach my $key (keys(%roleshash)) {
                   4638:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4639:                 my $group = $1;
                   4640:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4641:                     my $start = $2;
                   4642:                     my $end = $1;
                   4643:                     if ($start == -1) { next; } # deleted from group
                   4644:                     if (($start!=0) && ($start>$now)) { next; }
                   4645:                     if (($end!=0) && ($end<$now)) {
                   4646:                         if ($access_end && $access_end < $now) {
                   4647:                             if ($access_end - $end < 86400) {
                   4648:                                 push(@usersgroups,$group);
1.733     raeburn  4649:                             }
                   4650:                         }
1.817     raeburn  4651:                         next;
1.733     raeburn  4652:                     }
1.817     raeburn  4653:                     push(@usersgroups,$group);
1.683     raeburn  4654:                 }
                   4655:             }
                   4656:         }
1.817     raeburn  4657:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4658:         $grouplist = join(':',@usersgroups);
                   4659:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4660:     }
1.733     raeburn  4661:     return @usersgroups;
1.683     raeburn  4662: }
                   4663: 
                   4664: sub devalidate_getgroups_cache {
                   4665:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4666:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4667: 
1.683     raeburn  4668:     my $hashid="$udom:$uname:$courseid";
                   4669:     &devalidate_cache_new('getgroups',$hashid);
                   4670: }
                   4671: 
1.12      www      4672: # ------------------------------------------------------------------ Plain Text
                   4673: 
                   4674: sub plaintext {
1.742     raeburn  4675:     my ($short,$type,$cid) = @_;
1.758     albertel 4676:     if ($short =~ /^cr/) {
                   4677: 	return (split('/',$short))[-1];
                   4678:     }
1.742     raeburn  4679:     if (!defined($cid)) {
                   4680:         $cid = $env{'request.course.id'};
                   4681:     }
                   4682:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4683:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4684:                                           '.plaintext'});
                   4685:     }
                   4686:     my %rolenames = (
                   4687:                       Course => 'std',
                   4688:                       Group => 'alt1',
                   4689:                     );
                   4690:     if (defined($type) && 
                   4691:          defined($rolenames{$type}) && 
                   4692:          defined($prp{$short}{$rolenames{$type}})) {
                   4693:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4694:     } else {
                   4695:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4696:     }
1.12      www      4697: }
                   4698: 
                   4699: # ----------------------------------------------------------------- Assign Role
                   4700: 
                   4701: sub assignrole {
1.357     www      4702:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4703:     my $mrole;
                   4704:     if ($role =~ /^cr\//) {
1.393     www      4705:         my $cwosec=$url;
1.811     albertel 4706:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4707: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4708:            &logthis('Refused custom assignrole: '.
                   4709:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4710: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4711:            return 'refused'; 
                   4712:         }
1.21      www      4713:         $mrole='cr';
1.678     raeburn  4714:     } elsif ($role =~ /^gr\//) {
                   4715:         my $cwogrp=$url;
1.811     albertel 4716:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4717:         unless (&allowed('mdg',$cwogrp)) {
                   4718:             &logthis('Refused group assignrole: '.
                   4719:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4720:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4721:             return 'refused';
                   4722:         }
                   4723:         $mrole='gr';
1.21      www      4724:     } else {
1.82      www      4725:         my $cwosec=$url;
1.811     albertel 4726:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4727:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4728:            &logthis('Refused assignrole: '.
                   4729:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4730: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4731:            return 'refused'; 
                   4732:         }
1.21      www      4733:         $mrole=$role;
                   4734:     }
1.620     albertel 4735:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4736:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4737:     if ($end) { $command.='_'.$end; }
1.21      www      4738:     if ($start) {
                   4739: 	if ($end) { 
1.81      www      4740:            $command.='_'.$start; 
1.21      www      4741:         } else {
1.81      www      4742:            $command.='_0_'.$start;
1.21      www      4743:         }
                   4744:     }
1.739     raeburn  4745:     my $origstart = $start;
                   4746:     my $origend = $end;
1.357     www      4747: # actually delete
                   4748:     if ($deleteflag) {
1.373     www      4749: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4750: # modify command to delete the role
1.620     albertel 4751:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4752:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4753: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4754: # set start and finish to negative values for userrolelog
                   4755:            $start=-1;
                   4756:            $end=-1;
                   4757:         }
                   4758:     }
                   4759: # send command
1.349     www      4760:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4761: # log new user role if status is ok
1.349     www      4762:     if ($answer eq 'ok') {
1.663     raeburn  4763: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4764: # for course roles, perform group memberships changes triggered by role change.
                   4765:         unless ($role =~ /^gr/) {
                   4766:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4767:                                              $origstart);
                   4768:         }
1.349     www      4769:     }
                   4770:     return $answer;
1.169     harris41 4771: }
                   4772: 
                   4773: # -------------------------------------------------- Modify user authentication
1.197     www      4774: # Overrides without validation
                   4775: 
1.169     harris41 4776: sub modifyuserauth {
                   4777:     my ($udom,$uname,$umode,$upass)=@_;
                   4778:     my $uhome=&homeserver($uname,$udom);
1.197     www      4779:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4780:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4781:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4782:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4783:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4784: 		     &escape($upass),$uhome);
1.620     albertel 4785:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4786:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4787:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4788:     &log($udom,,$uname,$uhome,
1.620     albertel 4789:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4790:                                      $env{'user.name'}.', '.$umode.
1.197     www      4791:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4792:     unless ($reply eq 'ok') {
1.197     www      4793:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4794: 	return 'error: '.$reply;
                   4795:     }   
1.170     harris41 4796:     return 'ok';
1.80      www      4797: }
                   4798: 
1.81      www      4799: # --------------------------------------------------------------- Modify a user
1.80      www      4800: 
1.81      www      4801: sub modifyuser {
1.206     matthew  4802:     my ($udom,    $uname, $uid,
                   4803:         $umode,   $upass, $first,
                   4804:         $middle,  $last,  $gene,
1.387     www      4805:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4806:     $udom= &LONCAPA::clean_domain($udom);
                   4807:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4808:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4809:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4810: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4811:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4812:                                      ' desiredhome not specified'). 
1.620     albertel 4813:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4814:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4815:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4816: # ----------------------------------------------------------------- Create User
1.406     albertel 4817:     if (($uhome eq 'no_host') && 
                   4818: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4819:         my $unhome='';
1.844     albertel 4820:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4821:             $unhome = $desiredhome;
1.620     albertel 4822: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4823: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4824:         } else { # load balancing routine for determining $unhome
1.81      www      4825:             my $loadm=10000000;
1.841     albertel 4826: 	    my %servers = &get_servers($udom,'library');
                   4827: 	    foreach my $tryserver (keys(%servers)) {
                   4828: 		my $answer=reply('load',$tryserver);
                   4829: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4830: 		    $loadm=$answer;
                   4831: 		    $unhome=$tryserver;
                   4832: 		}
1.80      www      4833: 	    }
                   4834:         }
                   4835:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4836: 	    return 'error: unable to find a home server for '.$uname.
                   4837:                    ' in domain '.$udom;
1.80      www      4838:         }
                   4839:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4840:                          &escape($upass),$unhome);
                   4841: 	unless ($reply eq 'ok') {
                   4842:             return 'error: '.$reply;
                   4843:         }   
1.230     stredwic 4844:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4845:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4846: 	    return 'error: unable verify users home machine.';
1.80      www      4847:         }
1.209     matthew  4848:     }   # End of creation of new user
1.80      www      4849: # ---------------------------------------------------------------------- Add ID
                   4850:     if ($uid) {
                   4851:        $uid=~tr/A-Z/a-z/;
                   4852:        my %uidhash=&idrget($udom,$uname);
1.196     www      4853:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4854:          && (!$forceid)) {
1.80      www      4855: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4856: 	      return 'error: user id "'.$uid.'" does not match '.
                   4857:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4858:           }
                   4859:        } else {
                   4860: 	  &idput($udom,($uname => $uid));
                   4861:        }
                   4862:     }
                   4863: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4864:     my @tmp=&get('environment',
1.134     albertel 4865: 		   ['firstname','middlename','lastname','generation'],
                   4866: 		   $udom,$uname);
1.313     matthew  4867:     my %names;
                   4868:     if ($tmp[0] =~ m/^error:.*/) { 
                   4869:         %names=(); 
                   4870:     } else {
                   4871:         %names = @tmp;
                   4872:     }
1.388     www      4873: #
                   4874: # Make sure to not trash student environment if instructor does not bother
                   4875: # to supply name and email information
                   4876: #
                   4877:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4878:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4879:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4880:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4881:     if ($email) {
                   4882:        $email=~s/[^\w\@\.\-\,]//gs;
                   4883:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4884: 			   $names{'critnotification'} = $email;
                   4885: 			   $names{'permanentemail'} = $email; }
                   4886:     }
1.134     albertel 4887:     my $reply = &put('environment', \%names, $udom,$uname);
                   4888:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4889:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4890:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4891:              $umode.', '.$first.', '.$middle.', '.
                   4892: 	     $last.', '.$gene.' by '.
1.620     albertel 4893:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4894:     return 'ok';
1.80      www      4895: }
                   4896: 
1.81      www      4897: # -------------------------------------------------------------- Modify student
1.80      www      4898: 
1.81      www      4899: sub modifystudent {
                   4900:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4901:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4902:     if (!$cid) {
1.620     albertel 4903: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4904: 	    return 'not_in_class';
                   4905: 	}
1.80      www      4906:     }
                   4907: # --------------------------------------------------------------- Make the user
1.81      www      4908:     my $reply=&modifyuser
1.209     matthew  4909: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4910:          $desiredhome,$email);
1.80      www      4911:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4912:     # This will cause &modify_student_enrollment to get the uid from the
                   4913:     # students environment
                   4914:     $uid = undef if (!$forceid);
1.455     albertel 4915:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4916: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4917:     return $reply;
                   4918: }
                   4919: 
                   4920: sub modify_student_enrollment {
1.515     raeburn  4921:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4922:     my ($cdom,$cnum,$chome);
                   4923:     if (!$cid) {
1.620     albertel 4924: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4925: 	    return 'not_in_class';
                   4926: 	}
1.620     albertel 4927: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4928: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4929:     } else {
                   4930: 	($cdom,$cnum)=split(/_/,$cid);
                   4931:     }
1.620     albertel 4932:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4933:     if (!$chome) {
1.457     raeburn  4934: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4935:     }
1.455     albertel 4936:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4937:     # Make sure the user exists
1.81      www      4938:     my $uhome=&homeserver($uname,$udom);
                   4939:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4940: 	return 'error: no such user';
                   4941:     }
1.297     matthew  4942:     # Get student data if we were not given enough information
                   4943:     if (!defined($first)  || $first  eq '' || 
                   4944:         !defined($last)   || $last   eq '' || 
                   4945:         !defined($uid)    || $uid    eq '' || 
                   4946:         !defined($middle) || $middle eq '' || 
                   4947:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4948:         # They did not supply us with enough data to enroll the student, so
                   4949:         # we need to pick up more information.
1.297     matthew  4950:         my %tmp = &get('environment',
1.294     matthew  4951:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4952:                        ,$udom,$uname);
                   4953: 
1.800     albertel 4954:         #foreach my $key (keys(%tmp)) {
                   4955:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4956:         #}
1.294     matthew  4957:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4958:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4959:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4960:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4961:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4962:     }
1.556     albertel 4963:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4964:     my $reply=cput('classlist',
                   4965: 		   {"$uname:$udom" => 
1.515     raeburn  4966: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4967: 		   $cdom,$cnum);
1.81      www      4968:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4969: 	return 'error: '.$reply;
1.652     albertel 4970:     } else {
                   4971: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4972:     }
1.297     matthew  4973:     # Add student role to user
1.83      www      4974:     my $uurl='/'.$cid;
1.81      www      4975:     $uurl=~s/\_/\//g;
                   4976:     if ($usec) {
                   4977: 	$uurl.='/'.$usec;
                   4978:     }
                   4979:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4980: }
                   4981: 
1.556     albertel 4982: sub format_name {
                   4983:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4984:     my $name;
                   4985:     if ($first ne 'lastname') {
                   4986: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4987:     } else {
                   4988: 	if ($lastname=~/\S/) {
                   4989: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4990: 	    $name=~s/\s+,/,/;
                   4991: 	} else {
                   4992: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4993: 	}
                   4994:     }
                   4995:     $name=~s/^\s+//;
                   4996:     $name=~s/\s+$//;
                   4997:     $name=~s/\s+/ /g;
                   4998:     return $name;
                   4999: }
                   5000: 
1.84      www      5001: # ------------------------------------------------- Write to course preferences
                   5002: 
                   5003: sub writecoursepref {
                   5004:     my ($courseid,%prefs)=@_;
                   5005:     $courseid=~s/^\///;
                   5006:     $courseid=~s/\_/\//g;
                   5007:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5008:     my $chome=homeserver($cnum,$cdomain);
                   5009:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5010: 	return 'error: no such course';
                   5011:     }
                   5012:     my $cstring='';
1.800     albertel 5013:     foreach my $pref (keys(%prefs)) {
                   5014: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5015:     }
1.84      www      5016:     $cstring=~s/\&$//;
                   5017:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5018: }
                   5019: 
                   5020: # ---------------------------------------------------------- Make/modify course
                   5021: 
                   5022: sub createcourse {
1.741     raeburn  5023:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5024:         $course_owner,$crstype)=@_;
1.84      www      5025:     $url=&declutter($url);
                   5026:     my $cid='';
1.264     matthew  5027:     unless (&allowed('ccc',$udom)) {
1.84      www      5028:         return 'refused';
                   5029:     }
                   5030: # ------------------------------------------------------------------- Create ID
1.674     www      5031:    my $uname=int(1+rand(9)).
                   5032:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5033:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5034:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5035: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5036:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5037:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5038:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5039:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5040:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5041:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5042:            return 'error: unable to generate unique course-ID';
                   5043:        } 
                   5044:    }
1.264     matthew  5045: # ------------------------------------------------ Check supplied server name
1.620     albertel 5046:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845   ! albertel 5047:     if (! &is_library($course_server)) {
1.264     matthew  5048:         return 'error:bad server name '.$course_server;
                   5049:     }
1.84      www      5050: # ------------------------------------------------------------- Make the course
                   5051:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5052:                       $course_server);
1.84      www      5053:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5054:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5055:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5056: 	return 'error: no such course';
                   5057:     }
1.271     www      5058: # ----------------------------------------------------------------- Course made
1.516     raeburn  5059: # log existence
                   5060:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5061:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5062:                   &escape($crstype),$uhome);
1.358     www      5063:     &flushcourselogs();
                   5064: # set toplevel url
1.271     www      5065:     my $topurl=$url;
                   5066:     unless ($nonstandard) {
                   5067: # ------------------------------------------ For standard courses, make top url
                   5068:         my $mapurl=&clutter($url);
1.278     www      5069:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5070:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5071: <map>
                   5072: <resource id="1" type="start"></resource>
                   5073: <resource id="2" src="$mapurl"></resource>
                   5074: <resource id="3" type="finish"></resource>
                   5075: <link index="1" from="1" to="2"></link>
                   5076: <link index="2" from="2" to="3"></link>
                   5077: </map>
                   5078: ENDINITMAP
                   5079:         $topurl=&declutter(
1.638     albertel 5080:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5081:                           );
                   5082:     }
                   5083: # ----------------------------------------------------------- Write preferences
1.84      www      5084:     &writecoursepref($udom.'_'.$uname,
                   5085:                      ('description' => $description,
1.271     www      5086:                       'url'         => $topurl));
1.84      www      5087:     return '/'.$udom.'/'.$uname;
                   5088: }
                   5089: 
1.813     albertel 5090: sub is_course {
                   5091:     my ($cdom,$cnum) = @_;
                   5092:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5093: 				undef,'.');
                   5094:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5095:         return 1;
                   5096:     }
                   5097:     return 0;
                   5098: }
                   5099: 
1.21      www      5100: # ---------------------------------------------------------- Assign Custom Role
                   5101: 
                   5102: sub assigncustomrole {
1.357     www      5103:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5104:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5105:                        $end,$start,$deleteflag);
1.21      www      5106: }
                   5107: 
                   5108: # ----------------------------------------------------------------- Revoke Role
                   5109: 
                   5110: sub revokerole {
1.357     www      5111:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5112:     my $now=time;
1.357     www      5113:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5114: }
                   5115: 
                   5116: # ---------------------------------------------------------- Revoke Custom Role
                   5117: 
                   5118: sub revokecustomrole {
1.357     www      5119:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5120:     my $now=time;
1.357     www      5121:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5122:            $deleteflag);
1.17      www      5123: }
                   5124: 
1.533     banghart 5125: # ------------------------------------------------------------ Disk usage
1.535     albertel 5126: sub diskusage {
1.533     banghart 5127:     my ($udom,$uname,$directoryRoot)=@_;
                   5128:     $directoryRoot =~ s/\/$//;
1.535     albertel 5129:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5130:     return $listing;
1.512     banghart 5131: }
                   5132: 
1.566     banghart 5133: sub is_locked {
                   5134:     my ($file_name, $domain, $user) = @_;
                   5135:     my @check;
                   5136:     my $is_locked;
                   5137:     push @check, $file_name;
1.613     albertel 5138:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5139: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5140:     my ($tmp)=keys(%locked);
                   5141:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5142:     
1.566     banghart 5143:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5144:         $is_locked = 'false';
                   5145:         foreach my $entry (@{$locked{$file_name}}) {
                   5146:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5147:                $is_locked = 'true';
                   5148:                last;
1.745     raeburn  5149:            }
                   5150:        }
1.566     banghart 5151:     } else {
                   5152:         $is_locked = 'false';
                   5153:     }
                   5154: }
                   5155: 
1.759     albertel 5156: sub declutter_portfile {
                   5157:     my ($file) = @_;
1.833     albertel 5158:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5159:     return $file;
                   5160: }
                   5161: 
1.559     banghart 5162: # ------------------------------------------------------------- Mark as Read Only
                   5163: 
                   5164: sub mark_as_readonly {
                   5165:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5166:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5167:     my ($tmp)=keys(%current_permissions);
                   5168:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5169:     foreach my $file (@{$files}) {
1.759     albertel 5170: 	$file = &declutter_portfile($file);
1.561     banghart 5171:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5172:     }
1.613     albertel 5173:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5174:     return;
                   5175: }
                   5176: 
1.572     banghart 5177: # ------------------------------------------------------------Save Selected Files
                   5178: 
                   5179: sub save_selected_files {
                   5180:     my ($user, $path, @files) = @_;
                   5181:     my $filename = $user."savedfiles";
1.573     banghart 5182:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5183:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5184:     foreach my $file (@files) {
1.620     albertel 5185:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5186:     }
                   5187:     foreach my $file (@other_files) {
1.574     banghart 5188:         print (OUT $file."\n");
1.572     banghart 5189:     }
1.574     banghart 5190:     close (OUT);
1.572     banghart 5191:     return 'ok';
                   5192: }
                   5193: 
1.574     banghart 5194: sub clear_selected_files {
                   5195:     my ($user) = @_;
                   5196:     my $filename = $user."savedfiles";
                   5197:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5198:     print (OUT undef);
                   5199:     close (OUT);
                   5200:     return ("ok");    
                   5201: }
                   5202: 
1.572     banghart 5203: sub files_in_path {
                   5204:     my ($user, $path) = @_;
                   5205:     my $filename = $user."savedfiles";
                   5206:     my %return_files;
1.574     banghart 5207:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5208:     while (my $line_in = <IN>) {
1.574     banghart 5209:         chomp ($line_in);
                   5210:         my @paths_and_file = split (m!/!, $line_in);
                   5211:         my $file_part = pop (@paths_and_file);
                   5212:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5213:         $path_part.='/';
                   5214:         my $path_and_file = $path_part.$file_part;
                   5215:         if ($path_part eq $path) {
                   5216:             $return_files{$file_part}= 'selected';
                   5217:         }
                   5218:     }
1.574     banghart 5219:     close (IN);
                   5220:     return (\%return_files);
1.572     banghart 5221: }
                   5222: 
                   5223: # called in portfolio select mode, to show files selected NOT in current directory
                   5224: sub files_not_in_path {
                   5225:     my ($user, $path) = @_;
                   5226:     my $filename = $user."savedfiles";
                   5227:     my @return_files;
                   5228:     my $path_part;
1.800     albertel 5229:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5230:     while (my $line = <IN>) {
1.572     banghart 5231:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5232:         my @paths_and_file = split(m|/|, $line);
                   5233:         my $file_part = pop(@paths_and_file);
                   5234:         chomp($file_part);
                   5235:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5236:         $path_part .= '/';
                   5237:         my $path_and_file = $path_part.$file_part;
                   5238:         if ($path_part ne $path) {
1.800     albertel 5239:             push(@return_files, ($path_and_file));
1.572     banghart 5240:         }
                   5241:     }
1.800     albertel 5242:     close(OUT);
1.574     banghart 5243:     return (@return_files);
1.572     banghart 5244: }
                   5245: 
1.745     raeburn  5246: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5247: 
1.745     raeburn  5248: sub get_portfile_permissions {
                   5249:     my ($domain,$user) = @_;
1.613     albertel 5250:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5251:     my ($tmp)=keys(%current_permissions);
                   5252:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5253:     return \%current_permissions;
                   5254: }
                   5255: 
                   5256: #---------------------------------------------Get portfolio file access controls
                   5257: 
1.749     raeburn  5258: sub get_access_controls {
1.745     raeburn  5259:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5260:     my %access;
                   5261:     my $real_file = $file;
                   5262:     $file =~ s/\.meta$//;
1.745     raeburn  5263:     if (defined($file)) {
1.749     raeburn  5264:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5265:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5266:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5267:             }
                   5268:         }
1.745     raeburn  5269:     } else {
1.749     raeburn  5270:         foreach my $key (keys(%{$current_permissions})) {
                   5271:             if ($key =~ /\0accesscontrol$/) {
                   5272:                 if (defined($group)) {
                   5273:                     if ($key !~ m-^\Q$group\E/-) {
                   5274:                         next;
                   5275:                     }
                   5276:                 }
                   5277:                 my ($fullpath) = split(/\0/,$key);
                   5278:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5279:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5280:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5281:                     }
                   5282:                 }
                   5283:             }
                   5284:         }
                   5285:     }
                   5286:     return %access;
                   5287: }
                   5288: 
                   5289: sub modify_access_controls {
                   5290:     my ($file_name,$changes,$domain,$user)=@_;
                   5291:     my ($outcome,$deloutcome);
                   5292:     my %store_permissions;
                   5293:     my %new_values;
                   5294:     my %new_control;
                   5295:     my %translation;
                   5296:     my @deletions = ();
                   5297:     my $now = time;
                   5298:     if (exists($$changes{'activate'})) {
                   5299:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5300:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5301:             my $numnew = scalar(@newitems);
                   5302:             for (my $i=0; $i<$numnew; $i++) {
                   5303:                 my $newkey = $newitems[$i];
                   5304:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5305:                 if ($newkey =~ /^\d+:/) { 
                   5306:                     $newkey =~ s/^(\d+)/$newid/;
                   5307:                     $translation{$1} = $newid;
                   5308:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5309:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5310:                     $translation{$1} = $newid;
                   5311:                 }
1.749     raeburn  5312:                 $new_values{$file_name."\0".$newkey} = 
                   5313:                                           $$changes{'activate'}{$newitems[$i]};
                   5314:                 $new_control{$newkey} = $now;
                   5315:             }
                   5316:         }
                   5317:     }
                   5318:     my %todelete;
                   5319:     my %changed_items;
                   5320:     foreach my $action ('delete','update') {
                   5321:         if (exists($$changes{$action})) {
                   5322:             if (ref($$changes{$action}) eq 'HASH') {
                   5323:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5324:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5325:                     if ($action eq 'delete') { 
                   5326:                         $todelete{$itemnum} = 1;
                   5327:                     } else {
                   5328:                         $changed_items{$itemnum} = $key;
                   5329:                     }
                   5330:                 }
1.745     raeburn  5331:             }
                   5332:         }
1.749     raeburn  5333:     }
                   5334:     # get lock on access controls for file.
                   5335:     my $lockhash = {
                   5336:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5337:                                                        ':'.$env{'user.domain'},
                   5338:                    }; 
                   5339:     my $tries = 0;
                   5340:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5341:    
                   5342:     while (($gotlock ne 'ok') && $tries <3) {
                   5343:         $tries ++;
                   5344:         sleep 1;
                   5345:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5346:     }
                   5347:     if ($gotlock eq 'ok') {
                   5348:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5349:         my ($tmp)=keys(%curr_permissions);
                   5350:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5351:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5352:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5353:             if (ref($curr_controls) eq 'HASH') {
                   5354:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5355:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5356:                     if (defined($todelete{$itemnum})) {
                   5357:                         push(@deletions,$file_name."\0".$control_item);
                   5358:                     } else {
                   5359:                         if (defined($changed_items{$itemnum})) {
                   5360:                             $new_control{$changed_items{$itemnum}} = $now;
                   5361:                             push(@deletions,$file_name."\0".$control_item);
                   5362:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5363:                         } else {
                   5364:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5365:                         }
                   5366:                     }
1.745     raeburn  5367:                 }
                   5368:             }
                   5369:         }
1.749     raeburn  5370:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5371:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5372:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5373:         #  remove lock
                   5374:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5375:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5376:         my ($file,$group);
                   5377:         if (&is_course($domain,$user)) {
                   5378:             ($group,$file) = split(/\//,$file_name,2);
                   5379:         } else {
                   5380:             $file = $file_name;
                   5381:         }
                   5382:         my $sqlresult =
                   5383:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5384:                                     $group);
1.749     raeburn  5385:     } else {
                   5386:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5387:     }
1.749     raeburn  5388:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5389: }
                   5390: 
1.827     raeburn  5391: sub make_public_indefinitely {
                   5392:     my ($requrl) = @_;
                   5393:     my $now = time;
                   5394:     my $action = 'activate';
                   5395:     my $aclnum = 0;
                   5396:     if (&is_portfolio_url($requrl)) {
                   5397:         my (undef,$udom,$unum,$file_name,$group) =
                   5398:             &parse_portfolio_url($requrl);
                   5399:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5400:         my %access_controls = &get_access_controls($current_perms,
                   5401:                                                    $group,$file_name);
                   5402:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5403:             my ($num,$scope,$end,$start) = 
                   5404:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5405:             if ($scope eq 'public') {
                   5406:                 if ($start <= $now && $end == 0) {
                   5407:                     $action = 'none';
                   5408:                 } else {
                   5409:                     $action = 'update';
                   5410:                     $aclnum = $num;
                   5411:                 }
                   5412:                 last;
                   5413:             }
                   5414:         }
                   5415:         if ($action eq 'none') {
                   5416:              return 'ok';
                   5417:         } else {
                   5418:             my %changes;
                   5419:             my $newend = 0;
                   5420:             my $newstart = $now;
                   5421:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5422:             $changes{$action}{$newkey} = {
                   5423:                 type => 'public',
                   5424:                 time => {
                   5425:                     start => $newstart,
                   5426:                     end   => $newend,
                   5427:                 },
                   5428:             };
                   5429:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5430:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5431:             return $outcome;
                   5432:         }
                   5433:     } else {
                   5434:         return 'invalid';
                   5435:     }
                   5436: }
                   5437: 
1.745     raeburn  5438: #------------------------------------------------------Get Marked as Read Only
                   5439: 
                   5440: sub get_marked_as_readonly {
                   5441:     my ($domain,$user,$what,$group) = @_;
                   5442:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5443:     my @readonly_files;
1.629     banghart 5444:     my $cmp1=$what;
                   5445:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5446:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5447:         if (defined($group)) {
                   5448:             if ($file_name !~ m-^\Q$group\E/-) {
                   5449:                 next;
                   5450:             }
                   5451:         }
1.561     banghart 5452:         if (ref($value) eq "ARRAY"){
                   5453:             foreach my $stored_what (@{$value}) {
1.629     banghart 5454:                 my $cmp2=$stored_what;
1.759     albertel 5455:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5456:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5457:                 }
1.629     banghart 5458:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5459:                     push(@readonly_files, $file_name);
1.745     raeburn  5460:                     last;
1.563     banghart 5461:                 } elsif (!defined($what)) {
                   5462:                     push(@readonly_files, $file_name);
1.745     raeburn  5463:                     last;
1.561     banghart 5464:                 }
                   5465:             }
1.745     raeburn  5466:         }
1.561     banghart 5467:     }
                   5468:     return @readonly_files;
                   5469: }
1.577     banghart 5470: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5471: 
1.577     banghart 5472: sub get_marked_as_readonly_hash {
1.745     raeburn  5473:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5474:     my %readonly_files;
1.745     raeburn  5475:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5476:         if (defined($group)) {
                   5477:             if ($file_name !~ m-^\Q$group\E/-) {
                   5478:                 next;
                   5479:             }
                   5480:         }
1.577     banghart 5481:         if (ref($value) eq "ARRAY"){
                   5482:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5483:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5484:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5485:                         if ($lock_descriptor eq 'graded') {
                   5486:                             $readonly_files{$file_name} = 'graded';
                   5487:                         } elsif ($lock_descriptor eq 'handback') {
                   5488:                             $readonly_files{$file_name} = 'handback';
                   5489:                         } else {
                   5490:                             if (!exists($readonly_files{$file_name})) {
                   5491:                                 $readonly_files{$file_name} = 'locked';
                   5492:                             }
                   5493:                         }
1.745     raeburn  5494:                     }
1.750     banghart 5495:                 } 
1.577     banghart 5496:             }
                   5497:         } 
                   5498:     }
                   5499:     return %readonly_files;
                   5500: }
1.559     banghart 5501: # ------------------------------------------------------------ Unmark as Read Only
                   5502: 
                   5503: sub unmark_as_readonly {
1.629     banghart 5504:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5505:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5506:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5507:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5508:     my $symb_crs = $what;
                   5509:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5510:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5511:     my ($tmp)=keys(%current_permissions);
                   5512:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5513:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5514:     foreach my $file (@readonly_files) {
1.759     albertel 5515: 	my $clean_file = &declutter_portfile($file);
                   5516: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5517: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5518:         my @new_locks;
                   5519:         my @del_keys;
                   5520:         if (ref($current_locks) eq "ARRAY"){
                   5521:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5522:                 my $compare=$locker;
1.749     raeburn  5523:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5524:                     $compare=join('',@{$locker});
1.746     raeburn  5525:                     if ($compare ne $symb_crs) {
                   5526:                         push(@new_locks, $locker);
                   5527:                     }
1.563     banghart 5528:                 }
                   5529:             }
1.650     albertel 5530:             if (scalar(@new_locks) > 0) {
1.563     banghart 5531:                 $current_permissions{$file} = \@new_locks;
                   5532:             } else {
                   5533:                 push(@del_keys, $file);
1.613     albertel 5534:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5535:                 delete($current_permissions{$file});
1.563     banghart 5536:             }
                   5537:         }
1.561     banghart 5538:     }
1.613     albertel 5539:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5540:     return;
                   5541: }
1.512     banghart 5542: 
1.17      www      5543: # ------------------------------------------------------------ Directory lister
                   5544: 
                   5545: sub dirlist {
1.253     stredwic 5546:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5547: 
1.18      www      5548:     $uri=~s/^\///;
                   5549:     $uri=~s/\/$//;
1.253     stredwic 5550:     my ($udom, $uname);
                   5551:     (undef,$udom,$uname)=split(/\//,$uri);
                   5552:     if(defined($userdomain)) {
                   5553:         $udom = $userdomain;
                   5554:     }
                   5555:     if(defined($username)) {
                   5556:         $uname = $username;
                   5557:     }
                   5558: 
                   5559:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5560:     if(defined($alternateDirectoryRoot)) {
                   5561:         $dirRoot = $alternateDirectoryRoot;
                   5562:         $dirRoot =~ s/\/$//;
1.751     banghart 5563:     }
1.253     stredwic 5564: 
                   5565:     if($udom) {
                   5566:         if($uname) {
1.800     albertel 5567:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5568: 				 &homeserver($uname,$udom));
1.605     matthew  5569:             my @listing_results;
                   5570:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5571:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5572: 				  &homeserver($uname,$udom));
1.605     matthew  5573:                 @listing_results = split(/:/,$listing);
                   5574:             } else {
                   5575:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5576:             }
                   5577:             return @listing_results;
1.253     stredwic 5578:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5579:             my %allusers;
1.841     albertel 5580: 	    my %servers = &get_servers($udom,'library');
                   5581: 	    foreach my $tryserver (keys(%servers)) {
                   5582: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5583: 				     $udom, $tryserver);
                   5584: 		my @listing_results;
                   5585: 		if ($listing eq 'unknown_cmd') {
                   5586: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5587: 				      $udom, $tryserver);
                   5588: 		    @listing_results = split(/:/,$listing);
                   5589: 		} else {
                   5590: 		    @listing_results =
                   5591: 			map { &unescape($_); } split(/:/,$listing);
                   5592: 		}
                   5593: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5594: 		    $listing_results[0] ne 'empty'       &&
                   5595: 		    $listing_results[0] ne 'con_lost') {
                   5596: 		    foreach my $line (@listing_results) {
                   5597: 			my ($entry) = split(/&/,$line,2);
                   5598: 			$allusers{$entry} = 1;
                   5599: 		    }
                   5600: 		}
1.253     stredwic 5601:             }
                   5602:             my $alluserstr='';
1.800     albertel 5603:             foreach my $user (sort(keys(%allusers))) {
                   5604:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5605:             }
                   5606:             $alluserstr=~s/:$//;
                   5607:             return split(/:/,$alluserstr);
                   5608:         } else {
1.800     albertel 5609:             return ('missing user name');
1.253     stredwic 5610:         }
                   5611:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5612:         my @all_domains = sort(&all_domains());
                   5613:          foreach my $domain (@all_domains) {
                   5614:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5615:          }
                   5616:          return @all_domains;
                   5617:      } else {
1.800     albertel 5618:         return ('missing domain');
1.275     stredwic 5619:     }
                   5620: }
                   5621: 
                   5622: # --------------------------------------------- GetFileTimestamp
                   5623: # This function utilizes dirlist and returns the date stamp for
                   5624: # when it was last modified.  It will also return an error of -1
                   5625: # if an error occurs
                   5626: 
1.410     matthew  5627: ##
                   5628: ## FIXME: This subroutine assumes its caller knows something about the
                   5629: ## directory structure of the home server for the student ($root).
                   5630: ## Not a good assumption to make.  Since this is for looking up files
                   5631: ## in user directories, the full path should be constructed by lond, not
                   5632: ## whatever machine we request data from.
                   5633: ##
1.275     stredwic 5634: sub GetFileTimestamp {
                   5635:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5636:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5637:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5638:     my $subdir=$studentName.'__';
                   5639:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5640:     my $proname="$studentDomain/$subdir/$studentName";
                   5641:     $proname .= '/'.$filename;
1.375     matthew  5642:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5643:                                               $studentName, $root);
1.275     stredwic 5644:     my @stats = split('&', $fileStat);
                   5645:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5646:         # @stats contains first the filename, then the stat output
                   5647:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5648:     } else {
                   5649:         return -1;
1.253     stredwic 5650:     }
1.26      www      5651: }
                   5652: 
1.712     albertel 5653: sub stat_file {
                   5654:     my ($uri) = @_;
1.787     albertel 5655:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5656: 
1.712     albertel 5657:     my ($udom,$uname,$file,$dir);
                   5658:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5659: 	($udom,$uname,$file) =
1.811     albertel 5660: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5661: 	$file = 'userfiles/'.$file;
1.740     www      5662: 	$dir = &propath($udom,$uname);
1.712     albertel 5663:     }
                   5664:     if ($uri =~ m-^/res/-) {
                   5665: 	($udom,$uname) = 
1.807     albertel 5666: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5667: 	$file = $uri;
                   5668:     }
                   5669: 
                   5670:     if (!$udom || !$uname || !$file) {
                   5671: 	# unable to handle the uri
                   5672: 	return ();
                   5673:     }
                   5674: 
                   5675:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5676:     my @stats = split('&', $result);
1.721     banghart 5677:     
1.712     albertel 5678:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5679: 	shift(@stats); #filename is first
                   5680: 	return @stats;
                   5681:     }
                   5682:     return ();
                   5683: }
                   5684: 
1.26      www      5685: # -------------------------------------------------------- Value of a Condition
                   5686: 
1.713     albertel 5687: # gets the value of a specific preevaluated condition
                   5688: #    stored in the string  $env{user.state.<cid>}
                   5689: # or looks up a condition reference in the bighash and if if hasn't
                   5690: # already been evaluated recurses into docondval to get the value of
                   5691: # the condition, then memoizing it to 
                   5692: #   $env{user.state.<cid>.<condition>}
1.40      www      5693: sub directcondval {
                   5694:     my $number=shift;
1.620     albertel 5695:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5696: 	&Apache::lonuserstate::evalstate();
                   5697:     }
1.713     albertel 5698:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5699: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5700:     } elsif ($number =~ /^_/) {
                   5701: 	my $sub_condition;
                   5702: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5703: 		&GDBM_READER(),0640)) {
                   5704: 	    $sub_condition=$bighash{'conditions'.$number};
                   5705: 	    untie(%bighash);
                   5706: 	}
                   5707: 	my $value = &docondval($sub_condition);
                   5708: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5709: 	return $value;
                   5710:     }
1.620     albertel 5711:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5712:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5713:     } else {
                   5714:        return 2;
                   5715:     }
                   5716: }
                   5717: 
1.713     albertel 5718: # get the collection of conditions for this resource
1.26      www      5719: sub condval {
                   5720:     my $condidx=shift;
1.54      www      5721:     my $allpathcond='';
1.713     albertel 5722:     foreach my $cond (split(/\|/,$condidx)) {
                   5723: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5724: 	    $allpathcond.=
                   5725: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5726: 	}
1.191     harris41 5727:     }
1.54      www      5728:     $allpathcond=~s/\|$//;
1.713     albertel 5729:     return &docondval($allpathcond);
                   5730: }
                   5731: 
                   5732: #evaluates an expression of conditions
                   5733: sub docondval {
                   5734:     my ($allpathcond) = @_;
                   5735:     my $result=0;
                   5736:     if ($env{'request.course.id'}
                   5737: 	&& defined($allpathcond)) {
                   5738: 	my $operand='|';
                   5739: 	my @stack;
                   5740: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5741: 	    if ($chunk eq '(') {
                   5742: 		push @stack,($operand,$result);
                   5743: 	    } elsif ($chunk eq ')') {
                   5744: 		my $before=pop @stack;
                   5745: 		if (pop @stack eq '&') {
                   5746: 		    $result=$result>$before?$before:$result;
                   5747: 		} else {
                   5748: 		    $result=$result>$before?$result:$before;
                   5749: 		}
                   5750: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5751: 		$operand=$chunk;
                   5752: 	    } else {
                   5753: 		my $new=directcondval($chunk);
                   5754: 		if ($operand eq '&') {
                   5755: 		    $result=$result>$new?$new:$result;
                   5756: 		} else {
                   5757: 		    $result=$result>$new?$result:$new;
                   5758: 		}
                   5759: 	    }
                   5760: 	}
1.26      www      5761:     }
                   5762:     return $result;
1.421     albertel 5763: }
                   5764: 
                   5765: # ---------------------------------------------------- Devalidate courseresdata
                   5766: 
                   5767: sub devalidatecourseresdata {
                   5768:     my ($coursenum,$coursedomain)=@_;
                   5769:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5770:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5771: }
                   5772: 
1.763     www      5773: 
1.200     www      5774: # --------------------------------------------------- Course Resourcedata Query
                   5775: 
1.624     albertel 5776: sub get_courseresdata {
                   5777:     my ($coursenum,$coursedomain)=@_;
1.200     www      5778:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5779:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5780:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5781:     my %dumpreply;
1.417     albertel 5782:     unless (defined($cached)) {
1.624     albertel 5783: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5784: 	$result=\%dumpreply;
1.251     albertel 5785: 	my ($tmp) = keys(%dumpreply);
                   5786: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5787: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5788: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5789: 	    return $tmp;
1.416     albertel 5790: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5791: 	    $result=undef;
1.599     albertel 5792: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5793: 	}
                   5794:     }
1.624     albertel 5795:     return $result;
                   5796: }
                   5797: 
1.633     albertel 5798: sub devalidateuserresdata {
                   5799:     my ($uname,$udom)=@_;
                   5800:     my $hashid="$udom:$uname";
                   5801:     &devalidate_cache_new('userres',$hashid);
                   5802: }
                   5803: 
1.624     albertel 5804: sub get_userresdata {
                   5805:     my ($uname,$udom)=@_;
                   5806:     #most student don\'t have any data set, check if there is some data
                   5807:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5808: 
                   5809:     my $hashid="$udom:$uname";
                   5810:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5811:     if (!defined($cached)) {
                   5812: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5813: 	$result=\%resourcedata;
                   5814: 	&do_cache_new('userres',$hashid,$result,600);
                   5815:     }
                   5816:     my ($tmp)=keys(%$result);
                   5817:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5818: 	return $result;
                   5819:     }
                   5820:     #error 2 occurs when the .db doesn't exist
                   5821:     if ($tmp!~/error: 2 /) {
1.672     albertel 5822: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5823: 		 " Trying to get resource data for ".
                   5824: 		 $uname." at ".$udom.": ".
                   5825: 		 $tmp."</font>");
                   5826:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5827: 	#&EXT_cache_set($udom,$uname);
                   5828: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5829: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5830:     }
                   5831:     return $tmp;
                   5832: }
                   5833: 
                   5834: sub resdata {
                   5835:     my ($name,$domain,$type,@which)=@_;
                   5836:     my $result;
                   5837:     if ($type eq 'course') {
                   5838: 	$result=&get_courseresdata($name,$domain);
                   5839:     } elsif ($type eq 'user') {
                   5840: 	$result=&get_userresdata($name,$domain);
                   5841:     }
                   5842:     if (!ref($result)) { return $result; }    
1.251     albertel 5843:     foreach my $item (@which) {
1.417     albertel 5844: 	if (defined($result->{$item})) {
                   5845: 	    return $result->{$item};
1.251     albertel 5846: 	}
1.250     albertel 5847:     }
1.291     albertel 5848:     return undef;
1.200     www      5849: }
                   5850: 
1.379     matthew  5851: #
                   5852: # EXT resource caching routines
                   5853: #
                   5854: 
                   5855: sub clear_EXT_cache_status {
1.383     albertel 5856:     &delenv('cache.EXT.');
1.379     matthew  5857: }
                   5858: 
                   5859: sub EXT_cache_status {
                   5860:     my ($target_domain,$target_user) = @_;
1.383     albertel 5861:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5862:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5863:         # We know already the user has no data
                   5864:         return 1;
                   5865:     } else {
                   5866:         return 0;
                   5867:     }
                   5868: }
                   5869: 
                   5870: sub EXT_cache_set {
                   5871:     my ($target_domain,$target_user) = @_;
1.383     albertel 5872:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5873:     #&appenv($cachename => time);
1.379     matthew  5874: }
                   5875: 
1.28      www      5876: # --------------------------------------------------------- Value of a Variable
1.58      www      5877: sub EXT {
1.715     albertel 5878: 
1.395     albertel 5879:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5880:     unless ($varname) { return ''; }
1.218     albertel 5881:     #get real user name/domain, courseid and symb
                   5882:     my $courseid;
1.359     albertel 5883:     my $publicuser;
1.427     www      5884:     if ($symbparm) {
                   5885: 	$symbparm=&get_symb_from_alias($symbparm);
                   5886:     }
1.218     albertel 5887:     if (!($uname && $udom)) {
1.790     albertel 5888:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5889:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5890:     } else {
1.620     albertel 5891: 	$courseid=$env{'request.course.id'};
1.218     albertel 5892:     }
1.48      www      5893:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5894:     my $rest;
1.320     albertel 5895:     if (defined($therest[0])) {
1.48      www      5896:        $rest=join('.',@therest);
                   5897:     } else {
                   5898:        $rest='';
                   5899:     }
1.320     albertel 5900: 
1.57      www      5901:     my $qualifierrest=$qualifier;
                   5902:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5903:     my $spacequalifierrest=$space;
                   5904:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5905:     if ($realm eq 'user') {
1.48      www      5906: # --------------------------------------------------------------- user.resource
                   5907: 	if ($space eq 'resource') {
1.651     albertel 5908: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5909: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5910: 		 &&
1.744     albertel 5911: 		 ($symbparm eq &symbread()) ) {	
                   5912: 		# if we are in the middle of processing the resource the
                   5913: 		# get the value we are planning on committing
                   5914:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5915:                     return $Apache::lonhomework::results{$qualifierrest};
                   5916:                 } else {
                   5917:                     return $Apache::lonhomework::history{$qualifierrest};
                   5918:                 }
1.335     albertel 5919: 	    } else {
1.359     albertel 5920: 		my %restored;
1.620     albertel 5921: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5922: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5923: 		} else {
                   5924: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5925: 		}
1.335     albertel 5926: 		return $restored{$qualifierrest};
                   5927: 	    }
1.48      www      5928: # ----------------------------------------------------------------- user.access
                   5929:         } elsif ($space eq 'access') {
1.218     albertel 5930: 	    # FIXME - not supporting calls for a specific user
1.48      www      5931:             return &allowed($qualifier,$rest);
                   5932: # ------------------------------------------ user.preferences, user.environment
                   5933:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5934: 	    if (($uname eq $env{'user.name'}) &&
                   5935: 		($udom eq $env{'user.domain'})) {
                   5936: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5937: 	    } else {
1.359     albertel 5938: 		my %returnhash;
                   5939: 		if (!$publicuser) {
                   5940: 		    %returnhash=&userenvironment($udom,$uname,
                   5941: 						 $qualifierrest);
                   5942: 		}
1.218     albertel 5943: 		return $returnhash{$qualifierrest};
                   5944: 	    }
1.48      www      5945: # ----------------------------------------------------------------- user.course
                   5946:         } elsif ($space eq 'course') {
1.218     albertel 5947: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5948:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5949: # ------------------------------------------------------------------- user.role
                   5950:         } elsif ($space eq 'role') {
1.218     albertel 5951: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5952:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5953:             if ($qualifier eq 'value') {
                   5954: 		return $role;
                   5955:             } elsif ($qualifier eq 'extent') {
                   5956:                 return $where;
                   5957:             }
                   5958: # ----------------------------------------------------------------- user.domain
                   5959:         } elsif ($space eq 'domain') {
1.218     albertel 5960:             return $udom;
1.48      www      5961: # ------------------------------------------------------------------- user.name
                   5962:         } elsif ($space eq 'name') {
1.218     albertel 5963:             return $uname;
1.48      www      5964: # ---------------------------------------------------- Any other user namespace
1.29      www      5965:         } else {
1.359     albertel 5966: 	    my %reply;
                   5967: 	    if (!$publicuser) {
                   5968: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5969: 	    }
                   5970: 	    return $reply{$qualifierrest};
1.48      www      5971:         }
1.236     www      5972:     } elsif ($realm eq 'query') {
                   5973: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5974:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5975: 						[$spacequalifierrest]);
1.620     albertel 5976: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5977:    } elsif ($realm eq 'request') {
1.48      www      5978: # ------------------------------------------------------------- request.browser
                   5979:         if ($space eq 'browser') {
1.430     www      5980: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5981: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5982: 		    return 1;
                   5983: 		} else {
                   5984: 		    return 0;
                   5985: 		}
                   5986: 	    } else {
1.620     albertel 5987: 		return $env{'browser.'.$qualifier};
1.430     www      5988: 	    }
1.57      www      5989: # ------------------------------------------------------------ request.filename
                   5990:         } else {
1.620     albertel 5991:             return $env{'request.'.$spacequalifierrest};
1.29      www      5992:         }
1.28      www      5993:     } elsif ($realm eq 'course') {
1.48      www      5994: # ---------------------------------------------------------- course.description
1.620     albertel 5995:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5996:     } elsif ($realm eq 'resource') {
1.165     www      5997: 
1.620     albertel 5998: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5999: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6000: 	}
1.693     albertel 6001: 
                   6002: 	if ($space eq 'title') {
                   6003: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6004: 	    return &gettitle($symbparm);
                   6005: 	}
                   6006: 	
                   6007: 	if ($space eq 'map') {
                   6008: 	    my ($map) = &decode_symb($symbparm);
                   6009: 	    return &symbread($map);
                   6010: 	}
                   6011: 
                   6012: 	my ($section, $group, @groups);
1.593     albertel 6013: 	my ($courselevelm,$courselevel);
1.539     albertel 6014: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6015: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6016: 
1.218     albertel 6017: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6018: 
1.60      www      6019: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6020: 	    my $symbp=$symbparm;
1.735     albertel 6021: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6022: 
                   6023: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6024: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6025: 
1.620     albertel 6026: 	    if (($env{'user.name'} eq $uname) &&
                   6027: 		($env{'user.domain'} eq $udom)) {
                   6028: 		$section=$env{'request.course.sec'};
1.733     raeburn  6029:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6030:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6031: 	    } else {
1.539     albertel 6032: 		if (! defined($usection)) {
1.551     albertel 6033: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6034: 		} else {
                   6035: 		    $section = $usection;
                   6036: 		}
1.733     raeburn  6037:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6038: 	    }
                   6039: 
                   6040: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6041: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6042: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6043: 
1.593     albertel 6044: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6045: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6046: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6047: 
1.60      www      6048: # ----------------------------------------------------------- first, check user
1.624     albertel 6049: 
                   6050: 	    my $userreply=&resdata($uname,$udom,'user',
                   6051: 				       ($courselevelr,$courselevelm,
                   6052: 					$courselevel));
                   6053: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6054: 
1.594     albertel 6055: # ------------------------------------------------ second, check some of course
1.684     raeburn  6056:             my $coursereply;
1.691     raeburn  6057:             if (@groups > 0) {
                   6058:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6059:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6060:                 if (defined($coursereply)) { return $coursereply; }
                   6061:             }
1.96      www      6062: 
1.684     raeburn  6063: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6064: 				     $env{'course.'.$courseid.'.domain'},
                   6065: 				     'course',
                   6066: 				     ($seclevelr,$seclevelm,$seclevel,
                   6067: 				      $courselevelr));
1.287     albertel 6068: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6069: 
1.60      www      6070: # ------------------------------------------------------ third, check map parms
1.218     albertel 6071: 	    my %parmhash=();
                   6072: 	    my $thisparm='';
                   6073: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6074: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6075: 		    &GDBM_READER(),0640)) {
1.218     albertel 6076: 		$thisparm=$parmhash{$symbparm};
                   6077: 		untie(%parmhash);
                   6078: 	    }
                   6079: 	    if ($thisparm) { return $thisparm; }
                   6080: 	}
1.594     albertel 6081: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6082: 
1.218     albertel 6083: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6084: 	my $filename;
                   6085: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6086: 	if ($symbparm) {
1.409     www      6087: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6088: 	} else {
1.620     albertel 6089: 	    $filename=$env{'request.filename'};
1.282     albertel 6090: 	}
                   6091: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6092: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6093: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6094: 	if (defined($metadata)) { return $metadata; }
1.142     www      6095: 
1.594     albertel 6096: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6097: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6098: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6099: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6100: 				     $env{'course.'.$courseid.'.domain'},
                   6101: 				     'course',
                   6102: 				     ($courselevelm,$courselevel));
1.593     albertel 6103: 	    if (defined($coursereply)) { return $coursereply; }
                   6104: 	}
1.145     www      6105: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6106: 	unless ($space eq '0') {
1.336     albertel 6107: 	    my @parts=split(/_/,$space);
                   6108: 	    my $id=pop(@parts);
                   6109: 	    my $part=join('_',@parts);
                   6110: 	    if ($part eq '') { $part='0'; }
                   6111: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6112: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6113: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6114: 	}
1.395     albertel 6115: 	if ($recurse) { return undef; }
                   6116: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6117: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6118: 
1.48      www      6119: # ---------------------------------------------------- Any other user namespace
                   6120:     } elsif ($realm eq 'environment') {
                   6121: # ----------------------------------------------------------------- environment
1.620     albertel 6122: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6123: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6124: 	} else {
1.770     albertel 6125: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6126: 		return '';
                   6127: 	    }
1.219     albertel 6128: 	    my %returnhash=&userenvironment($udom,$uname,
                   6129: 					    $spacequalifierrest);
                   6130: 	    return $returnhash{$spacequalifierrest};
                   6131: 	}
1.28      www      6132:     } elsif ($realm eq 'system') {
1.48      www      6133: # ----------------------------------------------------------------- system.time
                   6134: 	if ($space eq 'time') {
                   6135: 	    return time;
                   6136:         }
1.696     albertel 6137:     } elsif ($realm eq 'server') {
                   6138: # ----------------------------------------------------------------- system.time
                   6139: 	if ($space eq 'name') {
                   6140: 	    return $ENV{'SERVER_NAME'};
                   6141:         }
1.28      www      6142:     }
1.48      www      6143:     return '';
1.61      www      6144: }
                   6145: 
1.691     raeburn  6146: sub check_group_parms {
                   6147:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6148:     my @groupitems = ();
                   6149:     my $resultitem;
                   6150:     my @levels = ($symbparm,$mapparm,$what);
                   6151:     foreach my $group (@{$groups}) {
                   6152:         foreach my $level (@levels) {
                   6153:              my $item = $courseid.'.['.$group.'].'.$level;
                   6154:              push(@groupitems,$item);
                   6155:         }
                   6156:     }
                   6157:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6158:                             $env{'course.'.$courseid.'.domain'},
                   6159:                                      'course',@groupitems);
                   6160:     return $coursereply;
                   6161: }
                   6162: 
                   6163: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6164:     my ($courseid,@groups) = @_;
                   6165:     @groups = sort(@groups);
1.691     raeburn  6166:     return @groups;
                   6167: }
                   6168: 
1.395     albertel 6169: sub packages_tab_default {
                   6170:     my ($uri,$varname)=@_;
                   6171:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6172: 
                   6173:     my (@extension,@specifics,$do_default);
                   6174:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6175: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6176: 	if ($pack_type eq 'default') {
                   6177: 	    $do_default=1;
                   6178: 	} elsif ($pack_type eq 'extension') {
                   6179: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6180: 	} else {
                   6181: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6182: 	}
                   6183:     }
                   6184:     # first look for a package that matches the requested part id
                   6185:     foreach my $package (@specifics) {
                   6186: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6187: 	next if ($pack_part ne $part);
                   6188: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6189: 	    return $packagetab{"$pack_type&$name&default"};
                   6190: 	}
                   6191:     }
                   6192:     # look for any possible matching non extension_ package
                   6193:     foreach my $package (@specifics) {
                   6194: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6195: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6196: 	    return $packagetab{"$pack_type&$name&default"};
                   6197: 	}
1.585     albertel 6198: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6199: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6200: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6201: 	}
                   6202:     }
1.738     albertel 6203:     # look for any posible extension_ match
                   6204:     foreach my $package (@extension) {
                   6205: 	my ($package,$pack_type)=@{$package};
                   6206: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6207: 	    return $packagetab{"$pack_type&$name&default"};
                   6208: 	}
                   6209: 	if (defined($packagetab{$package."&$name&default"})) {
                   6210: 	    return $packagetab{$package."&$name&default"};
                   6211: 	}
                   6212:     }
                   6213:     # look for a global default setting
                   6214:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6215: 	return $packagetab{"default&$name&default"};
                   6216:     }
1.395     albertel 6217:     return undef;
                   6218: }
                   6219: 
1.334     albertel 6220: sub add_prefix_and_part {
                   6221:     my ($prefix,$part)=@_;
                   6222:     my $keyroot;
                   6223:     if (defined($prefix) && $prefix !~ /^__/) {
                   6224: 	# prefix that has a part already
                   6225: 	$keyroot=$prefix;
                   6226:     } elsif (defined($prefix)) {
                   6227: 	# prefix that is missing a part
                   6228: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6229:     } else {
                   6230: 	# no prefix at all
                   6231: 	if (defined($part)) { $keyroot='_'.$part; }
                   6232:     }
                   6233:     return $keyroot;
                   6234: }
                   6235: 
1.71      www      6236: # ---------------------------------------------------------------- Get metadata
                   6237: 
1.599     albertel 6238: my %metaentry;
1.71      www      6239: sub metadata {
1.176     www      6240:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6241:     $uri=&declutter($uri);
1.288     albertel 6242:     # if it is a non metadata possible uri return quickly
1.529     albertel 6243:     if (($uri eq '') || 
                   6244: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6245: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6246:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6247: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6248: 	return undef;
1.288     albertel 6249:     }
1.73      www      6250:     my $filename=$uri;
                   6251:     $uri=~s/\.meta$//;
1.172     www      6252: #
                   6253: # Is the metadata already cached?
1.177     www      6254: # Look at timestamp of caching
1.172     www      6255: # Everything is cached by the main uri, libraries are never directly cached
                   6256: #
1.428     albertel 6257:     if (!defined($liburi)) {
1.599     albertel 6258: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6259: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6260:     }
                   6261:     {
1.172     www      6262: #
                   6263: # Is this a recursive call for a library?
                   6264: #
1.599     albertel 6265: #	if (! exists($metacache{$uri})) {
                   6266: #	    $metacache{$uri}={};
                   6267: #	}
1.171     www      6268:         if ($liburi) {
                   6269: 	    $liburi=&declutter($liburi);
                   6270:             $filename=$liburi;
1.401     bowersj2 6271:         } else {
1.599     albertel 6272: 	    &devalidate_cache_new('meta',$uri);
                   6273: 	    undef(%metaentry);
1.401     bowersj2 6274: 	}
1.140     www      6275:         my %metathesekeys=();
1.73      www      6276:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6277: 	my $metastring;
1.768     albertel 6278: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6279: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6280: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6281: 	    $metastring=&getfile($file);
1.489     albertel 6282: 	}
1.208     albertel 6283:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6284:         my $token;
1.140     www      6285:         undef %metathesekeys;
1.71      www      6286:         while ($token=$parser->get_token) {
1.339     albertel 6287: 	    if ($token->[0] eq 'S') {
                   6288: 		if (defined($token->[2]->{'package'})) {
1.172     www      6289: #
                   6290: # This is a package - get package info
                   6291: #
1.339     albertel 6292: 		    my $package=$token->[2]->{'package'};
                   6293: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6294: 		    if (defined($token->[2]->{'id'})) { 
                   6295: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6296: 		    }
1.599     albertel 6297: 		    if ($metaentry{':packages'}) {
                   6298: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6299: 		    } else {
1.599     albertel 6300: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6301: 		    }
1.736     albertel 6302: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6303: 			my $part=$keyroot;
                   6304: 			$part=~s/^\_//;
1.736     albertel 6305: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6306: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6307: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6308: 			    # ignore package.tab specified default values
                   6309:                             # here &package_tab_default() will fetch those
                   6310: 			    if ($subp eq 'default') { next; }
1.736     albertel 6311: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6312: 			    my $unikey;
                   6313: 			    if ($pack =~ /_0$/) {
                   6314: 				$unikey='parameter_0_'.$name;
                   6315: 				$part=0;
                   6316: 			    } else {
                   6317: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6318: 			    }
1.339     albertel 6319: 			    if ($subp eq 'display') {
                   6320: 				$value.=' [Part: '.$part.']';
                   6321: 			    }
1.599     albertel 6322: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6323: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6324: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6325: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6326: 			    }
1.599     albertel 6327: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6328: 				$metaentry{':'.$unikey}=
                   6329: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6330: 			    }
1.339     albertel 6331: 			}
                   6332: 		    }
                   6333: 		} else {
1.172     www      6334: #
                   6335: # This is not a package - some other kind of start tag
1.339     albertel 6336: #
                   6337: 		    my $entry=$token->[1];
                   6338: 		    my $unikey;
                   6339: 		    if ($entry eq 'import') {
                   6340: 			$unikey='';
                   6341: 		    } else {
                   6342: 			$unikey=$entry;
                   6343: 		    }
                   6344: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6345: 
                   6346: 		    if (defined($token->[2]->{'id'})) { 
                   6347: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6348: 		    }
1.175     www      6349: 
1.339     albertel 6350: 		    if ($entry eq 'import') {
1.175     www      6351: #
                   6352: # Importing a library here
1.339     albertel 6353: #
                   6354: 			if ($depthcount<20) {
                   6355: 			    my $location=$parser->get_text('/import');
                   6356: 			    my $dir=$filename;
                   6357: 			    $dir=~s|[^/]*$||;
                   6358: 			    $location=&filelocation($dir,$location);
1.736     albertel 6359: 			    my $metadata = 
                   6360: 				&metadata($uri,'keys', $location,$unikey,
                   6361: 					  $depthcount+1);
                   6362: 			    foreach my $meta (split(',',$metadata)) {
                   6363: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6364: 				$metathesekeys{$meta}=1;
1.339     albertel 6365: 			    }
                   6366: 			}
                   6367: 		    } else { 
                   6368: 			
                   6369: 			if (defined($token->[2]->{'name'})) { 
                   6370: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6371: 			}
                   6372: 			$metathesekeys{$unikey}=1;
1.736     albertel 6373: 			foreach my $param (@{$token->[3]}) {
                   6374: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6375: 				$token->[2]->{$param};
1.339     albertel 6376: 			}
                   6377: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6378: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6379: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6380: 		 # only ws inside the tag, and not in default, so use default
                   6381: 		 # as value
1.599     albertel 6382: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6383: 			} else {
1.321     albertel 6384: 		  # either something interesting inside the tag or default
                   6385:                   # uninteresting
1.599     albertel 6386: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6387: 			}
1.172     www      6388: # end of not-a-package not-a-library import
1.339     albertel 6389: 		    }
1.172     www      6390: # end of not-a-package start tag
1.339     albertel 6391: 		}
1.172     www      6392: # the next is the end of "start tag"
1.339     albertel 6393: 	    }
                   6394: 	}
1.483     albertel 6395: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6396: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6397: 	    #no specific packages #how's our extension
                   6398: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6399: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6400: 					 \%metathesekeys);
                   6401: 	}
1.599     albertel 6402: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6403: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6404: 		#no specific packages well let's get default then
                   6405: 		if ($key!~/^default&/) { next; }
1.488     albertel 6406: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6407: 					     \%metathesekeys);
                   6408: 	    }
                   6409: 	}
1.338     www      6410: # are there custom rights to evaluate
1.599     albertel 6411: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6412: 
1.338     www      6413:     #
                   6414:     # Importing a rights file here
1.339     albertel 6415:     #
                   6416: 	    unless ($depthcount) {
1.599     albertel 6417: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6418: 		my $dir=$filename;
                   6419: 		$dir=~s|[^/]*$||;
                   6420: 		$location=&filelocation($dir,$location);
1.736     albertel 6421: 		my $rights_metadata =
                   6422: 		    &metadata($uri,'keys',$location,'_rights',
                   6423: 			      $depthcount+1);
                   6424: 		foreach my $rights (split(',',$rights_metadata)) {
                   6425: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6426: 		    $metathesekeys{$rights}=1;
1.339     albertel 6427: 		}
                   6428: 	    }
                   6429: 	}
1.737     albertel 6430: 	# uniqifiy package listing
                   6431: 	my %seen;
                   6432: 	my @uniq_packages =
                   6433: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6434: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6435: 
                   6436: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6437: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6438: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6439: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6440: # this is the end of "was not already recently cached
1.71      www      6441:     }
1.599     albertel 6442:     return $metaentry{':'.$what};
1.261     albertel 6443: }
                   6444: 
1.488     albertel 6445: sub metadata_create_package_def {
1.483     albertel 6446:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6447:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6448:     if ($subp eq 'default') { next; }
                   6449:     
1.599     albertel 6450:     if (defined($metaentry{':packages'})) {
                   6451: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6452:     } else {
1.599     albertel 6453: 	$metaentry{':packages'}=$package;
1.483     albertel 6454:     }
                   6455:     my $value=$packagetab{$key};
                   6456:     my $unikey;
                   6457:     $unikey='parameter_0_'.$name;
1.599     albertel 6458:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6459:     $$metathesekeys{$unikey}=1;
1.599     albertel 6460:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6461: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6462:     }
1.599     albertel 6463:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6464: 	$metaentry{':'.$unikey}=
                   6465: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6466:     }
                   6467: }
                   6468: 
1.261     albertel 6469: sub metadata_generate_part0 {
                   6470:     my ($metadata,$metacache,$uri) = @_;
                   6471:     my %allnames;
1.737     albertel 6472:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6473: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6474: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6475: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6476: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6477: 	    $allnames{$name}=$part;
                   6478: 	  }
                   6479: 	}
                   6480:     }
                   6481:     foreach my $name (keys(%allnames)) {
                   6482:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6483:       my $key=":parameter_0_$name";
1.261     albertel 6484:       $$metacache{"$key.part"}='0';
                   6485:       $$metacache{"$key.name"}=$name;
1.428     albertel 6486:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6487: 					   $allnames{$name}.'_'.$name.
                   6488: 					   '.type'};
1.428     albertel 6489:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6490: 			     '.display'};
1.644     www      6491:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6492:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6493:       $$metacache{"$key.display"}=$olddis;
                   6494:     }
1.71      www      6495: }
                   6496: 
1.764     albertel 6497: # ------------------------------------------------------ Devalidate title cache
                   6498: 
                   6499: sub devalidate_title_cache {
                   6500:     my ($url)=@_;
                   6501:     if (!$env{'request.course.id'}) { return; }
                   6502:     my $symb=&symbread($url);
                   6503:     if (!$symb) { return; }
                   6504:     my $key=$env{'request.course.id'}."\0".$symb;
                   6505:     &devalidate_cache_new('title',$key);
                   6506: }
                   6507: 
1.301     www      6508: # ------------------------------------------------- Get the title of a resource
                   6509: 
                   6510: sub gettitle {
                   6511:     my $urlsymb=shift;
                   6512:     my $symb=&symbread($urlsymb);
1.534     albertel 6513:     if ($symb) {
1.620     albertel 6514: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6515: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6516: 	if (defined($cached)) { 
                   6517: 	    return $result;
                   6518: 	}
1.534     albertel 6519: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6520: 	my $title='';
                   6521: 	my %bighash;
1.620     albertel 6522: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6523: 		&GDBM_READER(),0640)) {
                   6524: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6525: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6526: 	    untie %bighash;
                   6527: 	}
                   6528: 	$title=~s/\&colon\;/\:/gs;
                   6529: 	if ($title) {
1.599     albertel 6530: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6531: 	}
                   6532: 	$urlsymb=$url;
                   6533:     }
                   6534:     my $title=&metadata($urlsymb,'title');
                   6535:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6536:     return $title;
1.301     www      6537: }
1.613     albertel 6538: 
1.614     albertel 6539: sub get_slot {
                   6540:     my ($which,$cnum,$cdom)=@_;
                   6541:     if (!$cnum || !$cdom) {
1.790     albertel 6542: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6543: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6544: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6545:     }
1.703     albertel 6546:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6547:     my %slotinfo;
                   6548:     if (exists($remembered{$key})) {
                   6549: 	$slotinfo{$which} = $remembered{$key};
                   6550:     } else {
                   6551: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6552: 	&Apache::lonhomework::showhash(%slotinfo);
                   6553: 	my ($tmp)=keys(%slotinfo);
                   6554: 	if ($tmp=~/^error:/) { return (); }
                   6555: 	$remembered{$key} = $slotinfo{$which};
                   6556:     }
1.616     albertel 6557:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6558: 	return %{$slotinfo{$which}};
                   6559:     }
                   6560:     return $slotinfo{$which};
1.614     albertel 6561: }
1.31      www      6562: # ------------------------------------------------- Update symbolic store links
                   6563: 
                   6564: sub symblist {
                   6565:     my ($mapname,%newhash)=@_;
1.438     www      6566:     $mapname=&deversion(&declutter($mapname));
1.31      www      6567:     my %hash;
1.620     albertel 6568:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6569:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6570:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6571: 	    foreach my $url (keys %newhash) {
                   6572: 		next if ($url eq 'last_known'
                   6573: 			 && $env{'form.no_update_last_known'});
                   6574: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6575: 						    $newhash{$url}->[1],
                   6576: 						    $newhash{$url}->[0]);
1.191     harris41 6577:             }
1.31      www      6578:             if (untie(%hash)) {
                   6579: 		return 'ok';
                   6580:             }
                   6581:         }
                   6582:     }
                   6583:     return 'error';
1.212     www      6584: }
                   6585: 
                   6586: # --------------------------------------------------------------- Verify a symb
                   6587: 
                   6588: sub symbverify {
1.510     www      6589:     my ($symb,$thisurl)=@_;
                   6590:     my $thisfn=$thisurl;
1.439     www      6591:     $thisfn=&declutter($thisfn);
1.215     www      6592: # direct jump to resource in page or to a sequence - will construct own symbs
                   6593:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6594: # check URL part
1.409     www      6595:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6596: 
1.431     www      6597:     unless ($url eq $thisfn) { return 0; }
1.213     www      6598: 
1.216     www      6599:     $symb=&symbclean($symb);
1.510     www      6600:     $thisurl=&deversion($thisurl);
1.439     www      6601:     $thisfn=&deversion($thisfn);
1.213     www      6602: 
                   6603:     my %bighash;
                   6604:     my $okay=0;
1.431     www      6605: 
1.620     albertel 6606:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6607:                             &GDBM_READER(),0640)) {
1.510     www      6608:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6609:         unless ($ids) { 
1.510     www      6610:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6611:         }
                   6612:         if ($ids) {
                   6613: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6614: 	    foreach my $id (split(/\,/,$ids)) {
                   6615: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6616:                if (
                   6617:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6618:    eq $symb) { 
1.620     albertel 6619: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6620: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6621: 		       $okay=1; 
                   6622: 		   }
                   6623: 	       }
1.216     www      6624: 	   }
                   6625:         }
1.213     www      6626: 	untie(%bighash);
                   6627:     }
                   6628:     return $okay;
1.31      www      6629: }
                   6630: 
1.210     www      6631: # --------------------------------------------------------------- Clean-up symb
                   6632: 
                   6633: sub symbclean {
                   6634:     my $symb=shift;
1.568     albertel 6635:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6636: # remove version from map
                   6637:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6638: 
1.210     www      6639: # remove version from URL
                   6640:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6641: 
1.507     www      6642: # remove wrapper
                   6643: 
1.510     www      6644:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6645:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6646:     return $symb;
1.409     www      6647: }
                   6648: 
                   6649: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6650: 
                   6651: sub encode_symb {
                   6652:     my ($map,$resid,$url)=@_;
                   6653:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6654: }
1.409     www      6655: 
                   6656: sub decode_symb {
1.568     albertel 6657:     my $symb=shift;
                   6658:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6659:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6660:     return (&fixversion($map),$resid,&fixversion($url));
                   6661: }
                   6662: 
                   6663: sub fixversion {
                   6664:     my $fn=shift;
1.609     banghart 6665:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6666:     my %bighash;
                   6667:     my $uri=&clutter($fn);
1.620     albertel 6668:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6669: # is this cached?
1.599     albertel 6670:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6671:     if (defined($cached)) { return $result; }
                   6672: # unfortunately not cached, or expired
1.620     albertel 6673:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6674: 	    &GDBM_READER(),0640)) {
                   6675:  	if ($bighash{'version_'.$uri}) {
                   6676:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6677:  	    unless (($version eq 'mostrecent') || 
                   6678: 		    ($version==&getversion($uri))) {
1.440     www      6679:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6680:  	    }
                   6681:  	}
                   6682:  	untie %bighash;
1.413     www      6683:     }
1.599     albertel 6684:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6685: }
                   6686: 
                   6687: sub deversion {
                   6688:     my $url=shift;
                   6689:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6690:     return $url;
1.210     www      6691: }
                   6692: 
1.31      www      6693: # ------------------------------------------------------ Return symb list entry
                   6694: 
                   6695: sub symbread {
1.249     www      6696:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6697:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6698:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6699: # no filename provided? try from environment
1.44      www      6700:     unless ($thisfn) {
1.620     albertel 6701:         if ($env{'request.symb'}) {
                   6702: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6703: 	}
1.620     albertel 6704: 	$thisfn=$env{'request.filename'};
1.44      www      6705:     }
1.569     albertel 6706:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6707: # is that filename actually a symb? Verify, clean, and return
                   6708:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6709: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6710: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6711: 	}
1.242     www      6712:     }
1.44      www      6713:     $thisfn=declutter($thisfn);
1.31      www      6714:     my %hash;
1.37      www      6715:     my %bighash;
                   6716:     my $syval='';
1.620     albertel 6717:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6718:         my $targetfn = $thisfn;
1.609     banghart 6719:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6720:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6721:         }
1.687     albertel 6722: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6723: 	    $targetfn=$1;
                   6724: 	}
1.620     albertel 6725:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6726:                       &GDBM_READER(),0640)) {
1.481     raeburn  6727: 	    $syval=$hash{$targetfn};
1.37      www      6728:             untie(%hash);
                   6729:         }
                   6730: # ---------------------------------------------------------- There was an entry
                   6731:         if ($syval) {
1.601     albertel 6732: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6733: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6734: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6735: 		    #return $env{$cache_str}='';
1.601     albertel 6736: 		#}    
                   6737: 		#$syval.=$1;
                   6738: 	    #}
1.37      www      6739:         } else {
                   6740: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6741:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6742:                             &GDBM_READER(),0640)) {
1.37      www      6743: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6744:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6745:               unless ($ids) { 
                   6746:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6747:               }
                   6748:               unless ($ids) {
                   6749: # alias?
                   6750: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6751:               }
1.37      www      6752:               if ($ids) {
                   6753: # ------------------------------------------------------------------- Has ID(s)
                   6754:                  my @possibilities=split(/\,/,$ids);
1.39      www      6755:                  if ($#possibilities==0) {
                   6756: # ----------------------------------------------- There is only one possibility
1.37      www      6757: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6758: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6759: 						    $resid,$thisfn);
1.249     www      6760:                  } elsif (!$donotrecurse) {
1.39      www      6761: # ------------------------------------------ There is more than one possibility
                   6762:                      my $realpossible=0;
1.800     albertel 6763:                      foreach my $id (@possibilities) {
                   6764: 			 my $file=$bighash{'src_'.$id};
1.39      www      6765:                          if (&allowed('bre',$file)) {
1.800     albertel 6766:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6767:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6768: 				$realpossible++;
1.626     albertel 6769:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6770: 						    $resid,$thisfn);
1.39      www      6771:                             }
                   6772: 			 }
1.191     harris41 6773:                      }
1.39      www      6774: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6775:                  } else {
                   6776:                      $syval='';
1.37      www      6777:                  }
                   6778: 	      }
                   6779:               untie(%bighash)
1.481     raeburn  6780:            }
1.31      www      6781:         }
1.62      www      6782:         if ($syval) {
1.620     albertel 6783: 	    return $env{$cache_str}=$syval;
1.62      www      6784:         }
1.31      www      6785:     }
1.44      www      6786:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6787:     return $env{$cache_str}='';
1.31      www      6788: }
                   6789: 
                   6790: # ---------------------------------------------------------- Return random seed
                   6791: 
1.32      www      6792: sub numval {
                   6793:     my $txt=shift;
                   6794:     $txt=~tr/A-J/0-9/;
                   6795:     $txt=~tr/a-j/0-9/;
                   6796:     $txt=~tr/K-T/0-9/;
                   6797:     $txt=~tr/k-t/0-9/;
                   6798:     $txt=~tr/U-Z/0-5/;
                   6799:     $txt=~tr/u-z/0-5/;
                   6800:     $txt=~s/\D//g;
1.564     albertel 6801:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6802:     return int($txt);
1.368     albertel 6803: }
                   6804: 
1.484     albertel 6805: sub numval2 {
                   6806:     my $txt=shift;
                   6807:     $txt=~tr/A-J/0-9/;
                   6808:     $txt=~tr/a-j/0-9/;
                   6809:     $txt=~tr/K-T/0-9/;
                   6810:     $txt=~tr/k-t/0-9/;
                   6811:     $txt=~tr/U-Z/0-5/;
                   6812:     $txt=~tr/u-z/0-5/;
                   6813:     $txt=~s/\D//g;
                   6814:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6815:     my $total;
                   6816:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6817:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6818:     return int($total);
                   6819: }
                   6820: 
1.575     albertel 6821: sub numval3 {
                   6822:     use integer;
                   6823:     my $txt=shift;
                   6824:     $txt=~tr/A-J/0-9/;
                   6825:     $txt=~tr/a-j/0-9/;
                   6826:     $txt=~tr/K-T/0-9/;
                   6827:     $txt=~tr/k-t/0-9/;
                   6828:     $txt=~tr/U-Z/0-5/;
                   6829:     $txt=~tr/u-z/0-5/;
                   6830:     $txt=~s/\D//g;
                   6831:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6832:     my $total;
                   6833:     foreach my $val (@txts) { $total+=$val; }
                   6834:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6835:     return $total;
                   6836: }
                   6837: 
1.675     albertel 6838: sub digest {
                   6839:     my ($data)=@_;
                   6840:     my $digest=&Digest::MD5::md5($data);
                   6841:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6842:     my ($e,$f);
                   6843:     {
                   6844:         use integer;
                   6845:         $e=($a+$b);
                   6846:         $f=($c+$d);
                   6847:         if ($_64bit) {
                   6848:             $e=(($e<<32)>>32);
                   6849:             $f=(($f<<32)>>32);
                   6850:         }
                   6851:     }
                   6852:     if (wantarray) {
                   6853: 	return ($e,$f);
                   6854:     } else {
                   6855: 	my $g;
                   6856: 	{
                   6857: 	    use integer;
                   6858: 	    $g=($e+$f);
                   6859: 	    if ($_64bit) {
                   6860: 		$g=(($g<<32)>>32);
                   6861: 	    }
                   6862: 	}
                   6863: 	return $g;
                   6864:     }
                   6865: }
                   6866: 
1.368     albertel 6867: sub latest_rnd_algorithm_id {
1.675     albertel 6868:     return '64bit5';
1.366     albertel 6869: }
1.32      www      6870: 
1.503     albertel 6871: sub get_rand_alg {
                   6872:     my ($courseid)=@_;
1.790     albertel 6873:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6874:     if ($courseid) {
1.620     albertel 6875: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6876:     }
                   6877:     return &latest_rnd_algorithm_id();
                   6878: }
                   6879: 
1.562     albertel 6880: sub validCODE {
                   6881:     my ($CODE)=@_;
                   6882:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6883:     return 0;
                   6884: }
                   6885: 
1.491     albertel 6886: sub getCODE {
1.620     albertel 6887:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6888:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6889: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6890: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6891: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6892:     }
                   6893:     return undef;
                   6894: }
                   6895: 
1.31      www      6896: sub rndseed {
1.155     albertel 6897:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6898: 
1.790     albertel 6899:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6900:     if (!$symb) {
1.366     albertel 6901: 	unless ($symb=$wsymb) { return time; }
                   6902:     }
                   6903:     if (!$courseid) { $courseid=$wcourseid; }
                   6904:     if (!$domain) { $domain=$wdomain; }
                   6905:     if (!$username) { $username=$wusername }
1.503     albertel 6906:     my $which=&get_rand_alg();
1.803     albertel 6907: 
1.491     albertel 6908:     if (defined(&getCODE())) {
1.675     albertel 6909: 	if ($which eq '64bit5') {
                   6910: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6911: 	} elsif ($which eq '64bit4') {
1.575     albertel 6912: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6913: 	} else {
                   6914: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6915: 	}
1.675     albertel 6916:     } elsif ($which eq '64bit5') {
                   6917: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6918:     } elsif ($which eq '64bit4') {
                   6919: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6920:     } elsif ($which eq '64bit3') {
                   6921: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6922:     } elsif ($which eq '64bit2') {
                   6923: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6924:     } elsif ($which eq '64bit') {
                   6925: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6926:     }
                   6927:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6928: }
                   6929: 
                   6930: sub rndseed_32bit {
                   6931:     my ($symb,$courseid,$domain,$username)=@_;
                   6932:     {
                   6933: 	use integer;
                   6934: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6935: 	my $symbseed=numval($symb) << 22;
                   6936: 	my $namechck=unpack("%32C*",$username) << 17;
                   6937: 	my $nameseed=numval($username) << 12;
                   6938: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6939: 	my $courseseed=unpack("%32C*",$courseid);
                   6940: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6941: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6942: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6943: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6944: 	return $num;
                   6945:     }
                   6946: }
                   6947: 
                   6948: sub rndseed_64bit {
                   6949:     my ($symb,$courseid,$domain,$username)=@_;
                   6950:     {
                   6951: 	use integer;
                   6952: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6953: 	my $symbseed=numval($symb) << 10;
                   6954: 	my $namechck=unpack("%32S*",$username);
                   6955: 	
                   6956: 	my $nameseed=numval($username) << 21;
                   6957: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6958: 	my $courseseed=unpack("%32S*",$courseid);
                   6959: 	
                   6960: 	my $num1=$symbchck+$symbseed+$namechck;
                   6961: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6962: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6963: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6964: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6965: 	return "$num1,$num2";
1.155     albertel 6966:     }
1.366     albertel 6967: }
                   6968: 
1.443     albertel 6969: sub rndseed_64bit2 {
                   6970:     my ($symb,$courseid,$domain,$username)=@_;
                   6971:     {
                   6972: 	use integer;
                   6973: 	# strings need to be an even # of cahracters long, it it is odd the
                   6974:         # last characters gets thrown away
                   6975: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6976: 	my $symbseed=numval($symb) << 10;
                   6977: 	my $namechck=unpack("%32S*",$username.' ');
                   6978: 	
                   6979: 	my $nameseed=numval($username) << 21;
1.501     albertel 6980: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6981: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6982: 	
                   6983: 	my $num1=$symbchck+$symbseed+$namechck;
                   6984: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6985: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6986: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6987: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6988: 	return "$num1,$num2";
                   6989:     }
                   6990: }
                   6991: 
                   6992: sub rndseed_64bit3 {
                   6993:     my ($symb,$courseid,$domain,$username)=@_;
                   6994:     {
                   6995: 	use integer;
                   6996: 	# strings need to be an even # of cahracters long, it it is odd the
                   6997:         # last characters gets thrown away
                   6998: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6999: 	my $symbseed=numval2($symb) << 10;
                   7000: 	my $namechck=unpack("%32S*",$username.' ');
                   7001: 	
                   7002: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7003: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7004: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7005: 	
                   7006: 	my $num1=$symbchck+$symbseed+$namechck;
                   7007: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7008: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7009: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7010: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7011: 	
1.503     albertel 7012: 	return "$num1:$num2";
1.443     albertel 7013:     }
                   7014: }
                   7015: 
1.575     albertel 7016: sub rndseed_64bit4 {
                   7017:     my ($symb,$courseid,$domain,$username)=@_;
                   7018:     {
                   7019: 	use integer;
                   7020: 	# strings need to be an even # of cahracters long, it it is odd the
                   7021:         # last characters gets thrown away
                   7022: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7023: 	my $symbseed=numval3($symb) << 10;
                   7024: 	my $namechck=unpack("%32S*",$username.' ');
                   7025: 	
                   7026: 	my $nameseed=numval3($username) << 21;
                   7027: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7028: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7029: 	
                   7030: 	my $num1=$symbchck+$symbseed+$namechck;
                   7031: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7032: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7033: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7034: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7035: 	
                   7036: 	return "$num1:$num2";
                   7037:     }
                   7038: }
                   7039: 
1.675     albertel 7040: sub rndseed_64bit5 {
                   7041:     my ($symb,$courseid,$domain,$username)=@_;
                   7042:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7043:     return "$num1:$num2";
                   7044: }
                   7045: 
1.366     albertel 7046: sub rndseed_CODE_64bit {
                   7047:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7048:     {
1.366     albertel 7049: 	use integer;
1.443     albertel 7050: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7051: 	my $symbseed=numval2($symb);
1.491     albertel 7052: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7053: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7054: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7055: 	my $num1=$symbseed+$CODEchck;
                   7056: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7057: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7058: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7059: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7060: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7061: 	return "$num1:$num2";
1.366     albertel 7062:     }
                   7063: }
                   7064: 
1.575     albertel 7065: sub rndseed_CODE_64bit4 {
                   7066:     my ($symb,$courseid,$domain,$username)=@_;
                   7067:     {
                   7068: 	use integer;
                   7069: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7070: 	my $symbseed=numval3($symb);
                   7071: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7072: 	my $CODEseed=numval3(&getCODE());
                   7073: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7074: 	my $num1=$symbseed+$CODEchck;
                   7075: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7076: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7077: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7078: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7079: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7080: 	return "$num1:$num2";
                   7081:     }
                   7082: }
                   7083: 
1.675     albertel 7084: sub rndseed_CODE_64bit5 {
                   7085:     my ($symb,$courseid,$domain,$username)=@_;
                   7086:     my $code = &getCODE();
                   7087:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7088:     return "$num1:$num2";
                   7089: }
                   7090: 
1.366     albertel 7091: sub setup_random_from_rndseed {
                   7092:     my ($rndseed)=@_;
1.503     albertel 7093:     if ($rndseed =~/([,:])/) {
                   7094: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7095: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7096:     } else {
                   7097: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7098:     }
1.36      albertel 7099: }
                   7100: 
1.474     albertel 7101: sub latest_receipt_algorithm_id {
1.835     albertel 7102:     return 'receipt3';
1.474     albertel 7103: }
                   7104: 
1.480     www      7105: sub recunique {
                   7106:     my $fucourseid=shift;
                   7107:     my $unique;
1.835     albertel 7108:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7109: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7110: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7111:     } else {
                   7112: 	$unique=$perlvar{'lonReceipt'};
                   7113:     }
                   7114:     return unpack("%32C*",$unique);
                   7115: }
                   7116: 
                   7117: sub recprefix {
                   7118:     my $fucourseid=shift;
                   7119:     my $prefix;
1.835     albertel 7120:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7121: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7122: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7123:     } else {
                   7124: 	$prefix=$perlvar{'lonHostID'};
                   7125:     }
                   7126:     return unpack("%32C*",$prefix);
                   7127: }
                   7128: 
1.76      www      7129: sub ireceipt {
1.474     albertel 7130:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7131: 
                   7132:     my $return =&recprefix($fucourseid).'-';
                   7133: 
                   7134:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7135: 	$env{'request.state'} eq 'construct') {
                   7136: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7137: 	return $return;
                   7138:     }
                   7139: 
1.76      www      7140:     my $cuname=unpack("%32C*",$funame);
                   7141:     my $cudom=unpack("%32C*",$fudom);
                   7142:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7143:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7144:     my $cunique=&recunique($fucourseid);
1.474     albertel 7145:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7146:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7147: 
1.790     albertel 7148: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7149: 			       
                   7150: 	$return.= ($cunique%$cuname+
                   7151: 		   $cunique%$cudom+
                   7152: 		   $cusymb%$cuname+
                   7153: 		   $cusymb%$cudom+
                   7154: 		   $cucourseid%$cuname+
                   7155: 		   $cucourseid%$cudom+
                   7156: 		   $cpart%$cuname+
                   7157: 		   $cpart%$cudom);
                   7158:     } else {
                   7159: 	$return.= ($cunique%$cuname+
                   7160: 		   $cunique%$cudom+
                   7161: 		   $cusymb%$cuname+
                   7162: 		   $cusymb%$cudom+
                   7163: 		   $cucourseid%$cuname+
                   7164: 		   $cucourseid%$cudom);
                   7165:     }
                   7166:     return $return;
1.76      www      7167: }
                   7168: 
                   7169: sub receipt {
1.474     albertel 7170:     my ($part)=@_;
1.790     albertel 7171:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7172:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7173: }
1.260     ng       7174: 
1.790     albertel 7175: sub whichuser {
                   7176:     my ($passedsymb)=@_;
                   7177:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7178:     if (defined($env{'form.grade_symb'})) {
                   7179: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7180: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7181: 	if (!$allowed &&
                   7182: 	    exists($env{'request.course.sec'}) &&
                   7183: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7184: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7185: 			      '/'.$env{'request.course.sec'});
                   7186: 	}
                   7187: 	if ($allowed) {
                   7188: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7189: 	    $courseid=$tmp_courseid;
                   7190: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7191: 	    ($name)=&get_env_multiple('form.grade_username');
                   7192: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7193: 	}
                   7194:     }
                   7195:     if (!$passedsymb) {
                   7196: 	$symb=&symbread();
                   7197:     } else {
                   7198: 	$symb=$passedsymb;
                   7199:     }
                   7200:     $courseid=$env{'request.course.id'};
                   7201:     $domain=$env{'user.domain'};
                   7202:     $name=$env{'user.name'};
                   7203:     if ($name eq 'public' && $domain eq 'public') {
                   7204: 	if (!defined($env{'form.username'})) {
                   7205: 	    $env{'form.username'}.=time.rand(10000000);
                   7206: 	}
                   7207: 	$name.=$env{'form.username'};
                   7208:     }
                   7209:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7210: 
                   7211: }
                   7212: 
1.36      albertel 7213: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7214: # returns either the contents of the file or 
                   7215: # -1 if the file doesn't exist
1.481     raeburn  7216: #
                   7217: # if the target is a file that was uploaded via DOCS, 
                   7218: # a check will be made to see if a current copy exists on the local server,
                   7219: # if it does this will be served, otherwise a copy will be retrieved from
                   7220: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7221: # the local server.   
1.472     albertel 7222: 
1.36      albertel 7223: sub getfile {
1.538     albertel 7224:     my ($file) = @_;
1.609     banghart 7225:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7226:     &repcopy($file);
                   7227:     return &readfile($file);
                   7228: }
                   7229: 
                   7230: sub repcopy_userfile {
                   7231:     my ($file)=@_;
1.609     banghart 7232:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7233:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7234:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7235: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7236:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7237:     if (-e "$file") {
1.828     www      7238: # we already have a local copy, check it out
1.538     albertel 7239: 	my @fileinfo = stat($file);
1.828     www      7240: 	my $rtncode;
                   7241: 	my $info;
1.538     albertel 7242: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7243: 	if ($lwpresp ne 'ok') {
1.828     www      7244: # there is no such file anymore, even though we had a local copy
1.482     albertel 7245: 	    if ($rtncode eq '404') {
1.538     albertel 7246: 		unlink($file);
1.482     albertel 7247: 	    }
                   7248: 	    return -1;
                   7249: 	}
                   7250: 	if ($info < $fileinfo[9]) {
1.828     www      7251: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7252: 	    return 'ok';
1.828     www      7253: 	} else {
                   7254: # the file is outdated, get rid of it
                   7255: 	    unlink($file);
1.482     albertel 7256: 	}
1.828     www      7257:     }
                   7258: # one way or the other, at this point, we don't have the file
                   7259: # construct the correct path for the file
                   7260:     my @parts = ($cdom,$cnum); 
                   7261:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7262: 	push @parts, split(/\//,$1);
                   7263:     }
                   7264:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7265:     foreach my $part (@parts) {
                   7266: 	$path .= '/'.$part;
                   7267: 	if (!-e $path) {
                   7268: 	    mkdir($path,0770);
1.482     albertel 7269: 	}
                   7270:     }
1.828     www      7271: # now the path exists for sure
                   7272: # get a user agent
                   7273:     my $ua=new LWP::UserAgent;
                   7274:     my $transferfile=$file.'.in.transfer';
                   7275: # FIXME: this should flock
                   7276:     if (-e $transferfile) { return 'ok'; }
                   7277:     my $request;
                   7278:     $uri=~s/^\///;
1.838     albertel 7279:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7280:     my $response=$ua->request($request,$transferfile);
                   7281: # did it work?
                   7282:     if ($response->is_error()) {
                   7283: 	unlink($transferfile);
                   7284: 	&logthis("Userfile repcopy failed for $uri");
                   7285: 	return -1;
                   7286:     }
                   7287: # worked, rename the transfer file
                   7288:     rename($transferfile,$file);
1.607     raeburn  7289:     return 'ok';
1.481     raeburn  7290: }
                   7291: 
1.517     albertel 7292: sub tokenwrapper {
                   7293:     my $uri=shift;
1.552     albertel 7294:     $uri=~s|^http\://([^/]+)||;
                   7295:     $uri=~s|^/||;
1.620     albertel 7296:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7297:     my $token=$1;
1.552     albertel 7298:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7299:     if ($udom && $uname && $file) {
                   7300: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7301:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7302:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7303:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7304:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7305:     } else {
                   7306:         return '/adm/notfound.html';
                   7307:     }
                   7308: }
                   7309: 
1.828     www      7310: # call with reqtype HEAD: get last modification time
                   7311: # call with reqtype GET: get the file contents
                   7312: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7313: #
1.481     raeburn  7314: sub getuploaded {
                   7315:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7316:     $uri=~s/^\///;
1.838     albertel 7317:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7318:     my $ua=new LWP::UserAgent;
                   7319:     my $request=new HTTP::Request($reqtype,$uri);
                   7320:     my $response=$ua->request($request);
                   7321:     $$rtncode = $response->code;
1.482     albertel 7322:     if (! $response->is_success()) {
                   7323: 	return 'failed';
                   7324:     }      
                   7325:     if ($reqtype eq 'HEAD') {
1.486     www      7326: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7327:     } elsif ($reqtype eq 'GET') {
                   7328: 	$$info = $response->content;
1.472     albertel 7329:     }
1.482     albertel 7330:     return 'ok';
1.36      albertel 7331: }
                   7332: 
1.481     raeburn  7333: sub readfile {
                   7334:     my $file = shift;
                   7335:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7336:     my $fh;
                   7337:     open($fh,"<$file");
                   7338:     my $a='';
1.800     albertel 7339:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7340:     return $a;
                   7341: }
                   7342: 
1.36      albertel 7343: sub filelocation {
1.590     banghart 7344:     my ($dir,$file) = @_;
                   7345:     my $location;
                   7346:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7347: 
                   7348:     if ($file =~ m-^/adm/-) {
                   7349: 	$file=~s-^/adm/wrapper/-/-;
                   7350: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7351:     }
1.590     banghart 7352:     if ($file=~m:^/~:) { # is a contruction space reference
                   7353:         $location = $file;
                   7354:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7355:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7356: 	# is a correct contruction space reference
                   7357:         $location = $file;
1.609     banghart 7358:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7359:         my ($udom,$uname,$filename)=
1.811     albertel 7360:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7361:         my $home=&homeserver($uname,$udom);
                   7362:         my $is_me=0;
                   7363:         my @ids=&current_machine_ids();
                   7364:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7365:         if ($is_me) {
1.740     www      7366:   	    $location=&propath($udom,$uname).
1.590     banghart 7367:   	      '/userfiles/'.$filename;
                   7368:         } else {
                   7369:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7370:   	      $udom.'/'.$uname.'/'.$filename;
                   7371:         }
                   7372:     } else {
                   7373:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7374:         $file=~s:^/res/:/:;
                   7375:         if ( !( $file =~ m:^/:) ) {
                   7376:             $location = $dir. '/'.$file;
                   7377:         } else {
                   7378:             $location = '/home/httpd/html/res'.$file;
                   7379:         }
1.59      albertel 7380:     }
1.590     banghart 7381:     $location=~s://+:/:g; # remove duplicate /
                   7382:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7383:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7384:     return $location;
1.46      www      7385: }
1.36      albertel 7386: 
1.46      www      7387: sub hreflocation {
                   7388:     my ($dir,$file)=@_;
1.460     albertel 7389:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7390: 	$file=filelocation($dir,$file);
1.700     albertel 7391:     } elsif ($file=~m-^/adm/-) {
                   7392: 	$file=~s-^/adm/wrapper/-/-;
                   7393: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7394:     }
                   7395:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7396: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7397:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7398: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7399:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7400: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7401: 	    -/uploaded/$1/$2/-x;
1.46      www      7402:     }
1.462     albertel 7403:     return $file;
1.465     albertel 7404: }
                   7405: 
                   7406: sub current_machine_domains {
1.838     albertel 7407:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7408:     my @domains;
1.838     albertel 7409:     my %hostname = &all_hostnames();
1.465     albertel 7410:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7411: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7412: 	if ($hostname eq $name) {
1.844     albertel 7413: 	    push(@domains,&host_domain($id));
1.465     albertel 7414: 	}
                   7415:     }
                   7416:     return @domains;
                   7417: }
                   7418: 
                   7419: sub current_machine_ids {
1.838     albertel 7420:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7421:     my @ids;
1.838     albertel 7422:     my %hostname = &all_hostnames();
1.465     albertel 7423:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7424: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7425: 	if ($hostname eq $name) {
                   7426: 	    push(@ids,$id);
                   7427: 	}
                   7428:     }
                   7429:     return @ids;
1.31      www      7430: }
                   7431: 
1.824     raeburn  7432: sub additional_machine_domains {
                   7433:     my @domains;
                   7434:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7435:     while( my $line = <$fh>) {
                   7436:         $line =~ s/\s//g;
                   7437:         push(@domains,$line);
                   7438:     }
                   7439:     return @domains;
                   7440: }
                   7441: 
                   7442: sub default_login_domain {
                   7443:     my $domain = $perlvar{'lonDefDomain'};
                   7444:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7445:     foreach my $posdom (&current_machine_domains(),
                   7446:                         &additional_machine_domains()) {
                   7447:         if (lc($posdom) eq lc($testdomain)) {
                   7448:             $domain=$posdom;
                   7449:             last;
                   7450:         }
                   7451:     }
                   7452:     return $domain;
                   7453: }
                   7454: 
1.31      www      7455: # ------------------------------------------------------------- Declutters URLs
                   7456: 
                   7457: sub declutter {
                   7458:     my $thisfn=shift;
1.569     albertel 7459:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7460:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7461:     $thisfn=~s/^\///;
1.697     albertel 7462:     $thisfn=~s|^adm/wrapper/||;
                   7463:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7464:     $thisfn=~s/^res\///;
1.235     www      7465:     $thisfn=~s/\?.+$//;
1.268     www      7466:     return $thisfn;
                   7467: }
                   7468: 
                   7469: # ------------------------------------------------------------- Clutter up URLs
                   7470: 
                   7471: sub clutter {
                   7472:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7473:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7474:        $thisfn='/res'.$thisfn; 
                   7475:     }
1.694     albertel 7476:     if ($thisfn !~m|/adm|) {
1.695     albertel 7477: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7478: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7479: 	} else {
                   7480: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7481: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7482: 	    if ($embstyle eq 'ssi'
                   7483: 		|| ($embstyle eq 'hdn')
                   7484: 		|| ($embstyle eq 'rat')
                   7485: 		|| ($embstyle eq 'prv')
                   7486: 		|| ($embstyle eq 'ign')) {
                   7487: 		#do nothing with these
                   7488: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7489: 		|| ($embstyle eq 'emb')
                   7490: 		|| ($embstyle eq 'wrp')) {
                   7491: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7492: 	    } elsif ($embstyle eq 'unk'
                   7493: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7494: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7495: 	    } else {
1.718     www      7496: #		&logthis("Got a blank emb style");
1.695     albertel 7497: 	    }
1.694     albertel 7498: 	}
                   7499:     }
1.31      www      7500:     return $thisfn;
1.12      www      7501: }
                   7502: 
1.787     albertel 7503: sub clutter_with_no_wrapper {
                   7504:     my $uri = &clutter(shift);
                   7505:     if ($uri =~ m-^/adm/-) {
                   7506: 	$uri =~ s-^/adm/wrapper/-/-;
                   7507: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7508:     }
                   7509:     return $uri;
                   7510: }
                   7511: 
1.557     albertel 7512: sub freeze_escape {
                   7513:     my ($value)=@_;
                   7514:     if (ref($value)) {
                   7515: 	$value=&nfreeze($value);
                   7516: 	return '__FROZEN__'.&escape($value);
                   7517:     }
                   7518:     return &escape($value);
                   7519: }
                   7520: 
1.11      www      7521: 
1.557     albertel 7522: sub thaw_unescape {
                   7523:     my ($value)=@_;
                   7524:     if ($value =~ /^__FROZEN__/) {
                   7525: 	substr($value,0,10,undef);
                   7526: 	$value=&unescape($value);
                   7527: 	return &thaw($value);
                   7528:     }
                   7529:     return &unescape($value);
                   7530: }
                   7531: 
1.436     albertel 7532: sub correct_line_ends {
                   7533:     my ($result)=@_;
                   7534:     $$result =~s/\r\n/\n/mg;
                   7535:     $$result =~s/\r/\n/mg;
1.415     albertel 7536: }
1.1       albertel 7537: # ================================================================ Main Program
                   7538: 
1.184     www      7539: sub goodbye {
1.204     albertel 7540:    &logthis("Starting Shut down");
1.443     albertel 7541: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7542:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7543: #converted
1.599     albertel 7544: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7545:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7546: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7547: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7548: #1.1 only
1.599     albertel 7549: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7550: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7551: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7552: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7553:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7554:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7555:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7556:    &flushcourselogs();
                   7557:    &logthis("Shutting down");
                   7558: }
                   7559: 
1.179     www      7560: BEGIN {
1.228     harris41 7561: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7562:     unless ($readit) {
1.217     harris41 7563: {
1.781     raeburn  7564:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7565:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7566: }
1.1       albertel 7567: 
1.327     albertel 7568: # ------------------------------------------------------------ Read domain file
                   7569: {
                   7570:     %domaindescription = ();
                   7571:     %domain_auth_def = ();
                   7572:     %domain_auth_arg_def = ();
1.448     albertel 7573:     my $fh;
                   7574:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7575: 	while (my $line = <$fh>) {
                   7576:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7577: #           next if /^\#/;
1.801     foxr     7578:            chomp $line;
1.403     www      7579:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7580: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7581: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7582:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7583: 	   $domaindescription{$domain}=$domain_description;
                   7584: 	   $domain_lang_def{$domain}=$def_lang;
                   7585: 	   $domain_city{$domain}=$city;
                   7586: 	   $domain_longi{$domain}=$longi;
                   7587: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7588:            $domain_primary{$domain}=$primary;
1.403     www      7589: 
1.448     albertel 7590:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7591: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7592: 	}
1.327     albertel 7593:     }
1.448     albertel 7594:     close ($fh);
1.327     albertel 7595: }
                   7596: 
                   7597: 
1.1       albertel 7598: # ------------------------------------------------------------- Read hosts file
                   7599: {
1.838     albertel 7600:     my %hostname;
1.844     albertel 7601:     my %hostdom;
1.845   ! albertel 7602:     my %libserv;
1.448     albertel 7603:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7604: 
                   7605:     while (my $configline=<$config>) {
1.303     matthew  7606:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7607:        chomp($configline);
1.595     albertel 7608:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7609:        $name=~s/\s//g;
1.595     albertel 7610:        if ($id && $domain && $role && $name) {
1.252     albertel 7611: 	 $hostname{$id}=$name;
                   7612: 	 $hostdom{$id}=$domain;
                   7613: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7614:        }
1.1       albertel 7615:     }
1.448     albertel 7616:     close($config);
1.619     albertel 7617:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7618:     #&get_iphost();
1.838     albertel 7619: 
                   7620:     sub hostname {
                   7621: 	my ($lonid) = @_;
                   7622: 	return $hostname{$lonid};
                   7623:     }
1.845   ! albertel 7624: 
1.838     albertel 7625:     sub all_hostnames {
                   7626: 	return %hostname;
                   7627:     }
1.845   ! albertel 7628: 
        !          7629:     sub is_library {
        !          7630: 	return exists($libserv{$_[0]});
        !          7631:     }
        !          7632: 
        !          7633:     sub all_library {
        !          7634: 	return %libserv;
        !          7635:     }
        !          7636: 
1.841     albertel 7637:     sub get_servers {
                   7638: 	my ($domain,$type) = @_;
                   7639: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7640: 	                                          : %hostname;
                   7641: 	my %result;
1.842     albertel 7642: 	if (ref($domain) eq 'ARRAY') {
                   7643: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7644: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7645: 		    $result{$host} = $hostname;
                   7646: 		}
                   7647: 	    }
                   7648: 	} else {
                   7649: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7650: 		if ($hostdom{$host} eq $domain) {
                   7651: 		    $result{$host} = $hostname;
                   7652: 		}
1.841     albertel 7653: 	    }
                   7654: 	}
                   7655: 	return %result;
                   7656:     }
1.845   ! albertel 7657: 
1.844     albertel 7658:     sub host_domain {
                   7659: 	my ($lonid) = @_;
                   7660: 	return $hostdom{$lonid};
                   7661:     }
                   7662: 
1.841     albertel 7663:     sub all_domains {
                   7664: 	my %seen;
                   7665: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7666: 	return @uniq;
                   7667:     }
1.1       albertel 7668: }
                   7669: 
1.839     albertel 7670: sub get_hosts_from_ip {
                   7671:     my ($ip) = @_;
                   7672:     my %iphosts = &get_iphost();
                   7673:     if (ref($iphosts{$ip})) {
                   7674: 	return @{$iphosts{$ip}};
                   7675:     }
                   7676:     return;
                   7677: }
                   7678: 
1.598     albertel 7679: sub get_iphost {
                   7680:     if (%iphost) { return %iphost; }
1.653     albertel 7681:     my %name_to_ip;
1.838     albertel 7682:     my %hostname = &all_hostnames();
1.598     albertel 7683:     foreach my $id (keys(%hostname)) {
                   7684: 	my $name=$hostname{$id};
1.653     albertel 7685: 	my $ip;
                   7686: 	if (!exists($name_to_ip{$name})) {
                   7687: 	    $ip = gethostbyname($name);
                   7688: 	    if (!$ip || length($ip) ne 4) {
1.826     www      7689: 		&logthis("Skipping host $id name $name no IP found");
1.653     albertel 7690: 		next;
                   7691: 	    }
                   7692: 	    $ip=inet_ntoa($ip);
                   7693: 	    $name_to_ip{$name} = $ip;
                   7694: 	} else {
                   7695: 	    $ip = $name_to_ip{$name};
1.598     albertel 7696: 	}
                   7697: 	push(@{$iphost{$ip}},$id);
                   7698:     }
                   7699:     return %iphost;
                   7700: }
                   7701: 
1.1       albertel 7702: # ------------------------------------------------------ Read spare server file
                   7703: {
1.448     albertel 7704:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7705: 
                   7706:     while (my $configline=<$config>) {
                   7707:        chomp($configline);
1.284     matthew  7708:        if ($configline) {
1.784     albertel 7709: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7710: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7711: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7712:        }
                   7713:     }
1.448     albertel 7714:     close($config);
1.1       albertel 7715: }
1.11      www      7716: # ------------------------------------------------------------ Read permissions
                   7717: {
1.448     albertel 7718:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7719: 
                   7720:     while (my $configline=<$config>) {
1.448     albertel 7721: 	chomp($configline);
                   7722: 	if ($configline) {
                   7723: 	    my ($role,$perm)=split(/ /,$configline);
                   7724: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7725: 	}
1.11      www      7726:     }
1.448     albertel 7727:     close($config);
1.11      www      7728: }
                   7729: 
                   7730: # -------------------------------------------- Read plain texts for permissions
                   7731: {
1.448     albertel 7732:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7733: 
                   7734:     while (my $configline=<$config>) {
1.448     albertel 7735: 	chomp($configline);
                   7736: 	if ($configline) {
1.742     raeburn  7737: 	    my ($short,@plain)=split(/:/,$configline);
                   7738:             %{$prp{$short}} = ();
                   7739: 	    if (@plain > 0) {
                   7740:                 $prp{$short}{'std'} = $plain[0];
                   7741:                 for (my $i=1; $i<@plain; $i++) {
                   7742:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7743:                 }
                   7744:             }
1.448     albertel 7745: 	}
1.135     www      7746:     }
1.448     albertel 7747:     close($config);
1.135     www      7748: }
                   7749: 
                   7750: # ---------------------------------------------------------- Read package table
                   7751: {
1.448     albertel 7752:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7753: 
                   7754:     while (my $configline=<$config>) {
1.483     albertel 7755: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7756: 	chomp($configline);
                   7757: 	my ($short,$plain)=split(/:/,$configline);
                   7758: 	my ($pack,$name)=split(/\&/,$short);
                   7759: 	if ($plain ne '') {
                   7760: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7761: 	    $packagetab{$short}=$plain; 
                   7762: 	}
1.11      www      7763:     }
1.448     albertel 7764:     close($config);
1.329     matthew  7765: }
                   7766: 
                   7767: # ------------- set up temporary directory
                   7768: {
                   7769:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7770: 
1.11      www      7771: }
                   7772: 
1.794     albertel 7773: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7774: 				'compress_threshold'=> 20_000,
                   7775:  			        });
1.185     www      7776: 
1.281     www      7777: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7778: $dumpcount=0;
1.22      www      7779: 
1.163     harris41 7780: &logtouch();
1.672     albertel 7781: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7782: $readit=1;
1.564     albertel 7783:     {
                   7784: 	use integer;
                   7785: 	my $test=(2**32)+1;
1.568     albertel 7786: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7787: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7788:     }
1.195     www      7789: }
1.1       albertel 7790: }
1.179     www      7791: 
1.1       albertel 7792: 1;
1.191     harris41 7793: __END__
                   7794: 
1.243     albertel 7795: =pod
                   7796: 
1.191     harris41 7797: =head1 NAME
                   7798: 
1.243     albertel 7799: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7800: 
                   7801: =head1 SYNOPSIS
                   7802: 
1.243     albertel 7803: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7804: 
                   7805:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7806: 
1.243     albertel 7807: Common parameters:
                   7808: 
                   7809: =over 4
                   7810: 
                   7811: =item *
                   7812: 
                   7813: $uname : an internal username (if $cname expecting a course Id specifically)
                   7814: 
                   7815: =item *
                   7816: 
                   7817: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7818: 
                   7819: =item *
                   7820: 
                   7821: $symb : a resource instance identifier
                   7822: 
                   7823: =item *
                   7824: 
                   7825: $namespace : the name of a .db file that contains the data needed or
                   7826: being set.
                   7827: 
                   7828: =back
                   7829: 
1.394     bowersj2 7830: =head1 OVERVIEW
1.191     harris41 7831: 
1.394     bowersj2 7832: lonnet provides subroutines which interact with the
                   7833: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7834: about classes, users, and resources.
1.243     albertel 7835: 
                   7836: For many of these objects you can also use this to store data about
                   7837: them or modify them in various ways.
1.191     harris41 7838: 
1.394     bowersj2 7839: =head2 Symbs
1.191     harris41 7840: 
1.394     bowersj2 7841: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7842: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7843: map, the resource number of the resource in the map, and the URL of
                   7844: the resource itself. The latter is somewhat redundant, but might help
                   7845: if maps change.
                   7846: 
                   7847: An example is
                   7848: 
                   7849:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7850: 
                   7851: The respective map entry is
                   7852: 
                   7853:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7854:   title="Problem 2">
                   7855:  </resource>
                   7856: 
                   7857: Symbs are used by the random number generator, as well as to store and
                   7858: restore data specific to a certain instance of for example a problem.
                   7859: 
                   7860: =head2 Storing And Retrieving Data
                   7861: 
                   7862: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7863: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7864: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7865: is is the non-critical message twin of cstore. These functions are for
                   7866: handlers to store a perl hash to a user's permanent data space in an
                   7867: easy manner, and to retrieve it again on another call. It is expected
                   7868: that a handler would use this once at the beginning to retrieve data,
                   7869: and then again once at the end to send only the new data back.
                   7870: 
                   7871: The data is stored in the user's data directory on the user's
                   7872: homeserver under the ID of the course.
                   7873: 
                   7874: The hash that is returned by restore will have all of the previous
                   7875: value for all of the elements of the hash.
                   7876: 
                   7877: Example:
                   7878: 
                   7879:  #creating a hash
                   7880:  my %hash;
                   7881:  $hash{'foo'}='bar';
                   7882: 
                   7883:  #storing it
                   7884:  &Apache::lonnet::cstore(\%hash);
                   7885: 
                   7886:  #changing a value
                   7887:  $hash{'foo'}='notbar';
                   7888: 
                   7889:  #adding a new value
                   7890:  $hash{'bar'}='foo';
                   7891:  &Apache::lonnet::cstore(\%hash);
                   7892: 
                   7893:  #retrieving the hash
                   7894:  my %history=&Apache::lonnet::restore();
                   7895: 
                   7896:  #print the hash
                   7897:  foreach my $key (sort(keys(%history))) {
                   7898:    print("\%history{$key} = $history{$key}");
                   7899:  }
                   7900: 
                   7901: Will print out:
1.191     harris41 7902: 
1.394     bowersj2 7903:  %history{1:foo} = bar
                   7904:  %history{1:keys} = foo:timestamp
                   7905:  %history{1:timestamp} = 990455579
                   7906:  %history{2:bar} = foo
                   7907:  %history{2:foo} = notbar
                   7908:  %history{2:keys} = foo:bar:timestamp
                   7909:  %history{2:timestamp} = 990455580
                   7910:  %history{bar} = foo
                   7911:  %history{foo} = notbar
                   7912:  %history{timestamp} = 990455580
                   7913:  %history{version} = 2
                   7914: 
                   7915: Note that the special hash entries C<keys>, C<version> and
                   7916: C<timestamp> were added to the hash. C<version> will be equal to the
                   7917: total number of versions of the data that have been stored. The
                   7918: C<timestamp> attribute will be the UNIX time the hash was
                   7919: stored. C<keys> is available in every historical section to list which
                   7920: keys were added or changed at a specific historical revision of a
                   7921: hash.
                   7922: 
                   7923: B<Warning>: do not store the hash that restore returns directly. This
                   7924: will cause a mess since it will restore the historical keys as if the
                   7925: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7926: 
1.394     bowersj2 7927: Calling convention:
1.191     harris41 7928: 
1.394     bowersj2 7929:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7930:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7931: 
1.394     bowersj2 7932: For more detailed information, see lonnet specific documentation.
1.191     harris41 7933: 
1.394     bowersj2 7934: =head1 RETURN MESSAGES
1.191     harris41 7935: 
1.394     bowersj2 7936: =over 4
1.191     harris41 7937: 
1.394     bowersj2 7938: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7939: 
1.394     bowersj2 7940: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7941: when the connection is brought back up
1.191     harris41 7942: 
1.394     bowersj2 7943: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7944: for later delivery
1.191     harris41 7945: 
1.394     bowersj2 7946: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7947: 
1.394     bowersj2 7948: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7949: that was requested
1.191     harris41 7950: 
1.243     albertel 7951: =back
1.191     harris41 7952: 
1.243     albertel 7953: =head1 PUBLIC SUBROUTINES
1.191     harris41 7954: 
1.243     albertel 7955: =head2 Session Environment Functions
1.191     harris41 7956: 
1.243     albertel 7957: =over 4
1.191     harris41 7958: 
1.394     bowersj2 7959: =item * 
                   7960: X<appenv()>
                   7961: B<appenv(%hash)>: the value of %hash is written to
                   7962: the user envirnoment file, and will be restored for each access this
1.620     albertel 7963: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7964: process
1.191     harris41 7965: 
                   7966: =item *
1.394     bowersj2 7967: X<delenv()>
                   7968: B<delenv($regexp)>: removes all items from the session
                   7969: environment file that matches the regular expression in $regexp. The
1.620     albertel 7970: values are also delted from the current processes %env.
1.191     harris41 7971: 
1.795     albertel 7972: =item * get_env_multiple($name) 
                   7973: 
                   7974: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7975: values may be defined and end up as an array ref.
                   7976: 
                   7977: returns an array of values
                   7978: 
1.243     albertel 7979: =back
                   7980: 
                   7981: =head2 User Information
1.191     harris41 7982: 
1.243     albertel 7983: =over 4
1.191     harris41 7984: 
                   7985: =item *
1.394     bowersj2 7986: X<queryauthenticate()>
                   7987: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7988: authentication scheme
                   7989: 
                   7990: =item *
1.394     bowersj2 7991: X<authenticate()>
                   7992: B<authenticate($uname,$upass,$udom)>: try to
                   7993: authenticate user from domain's lib servers (first use the current
                   7994: one). C<$upass> should be the users password.
1.191     harris41 7995: 
                   7996: =item *
1.394     bowersj2 7997: X<homeserver()>
                   7998: B<homeserver($uname,$udom)>: find the server which has
                   7999: the user's directory and files (there must be only one), this caches
                   8000: the answer, and also caches if there is a borken connection.
1.191     harris41 8001: 
                   8002: =item *
1.394     bowersj2 8003: X<idget()>
                   8004: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8005: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8006: username, and only 1 username per ID in a specific domain) (returns
                   8007: hash: id=>name,id=>name)
1.191     harris41 8008: 
                   8009: =item *
1.394     bowersj2 8010: X<idrget()>
                   8011: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8012: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8013: 
                   8014: =item *
1.394     bowersj2 8015: X<idput()>
                   8016: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8017: 
                   8018: =item *
1.394     bowersj2 8019: X<rolesinit()>
                   8020: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8021: 
                   8022: =item *
1.551     albertel 8023: X<getsection()>
                   8024: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8025: course $cname, return section name/number or '' for "not in course"
                   8026: and '-1' for "no section"
                   8027: 
                   8028: =item *
1.394     bowersj2 8029: X<userenvironment()>
                   8030: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8031: passed in @what from the requested user's environment, returns a hash
                   8032: 
                   8033: =back
                   8034: 
                   8035: =head2 User Roles
                   8036: 
                   8037: =over 4
                   8038: 
                   8039: =item *
                   8040: 
1.810     raeburn  8041: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8042:  F: full access
                   8043:  U,I,K: authentication modes (cxx only)
                   8044:  '': forbidden
                   8045:  1: user needs to choose course
                   8046:  2: browse allowed
1.766     albertel 8047:  A: passphrase authentication needed
1.243     albertel 8048: 
                   8049: =item *
                   8050: 
                   8051: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8052: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8053: and course level
                   8054: 
                   8055: =item *
                   8056: 
                   8057: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8058: explanation of a user role term
                   8059: 
1.832     raeburn  8060: =item *
                   8061: 
1.834     albertel 8062: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
                   8063: optional.  Returns a hash of a user's roles, with keys set to
                   8064: colon-sparated $uname,$udom,and $role, and value set to
                   8065: colon-separated start and end times for the role. If no username and
                   8066: domain are specified, will default to current user/domain. Types,
                   8067: roles, and roledoms are references to arrays, of role statuses
                   8068: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
                   8069: of the roles which can be used to restrict the list if roles
                   8070: reported. If no array ref is provided for types, will default to
                   8071: return only active roles.
                   8072: 
1.243     albertel 8073: =back
                   8074: 
                   8075: =head2 User Modification
                   8076: 
                   8077: =over 4
                   8078: 
                   8079: =item *
                   8080: 
                   8081: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8082: user for the level given by URL.  Optional start and end dates (leave empty
                   8083: string or zero for "no date")
1.191     harris41 8084: 
                   8085: =item *
                   8086: 
1.243     albertel 8087: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8088: change a users, password, possible return values are: ok,
                   8089: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8090: refused
1.191     harris41 8091: 
                   8092: =item *
                   8093: 
1.243     albertel 8094: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8095: 
                   8096: =item *
                   8097: 
1.243     albertel 8098: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8099: modify user
1.191     harris41 8100: 
                   8101: =item *
                   8102: 
1.286     matthew  8103: modifystudent
                   8104: 
                   8105: modify a students enrollment and identification information.
                   8106: The course id is resolved based on the current users environment.  
                   8107: This means the envoking user must be a course coordinator or otherwise
                   8108: associated with a course.
                   8109: 
1.297     matthew  8110: This call is essentially a wrapper for lonnet::modifyuser and
                   8111: lonnet::modify_student_enrollment
1.286     matthew  8112: 
                   8113: Inputs: 
                   8114: 
                   8115: =over 4
                   8116: 
                   8117: =item B<$udom> Students loncapa domain
                   8118: 
                   8119: =item B<$uname> Students loncapa login name
                   8120: 
                   8121: =item B<$uid> Students id/student number
                   8122: 
                   8123: =item B<$umode> Students authentication mode
                   8124: 
                   8125: =item B<$upass> Students password
                   8126: 
                   8127: =item B<$first> Students first name
                   8128: 
                   8129: =item B<$middle> Students middle name
                   8130: 
                   8131: =item B<$last> Students last name
                   8132: 
                   8133: =item B<$gene> Students generation
                   8134: 
                   8135: =item B<$usec> Students section in course
                   8136: 
                   8137: =item B<$end> Unix time of the roles expiration
                   8138: 
                   8139: =item B<$start> Unix time of the roles start date
                   8140: 
                   8141: =item B<$forceid> If defined, allow $uid to be changed
                   8142: 
                   8143: =item B<$desiredhome> server to use as home server for student
                   8144: 
                   8145: =back
1.297     matthew  8146: 
                   8147: =item *
                   8148: 
                   8149: modify_student_enrollment
                   8150: 
                   8151: Change a students enrollment status in a class.  The environment variable
                   8152: 'role.request.course' must be defined for this function to proceed.
                   8153: 
                   8154: Inputs:
                   8155: 
                   8156: =over 4
                   8157: 
                   8158: =item $udom, students domain
                   8159: 
                   8160: =item $uname, students name
                   8161: 
                   8162: =item $uid, students user id
                   8163: 
                   8164: =item $first, students first name
                   8165: 
                   8166: =item $middle
                   8167: 
                   8168: =item $last
                   8169: 
                   8170: =item $gene
                   8171: 
                   8172: =item $usec
                   8173: 
                   8174: =item $end
                   8175: 
                   8176: =item $start
                   8177: 
                   8178: =back
                   8179: 
1.191     harris41 8180: 
                   8181: =item *
                   8182: 
1.243     albertel 8183: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8184: custom role; give a custom role to a user for the level given by URL.  Specify
                   8185: name and domain of role author, and role name
1.191     harris41 8186: 
                   8187: =item *
                   8188: 
1.243     albertel 8189: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8190: 
                   8191: =item *
                   8192: 
1.243     albertel 8193: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8194: 
                   8195: =back
                   8196: 
                   8197: =head2 Course Infomation
                   8198: 
                   8199: =over 4
1.191     harris41 8200: 
                   8201: =item *
                   8202: 
1.631     albertel 8203: coursedescription($courseid) : returns a hash of information about the
                   8204: specified course id, including all environment settings for the
                   8205: course, the description of the course will be in the hash under the
                   8206: key 'description'
1.191     harris41 8207: 
                   8208: =item *
                   8209: 
1.624     albertel 8210: resdata($name,$domain,$type,@which) : request for current parameter
                   8211: setting for a specific $type, where $type is either 'course' or 'user',
                   8212: @what should be a list of parameters to ask about. This routine caches
                   8213: answers for 5 minutes.
1.243     albertel 8214: 
                   8215: =back
                   8216: 
                   8217: =head2 Course Modification
                   8218: 
                   8219: =over 4
1.191     harris41 8220: 
                   8221: =item *
                   8222: 
1.243     albertel 8223: writecoursepref($courseid,%prefs) : write preferences (environment
                   8224: database) for a course
1.191     harris41 8225: 
                   8226: =item *
                   8227: 
1.243     albertel 8228: createcourse($udom,$description,$url) : make/modify course
                   8229: 
                   8230: =back
                   8231: 
                   8232: =head2 Resource Subroutines
                   8233: 
                   8234: =over 4
1.191     harris41 8235: 
                   8236: =item *
                   8237: 
1.243     albertel 8238: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8239: 
                   8240: =item *
                   8241: 
1.243     albertel 8242: repcopy($filename) : subscribes to the requested file, and attempts to
                   8243: replicate from the owning library server, Might return
1.607     raeburn  8244: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8245: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8246: resource. Expects the local filesystem pathname
                   8247: (/home/httpd/html/res/....)
                   8248: 
                   8249: =back
                   8250: 
                   8251: =head2 Resource Information
                   8252: 
                   8253: =over 4
1.191     harris41 8254: 
                   8255: =item *
                   8256: 
1.243     albertel 8257: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8258: a vairety of different possible values, $varname should be a request
                   8259: string, and the other parameters can be used to specify who and what
                   8260: one is asking about.
                   8261: 
                   8262: Possible values for $varname are environment.lastname (or other item
                   8263: from the envirnment hash), user.name (or someother aspect about the
                   8264: user), resource.0.maxtries (or some other part and parameter of a
                   8265: resource)
1.204     albertel 8266: 
                   8267: =item *
                   8268: 
1.243     albertel 8269: directcondval($number) : get current value of a condition; reads from a state
                   8270: string
1.204     albertel 8271: 
                   8272: =item *
                   8273: 
1.243     albertel 8274: condval($condidx) : value of condition index based on state
1.204     albertel 8275: 
                   8276: =item *
                   8277: 
1.243     albertel 8278: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8279: resource's metadata, $what should be either a specific key, or either
                   8280: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8281: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8282: 
                   8283: this function automatically caches all requests
1.191     harris41 8284: 
                   8285: =item *
                   8286: 
1.243     albertel 8287: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8288: network of library servers; returns file handle of where SQL and regex results
                   8289: will be stored for query
1.191     harris41 8290: 
                   8291: =item *
                   8292: 
1.243     albertel 8293: symbread($filename) : return symbolic list entry (filename argument optional);
                   8294: returns the data handle
1.191     harris41 8295: 
                   8296: =item *
                   8297: 
1.243     albertel 8298: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8299: a possible symb for the URL in $thisfn, and if is an encryypted
                   8300: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8301: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8302: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8303: 
1.191     harris41 8304: 
                   8305: =item *
                   8306: 
1.243     albertel 8307: symbclean($symb) : removes versions numbers from a symb, returns the
                   8308: cleaned symb
1.191     harris41 8309: 
                   8310: =item *
                   8311: 
1.243     albertel 8312: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8313: course map, user must be in a course for it to work.
1.191     harris41 8314: 
                   8315: =item *
                   8316: 
1.243     albertel 8317: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8318: 
                   8319: =item *
                   8320: 
1.243     albertel 8321: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8322: a random seed, all arguments are optional, if they aren't sent it uses the
                   8323: environment to derive them. Note: if symb isn't sent and it can't get one
                   8324: from &symbread it will use the current time as its return value
1.191     harris41 8325: 
                   8326: =item *
                   8327: 
1.243     albertel 8328: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8329: unfakeable, receipt
1.191     harris41 8330: 
                   8331: =item *
                   8332: 
1.620     albertel 8333: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8334: 
                   8335: =item *
                   8336: 
1.243     albertel 8337: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8338: 
                   8339: =item *
                   8340: 
1.243     albertel 8341: 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 8342: 
                   8343: =item *
                   8344: 
1.243     albertel 8345: 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 8346: 
                   8347: =item *
                   8348: 
1.243     albertel 8349: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8350: 
                   8351: =item *
                   8352: 
1.243     albertel 8353: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8354: forcing spreadsheet to reevaluate the resource scores next time.
                   8355: 
                   8356: =back
                   8357: 
                   8358: =head2 Storing/Retreiving Data
                   8359: 
                   8360: =over 4
1.191     harris41 8361: 
                   8362: =item *
                   8363: 
1.243     albertel 8364: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8365: for this url; hashref needs to be given and should be a \%hashname; the
                   8366: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8367: be derived from the env
1.191     harris41 8368: 
                   8369: =item *
                   8370: 
1.243     albertel 8371: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8372: uses critical subroutine
1.191     harris41 8373: 
                   8374: =item *
                   8375: 
1.243     albertel 8376: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8377: all args are optional
1.191     harris41 8378: 
                   8379: =item *
                   8380: 
1.717     albertel 8381: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8382: dumps the complete (or key matching regexp) namespace into a hash
                   8383: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8384: normally &store()ed into
                   8385: 
                   8386: $range should be either an integer '100' (give me the first 100
                   8387:                                            matching records)
                   8388:               or be  two integers sperated by a - with no spaces
                   8389:                  '30-50' (give me the 30th through the 50th matching
                   8390:                           records)
                   8391: 
                   8392: 
                   8393: =item *
                   8394: 
                   8395: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8396: replaces a &store() version of data with a replacement set of data
                   8397: for a particular resource in a namespace passed in the $storehash hash 
                   8398: reference
                   8399: 
                   8400: =item *
                   8401: 
1.243     albertel 8402: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8403: works very similar to store/cstore, but all data is stored in a
                   8404: temporary location and can be reset using tmpreset, $storehash should
                   8405: be a hash reference, returns nothing on success
1.191     harris41 8406: 
                   8407: =item *
                   8408: 
1.243     albertel 8409: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8410: similar to restore, but all data is stored in a temporary location and
                   8411: can be reset using tmpreset. Returns a hash of values on success,
                   8412: error string otherwise.
1.191     harris41 8413: 
                   8414: =item *
                   8415: 
1.243     albertel 8416: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8417: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8418: 
                   8419: =item *
                   8420: 
1.243     albertel 8421: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8422: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8423: 
                   8424: =item *
                   8425: 
1.243     albertel 8426: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8427: namesp ($udom and $uname are optional)
1.191     harris41 8428: 
                   8429: =item *
                   8430: 
1.702     albertel 8431: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8432: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8433: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8434: 
1.702     albertel 8435: $range should be either an integer '100' (give me the first 100
                   8436:                                            matching records)
                   8437:               or be  two integers sperated by a - with no spaces
                   8438:                  '30-50' (give me the 30th through the 50th matching
                   8439:                           records)
1.449     matthew  8440: =item *
                   8441: 
                   8442: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8443: $store can be a scalar, an array reference, or if the amount to be 
                   8444: incremented is > 1, a hash reference.
                   8445: 
                   8446: ($udom and $uname are optional)
1.191     harris41 8447: 
                   8448: =item *
                   8449: 
1.243     albertel 8450: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8451: ($udom and $uname are optional)
1.191     harris41 8452: 
                   8453: =item *
                   8454: 
1.243     albertel 8455: cput($namespace,$storehash,$udom,$uname) : critical put
                   8456: ($udom and $uname are optional)
1.191     harris41 8457: 
                   8458: =item *
                   8459: 
1.748     albertel 8460: newput($namespace,$storehash,$udom,$uname) :
                   8461: 
                   8462: Attempts to store the items in the $storehash, but only if they don't
                   8463: currently exist, if this succeeds you can be certain that you have 
                   8464: successfully created a new key value pair in the $namespace db.
                   8465: 
                   8466: 
                   8467: Args:
                   8468:  $namespace: name of database to store values to
                   8469:  $storehash: hashref to store to the db
                   8470:  $udom: (optional) domain of user containing the db
                   8471:  $uname: (optional) name of user caontaining the db
                   8472: 
                   8473: Returns:
                   8474:  'ok' -> succeeded in storing all keys of $storehash
                   8475:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8476:                         least <key> already existed in the db (other
                   8477:                         requested keys may also already exist)
                   8478:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8479:  'con_lost' -> unable to contact request server
                   8480:  'refused' -> action was not allowed by remote machine
                   8481: 
                   8482: 
                   8483: =item *
                   8484: 
1.243     albertel 8485: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8486: reference filled in from namesp (encrypts the return communication)
                   8487: ($udom and $uname are optional)
1.191     harris41 8488: 
                   8489: =item *
                   8490: 
1.243     albertel 8491: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8492: critical subroutine
                   8493: 
1.806     raeburn  8494: =item *
                   8495: 
                   8496: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8497: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8498: 
                   8499: =item *
                   8500: 
                   8501: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8502: 
1.243     albertel 8503: =back
                   8504: 
                   8505: =head2 Network Status Functions
                   8506: 
                   8507: =over 4
1.191     harris41 8508: 
                   8509: =item *
                   8510: 
                   8511: dirlist($uri) : return directory list based on URI
                   8512: 
                   8513: =item *
                   8514: 
1.243     albertel 8515: spareserver() : find server with least workload from spare.tab
                   8516: 
                   8517: =back
                   8518: 
                   8519: =head2 Apache Request
                   8520: 
                   8521: =over 4
1.191     harris41 8522: 
                   8523: =item *
                   8524: 
1.243     albertel 8525: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8526: localhost, posts hash
                   8527: 
                   8528: =back
                   8529: 
                   8530: =head2 Data to String to Data
                   8531: 
                   8532: =over 4
1.191     harris41 8533: 
                   8534: =item *
                   8535: 
1.243     albertel 8536: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8537: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8538: 
                   8539: =item *
                   8540: 
1.243     albertel 8541: hashref2str($hashref) : convert a hashref into a string complete with
                   8542: escaping and '=' and '&' separators, supports elements that are
                   8543: arrayrefs and hashrefs
1.191     harris41 8544: 
                   8545: =item *
                   8546: 
1.243     albertel 8547: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8548: with escaping and '&' separators, supports elements that are arrayrefs
                   8549: and hashrefs
1.191     harris41 8550: 
                   8551: =item *
                   8552: 
1.243     albertel 8553: str2hash($string) : convert string to hash using unescaping and
                   8554: splitting on '=' and '&', supports elements that are arrayrefs and
                   8555: hashrefs
1.191     harris41 8556: 
                   8557: =item *
                   8558: 
1.243     albertel 8559: str2array($string) : convert string to hash using unescaping and
                   8560: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8561: 
                   8562: =back
                   8563: 
                   8564: =head2 Logging Routines
                   8565: 
                   8566: =over 4
                   8567: 
                   8568: These routines allow one to make log messages in the lonnet.log and
                   8569: lonnet.perm logfiles.
1.191     harris41 8570: 
                   8571: =item *
                   8572: 
1.243     albertel 8573: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8574: 
                   8575: =item *
                   8576: 
1.243     albertel 8577: logthis() : append message to the normal lonnet.log file, it gets
                   8578: preiodically rolled over and deleted.
1.191     harris41 8579: 
                   8580: =item *
                   8581: 
1.243     albertel 8582: logperm() : append a permanent message to lonnet.perm.log, this log
                   8583: file never gets deleted by any automated portion of the system, only
                   8584: messages of critical importance should go in here.
                   8585: 
                   8586: =back
                   8587: 
                   8588: =head2 General File Helper Routines
                   8589: 
                   8590: =over 4
1.191     harris41 8591: 
                   8592: =item *
                   8593: 
1.481     raeburn  8594: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8595: (a) files in /uploaded
                   8596:   (i) If a local copy of the file exists - 
                   8597:       compares modification date of local copy with last-modified date for 
                   8598:       definitive version stored on home server for course. If local copy is 
                   8599:       stale, requests a new version from the home server and stores it. 
                   8600:       If the original has been removed from the home server, then local copy 
                   8601:       is unlinked.
                   8602:   (ii) If local copy does not exist -
                   8603:       requests the file from the home server and stores it. 
                   8604:   
                   8605:   If $caller is 'uploadrep':  
                   8606:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8607:     for request for files originally uploaded via DOCS. 
                   8608:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8609:   
                   8610:   Otherwise:
                   8611:      This indicates a call from the content generation phase of the request.
                   8612:      -  returns the entire contents of the file or -1.
                   8613:      
                   8614: (b) files in /res
                   8615:    - returns the entire contents of a file or -1; 
                   8616:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8617: 
1.712     albertel 8618: 
                   8619: =item *
                   8620: 
                   8621: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8622:                   reference
                   8623: 
                   8624: returns either a stat() list of data about the file or an empty list
                   8625: if the file doesn't exist or couldn't find out about it (connection
                   8626: problems or user unknown)
                   8627: 
1.191     harris41 8628: =item *
                   8629: 
1.243     albertel 8630: filelocation($dir,$file) : returns file system location of a file
                   8631: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8632: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8633: and a file of ../bob will become /a/bob)
1.191     harris41 8634: 
                   8635: =item *
                   8636: 
                   8637: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8638: filelocation except for hrefs
                   8639: 
                   8640: =item *
                   8641: 
                   8642: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8643: 
1.243     albertel 8644: =back
                   8645: 
1.608     albertel 8646: =head2 Usererfile file routines (/uploaded*)
                   8647: 
                   8648: =over 4
                   8649: 
                   8650: =item *
                   8651: 
                   8652: userfileupload(): main rotine for putting a file in a user or course's
                   8653:                   filespace, arguments are,
                   8654: 
1.620     albertel 8655:  formname - required - this is the name of the element in $env where the
1.608     albertel 8656:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8657:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8658:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8659:  coursedoc - if true, store the file in the course of the active role
                   8660:              of the current user
                   8661:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8662:          if undefined, it will be placed in "unknown"
                   8663: 
                   8664:  (This routine calls clean_filename() to remove any dangerous
                   8665:  characters from the filename, and then calls finuserfileupload() to
                   8666:  complete the transaction)
                   8667: 
                   8668:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8669:  and /adm/notfound.html if unsuccessful
                   8670: 
                   8671: =item *
                   8672: 
                   8673: clean_filename(): routine for cleaing a filename up for storage in
                   8674:                  userfile space, argument is:
                   8675: 
                   8676:  filename - proposed filename
                   8677: 
                   8678: returns: the new clean filename
                   8679: 
                   8680: =item *
                   8681: 
                   8682: finishuserfileupload(): routine that creaes and sends the file to
                   8683: userspace, probably shouldn't be called directly
                   8684: 
                   8685:   docuname: username or courseid of destination for the file
                   8686:   docudom: domain of user/course of destination for the file
                   8687:   formname: same as for userfileupload()
                   8688:   fname: filename (inculding subdirectories) for the file
                   8689: 
                   8690:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8691:  and /adm/notfound.html if unsuccessful
                   8692: 
                   8693: =item *
                   8694: 
                   8695: renameuserfile(): renames an existing userfile to a new name
                   8696: 
                   8697:   Args:
                   8698:    docuname: username or courseid of destination for the file
                   8699:    docudom: domain of user/course of destination for the file
                   8700:    old: current file name (including any subdirs under userfiles)
                   8701:    new: desired file name (including any subdirs under userfiles)
                   8702: 
                   8703: =item *
                   8704: 
                   8705: mkdiruserfile(): creates a directory is a userfiles dir
                   8706: 
                   8707:   Args:
                   8708:    docuname: username or courseid of destination for the file
                   8709:    docudom: domain of user/course of destination for the file
                   8710:    dir: dir to create (including any subdirs under userfiles)
                   8711: 
                   8712: =item *
                   8713: 
                   8714: removeuserfile(): removes a file that exists in userfiles
                   8715: 
                   8716:   Args:
                   8717:    docuname: username or courseid of destination for the file
                   8718:    docudom: domain of user/course of destination for the file
                   8719:    fname: filname to delete (including any subdirs under userfiles)
                   8720: 
                   8721: =item *
                   8722: 
                   8723: removeuploadedurl(): convience function for removeuserfile()
                   8724: 
                   8725:   Args:
                   8726:    url:  a full /uploaded/... url to delete
                   8727: 
1.747     albertel 8728: =item * 
                   8729: 
                   8730: get_portfile_permissions():
                   8731:   Args:
                   8732:     domain: domain of user or course contain the portfolio files
                   8733:     user: name of user or num of course contain the portfolio files
                   8734:   Returns:
                   8735:     hashref of a dump of the proper file_permissions.db
                   8736:    
                   8737: 
                   8738: =item * 
                   8739: 
                   8740: get_access_controls():
                   8741: 
                   8742: Args:
                   8743:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8744:   group: (optional) the group you want the files associated with
                   8745:   file: (optional) the file you want access info on
                   8746: 
                   8747: Returns:
1.749     raeburn  8748:     a hash (keys are file names) of hashes containing
                   8749:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8750:         values are XML containing access control settings (see below) 
1.747     albertel 8751: 
                   8752: Internal notes:
                   8753: 
1.749     raeburn  8754:  access controls are stored in file_permissions.db as key=value pairs.
                   8755:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8756:         where scope -> public,guest,course,group,domains or users.
                   8757:               end -> UNIX time for end of access (0 -> no end date)
                   8758:               start -> UNIX time for start of access
                   8759: 
                   8760:     value -> XML description of access control
                   8761:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8762:             <start></start>
                   8763:             <end></end>
                   8764: 
                   8765:             <password></password>  for scope type = guest
                   8766: 
                   8767:             <domain></domain>     for scope type = course or group
                   8768:             <number></number>
                   8769:             <roles id="">
                   8770:              <role></role>
                   8771:              <access></access>
                   8772:              <section></section>
                   8773:              <group></group>
                   8774:             </roles>
                   8775: 
                   8776:             <dom></dom>         for scope type = domains
                   8777: 
                   8778:             <users>             for scope type = users
                   8779:              <user>
                   8780:               <uname></uname>
                   8781:               <udom></udom>
                   8782:              </user>
                   8783:             </users>
                   8784:            </scope> 
                   8785:               
                   8786:  Access data is also aggregated for each file in an additional key=value pair:
                   8787:  key -> path to file/file_name\0accesscontrol 
                   8788:  value -> reference to hash
                   8789:           hash contains key = value pairs
                   8790:           where key = uniqueID:scope_end_start
                   8791:                 value = UNIX time record was last updated
                   8792: 
                   8793:           Used to improve speed of look-ups of access controls for each file.  
                   8794:  
                   8795:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8796: 
                   8797: modify_access_controls():
                   8798: 
                   8799: Modifies access controls for a portfolio file
                   8800: Args
                   8801: 1. file name
                   8802: 2. reference to hash of required changes,
                   8803: 3. domain
                   8804: 4. username
                   8805:   where domain,username are the domain of the portfolio owner 
                   8806:   (either a user or a course) 
                   8807: 
                   8808: Returns:
                   8809: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8810: 2. result of deletions ('ok' or 'error', with error message).
                   8811: 3. reference to hash of any new or updated access controls.
                   8812: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8813:    key = integer (inbound ID)
                   8814:    value = uniqueID  
1.747     albertel 8815: 
1.608     albertel 8816: =back
                   8817: 
1.243     albertel 8818: =head2 HTTP Helper Routines
                   8819: 
                   8820: =over 4
                   8821: 
1.191     harris41 8822: =item *
                   8823: 
                   8824: escape() : unpack non-word characters into CGI-compatible hex codes
                   8825: 
                   8826: =item *
                   8827: 
                   8828: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8829: 
1.243     albertel 8830: =back
                   8831: 
                   8832: =head1 PRIVATE SUBROUTINES
                   8833: 
                   8834: =head2 Underlying communication routines (Shouldn't call)
                   8835: 
                   8836: =over 4
                   8837: 
                   8838: =item *
                   8839: 
                   8840: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8841: 
                   8842: =item *
                   8843: 
                   8844: reply() : uses subreply to send a message to remote machine, logs all failures
                   8845: 
                   8846: =item *
                   8847: 
                   8848: critical() : passes a critical message to another server; if cannot
                   8849: get through then place message in connection buffer directory and
                   8850: returns con_delayed, if incapable of saving message, returns
                   8851: con_failed
                   8852: 
                   8853: =item *
                   8854: 
                   8855: reconlonc() : tries to reconnect lonc client processes.
                   8856: 
                   8857: =back
                   8858: 
                   8859: =head2 Resource Access Logging
                   8860: 
                   8861: =over 4
                   8862: 
                   8863: =item *
                   8864: 
                   8865: flushcourselogs() : flush (save) buffer logs and access logs
                   8866: 
                   8867: =item *
                   8868: 
                   8869: courselog($what) : save message for course in hash
                   8870: 
                   8871: =item *
                   8872: 
                   8873: courseacclog($what) : save message for course using &courselog().  Perform
                   8874: special processing for specific resource types (problems, exams, quizzes, etc).
                   8875: 
1.191     harris41 8876: =item *
                   8877: 
                   8878: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8879: as a PerlChildExitHandler
1.243     albertel 8880: 
                   8881: =back
                   8882: 
                   8883: =head2 Other
                   8884: 
                   8885: =over 4
                   8886: 
                   8887: =item *
                   8888: 
                   8889: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8890: 
                   8891: =back
                   8892: 
                   8893: =cut

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