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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.848   ! albertel    4: # $Id: lonnet.pm,v 1.847 2007/03/12 17:07:43 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.847     albertel   38: qw(%perlvar %badServerCache %spareid 
1.845     albertel   39:    %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.685     raeburn    42:    $tmpdir $_64bit %env);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.637     raeburn    47: use HTML::Parser;
1.88      www        48: use Fcntl qw(:flock);
1.557     albertel   49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   50: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   51: use Cache::Memcached;
1.676     albertel   52: use Digest::MD5;
1.790     albertel   53: use Math::Random;
1.807     albertel   54: use LONCAPA qw(:DEFAULT :match);
1.740     www        55: use LONCAPA::Configuration;
1.676     albertel   56: 
1.195     www        57: my $readit;
1.550     foxr       58: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   59: 
1.619     albertel   60: require Exporter;
                     61: 
                     62: our @ISA = qw (Exporter);
                     63: our @EXPORT = qw(%env);
                     64: 
1.449     matthew    65: =pod
                     66: 
                     67: =head1 Package Variables
                     68: 
                     69: These are largely undocumented, so if you decipher one please note it here.
                     70: 
                     71: =over 4
                     72: 
                     73: =item $processmarker
                     74: 
                     75: Contains the time this process was started and this servers host id.
                     76: 
                     77: =item $dumpcount
                     78: 
                     79: Counts the number of times a message log flush has been attempted (regardless
                     80: of success) by this process.  Used as part of the filename when messages are
                     81: delayed.
                     82: 
                     83: =back
                     84: 
                     85: =cut
                     86: 
                     87: 
1.1       albertel   88: # --------------------------------------------------------------------- Logging
1.729     www        89: {
                     90:     my $logid;
                     91:     sub instructor_log {
                     92: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     93: 	$logid++;
                     94: 	my $id=time().'00000'.$$.'00000'.$logid;
                     95: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        96: 				    { $id => {
                     97: 					'exe_uname' => $env{'user.name'},
                     98: 					'exe_udom'  => $env{'user.domain'},
                     99: 					'exe_time'  => time(),
                    100: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    101: 					'delflag'   => $delflag,
                    102: 					'logentry'  => $storehash,
                    103: 					'uname'     => $uname,
                    104: 					'udom'      => $udom,
                    105: 				    }
                    106: 				  },
1.729     www       107: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    108: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    109: 				    );
                    110:     }
                    111: }
1.1       albertel  112: 
1.163     harris41  113: sub logtouch {
                    114:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  115:     unless (-e "$execdir/logs/lonnet.log") {	
                    116: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  117: 	close $fh;
                    118:     }
                    119:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    120:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    121: }
                    122: 
1.1       albertel  123: sub logthis {
                    124:     my $message=shift;
                    125:     my $execdir=$perlvar{'lonDaemons'};
                    126:     my $now=time;
                    127:     my $local=localtime($now);
1.448     albertel  128:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    129: 	print $fh "$local ($$): $message\n";
                    130: 	close($fh);
                    131:     }
1.1       albertel  132:     return 1;
                    133: }
                    134: 
                    135: sub logperm {
                    136:     my $message=shift;
                    137:     my $execdir=$perlvar{'lonDaemons'};
                    138:     my $now=time;
                    139:     my $local=localtime($now);
1.448     albertel  140:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    141: 	print $fh "$now:$message:$local\n";
                    142: 	close($fh);
                    143:     }
1.1       albertel  144:     return 1;
                    145: }
                    146: 
                    147: # -------------------------------------------------- Non-critical communication
                    148: sub subreply {
                    149:     my ($cmd,$server)=@_;
1.838     albertel  150:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      151:     #
                    152:     #  With loncnew process trimming, there's a timing hole between lonc server
                    153:     #  process exit and the master server picking up the listen on the AF_UNIX
                    154:     #  socket.  In that time interval, a lock file will exist:
                    155: 
                    156:     my $lockfile=$peerfile.".lock";
                    157:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    158: 	sleep(1);
                    159:     }
                    160:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      161:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      162:     #
1.550     foxr      163:     #   We'll give the connection a few tries before abandoning it.  If
                    164:     #   connection is not possible, we'll con_lost back to the client.
                    165:     #   
                    166:     my $client;
                    167:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    168: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    169: 				      Type    => SOCK_STREAM,
                    170: 				      Timeout => 10);
                    171: 	if($client) {
                    172: 	    last;		# Connected!
                    173: 	}
                    174: 	sleep(1);		# Try again later if failed connection.
                    175:     }
                    176:     my $answer;
                    177:     if ($client) {
1.704     albertel  178: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      179: 	$answer=<$client>;
                    180: 	if (!$answer) { $answer="con_lost"; }
                    181: 	chomp($answer);
                    182:     } else {
                    183: 	$answer = 'con_lost';	# Failed connection.
                    184:     }
1.1       albertel  185:     return $answer;
                    186: }
                    187: 
                    188: sub reply {
                    189:     my ($cmd,$server)=@_;
1.838     albertel  190:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  191:     my $answer=subreply($cmd,$server);
1.65      www       192:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  193:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       194:                 " $cmd to $server returned $answer</font>");
                    195:     }
1.1       albertel  196:     return $answer;
                    197: }
                    198: 
                    199: # ----------------------------------------------------------- Send USR1 to lonc
                    200: 
                    201: sub reconlonc {
1.836     www       202:     &logthis("Trying to reconnect lonc");
1.1       albertel  203:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  204:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  205: 	my $loncpid=<$fh>;
                    206:         chomp($loncpid);
                    207:         if (kill 0 => $loncpid) {
                    208: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    209:             kill USR1 => $loncpid;
                    210:             sleep 1;
1.836     www       211:          } else {
1.12      www       212: 	    &logthis(
1.672     albertel  213:                "<font color=\"blue\">WARNING:".
1.12      www       214:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  215:         }
                    216:     } else {
1.836     www       217: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  218:     }
                    219: }
                    220: 
                    221: # ------------------------------------------------------ Critical communication
1.12      www       222: 
1.1       albertel  223: sub critical {
                    224:     my ($cmd,$server)=@_;
1.838     albertel  225:     unless (&hostname($server)) {
1.672     albertel  226:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       227:                " Critical message to unknown server ($server)</font>");
                    228:         return 'no_such_host';
                    229:     }
1.1       albertel  230:     my $answer=reply($cmd,$server);
                    231:     if ($answer eq 'con_lost') {
                    232: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  233: 	my $answer=reply($cmd,$server);
1.1       albertel  234:         if ($answer eq 'con_lost') {
                    235:             my $now=time;
                    236:             my $middlename=$cmd;
1.5       www       237:             $middlename=substr($middlename,0,16);
1.1       albertel  238:             $middlename=~s/\W//g;
                    239:             my $dfilename=
1.305     www       240:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    241:             $dumpcount++;
1.1       albertel  242:             {
1.448     albertel  243: 		my $dfh;
                    244: 		if (open($dfh,">$dfilename")) {
                    245: 		    print $dfh "$cmd\n"; 
                    246: 		    close($dfh);
                    247: 		}
1.1       albertel  248:             }
                    249:             sleep 2;
                    250:             my $wcmd='';
                    251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,"<$dfilename")) {
                    254: 		    $wcmd=<$dfh>; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             chomp($wcmd);
1.7       www       259:             if ($wcmd eq $cmd) {
1.672     albertel  260: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       261:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  262:                 &logperm("D:$server:$cmd");
                    263: 	        return 'con_delayed';
                    264:             } else {
1.672     albertel  265:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       266:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  267:                 &logperm("F:$server:$cmd");
                    268:                 return 'con_failed';
                    269:             }
                    270:         }
                    271:     }
                    272:     return $answer;
1.405     albertel  273: }
                    274: 
1.755     albertel  275: # ------------------------------------------- check if return value is an error
                    276: 
                    277: sub error {
                    278:     my ($result) = @_;
1.756     albertel  279:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  280: 	if ($2 == 2) { return undef; }
                    281: 	return $1;
                    282:     }
                    283:     return undef;
                    284: }
                    285: 
1.783     albertel  286: sub convert_and_load_session_env {
                    287:     my ($lonidsdir,$handle)=@_;
                    288:     my @profile;
                    289:     {
                    290: 	open(my $idf,"$lonidsdir/$handle.id");
                    291: 	flock($idf,LOCK_SH);
                    292: 	@profile=<$idf>;
                    293: 	close($idf);
                    294:     }
                    295:     my %temp_env;
                    296:     foreach my $line (@profile) {
1.786     albertel  297: 	if ($line !~ m/=/) {
                    298: 	    return 0;
                    299: 	}
1.783     albertel  300: 	chomp($line);
                    301: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    302: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    303:     }
                    304:     unlink("$lonidsdir/$handle.id");
                    305:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    306: 	    0640)) {
                    307: 	%disk_env = %temp_env;
                    308: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    309: 	untie(%disk_env);
                    310:     }
1.786     albertel  311:     return 1;
1.783     albertel  312: }
                    313: 
1.374     www       314: # ------------------------------------------- Transfer profile into environment
1.780     albertel  315: my $env_loaded;
                    316: sub transfer_profile_to_env {
1.788     albertel  317:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    318:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       319: 
1.720     albertel  320:     if (!defined($lonidsdir)) {
                    321: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    322:     }
                    323:     if (!defined($handle)) {
                    324:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    325:     }
                    326: 
1.786     albertel  327:     my $convert;
                    328:     {
                    329:     	open(my $idf,"$lonidsdir/$handle.id");
                    330: 	flock($idf,LOCK_SH);
                    331: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    332: 		&GDBM_READER(),0640)) {
                    333: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    334: 	    untie(%disk_env);
                    335: 	} else {
                    336: 	    $convert = 1;
                    337: 	}
                    338:     }
                    339:     if ($convert) {
                    340: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    341: 	    &logthis("Failed to load session, or convert session.");
                    342: 	}
1.374     www       343:     }
1.783     albertel  344: 
1.786     albertel  345:     my %remove;
1.783     albertel  346:     while ( my $envname = each(%env) ) {
1.433     matthew   347:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    348:             if ($time < time-300) {
1.783     albertel  349:                 $remove{$key}++;
1.433     matthew   350:             }
                    351:         }
                    352:     }
1.783     albertel  353: 
1.619     albertel  354:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  355:     $env_loaded=1;
1.783     albertel  356:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   357:         &delenv($expired_key);
1.374     www       358:     }
1.1       albertel  359: }
                    360: 
1.830     albertel  361: sub timed_flock {
                    362:     my ($file,$lock_type) = @_;
                    363:     my $failed=0;
                    364:     eval {
                    365: 	local $SIG{__DIE__}='DEFAULT';
                    366: 	local $SIG{ALRM}=sub {
                    367: 	    $failed=1;
                    368: 	    die("failed lock");
                    369: 	};
                    370: 	alarm(13);
                    371: 	flock($file,$lock_type);
                    372: 	alarm(0);
                    373:     };
                    374:     if ($failed) {
                    375: 	return undef;
                    376:     } else {
                    377: 	return 1;
                    378:     }
                    379: }
                    380: 
1.5       www       381: # ---------------------------------------------------------- Append Environment
                    382: 
                    383: sub appenv {
1.6       www       384:     my %newenv=@_;
1.692     albertel  385:     foreach my $key (keys(%newenv)) {
                    386: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  387:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  388:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       389:                 .'</font>');
1.692     albertel  390: 	    delete($newenv{$key});
1.35      www       391:         } else {
1.692     albertel  392:             $env{$key}=$newenv{$key};
1.35      www       393:         }
1.191     harris41  394:     }
1.830     albertel  395:     open(my $env_file,$env{'user.environment'});
                    396:     if (&timed_flock($env_file,LOCK_EX)
                    397: 	&&
                    398: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    399: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  400: 	while (my ($key,$value) = each(%newenv)) {
                    401: 	    $disk_env{$key} = $value;
1.448     albertel  402: 	}
1.783     albertel  403: 	untie(%disk_env);
1.56      www       404:     }
                    405:     return 'ok';
                    406: }
                    407: # ----------------------------------------------------- Delete from Environment
                    408: 
                    409: sub delenv {
                    410:     my $delthis=shift;
                    411:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  412:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       413:                 "Attempt to delete from environment ".$delthis);
                    414:         return 'error';
                    415:     }
1.830     albertel  416:     open(my $env_file,$env{'user.environment'});
                    417:     if (&timed_flock($env_file,LOCK_EX)
                    418: 	&&
                    419: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    420: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  421: 	foreach my $key (keys(%disk_env)) {
                    422: 	    if ($key=~/^$delthis/) { 
1.619     albertel  423:                 delete($env{$key});
1.783     albertel  424:                 delete($disk_env{$key});
1.473     matthew   425:             }
1.448     albertel  426: 	}
1.783     albertel  427: 	untie(%disk_env);
1.5       www       428:     }
                    429:     return 'ok';
1.369     albertel  430: }
                    431: 
1.790     albertel  432: sub get_env_multiple {
                    433:     my ($name) = @_;
                    434:     my @values;
                    435:     if (defined($env{$name})) {
                    436:         # exists is it an array
                    437:         if (ref($env{$name})) {
                    438:             @values=@{ $env{$name} };
                    439:         } else {
                    440:             $values[0]=$env{$name};
                    441:         }
                    442:     }
                    443:     return(@values);
                    444: }
                    445: 
1.369     albertel  446: # ------------------------------------------ Find out current server userload
                    447: # there is a copy in lond
                    448: sub userload {
                    449:     my $numusers=0;
                    450:     {
                    451: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    452: 	my $filename;
                    453: 	my $curtime=time;
                    454: 	while ($filename=readdir(LONIDS)) {
                    455: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  456: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  457: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  458: 	}
                    459: 	closedir(LONIDS);
                    460:     }
                    461:     my $userloadpercent=0;
                    462:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    463:     if ($maxuserload) {
1.371     albertel  464: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  465:     }
1.372     albertel  466:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  467:     return $userloadpercent;
1.283     www       468: }
                    469: 
                    470: # ------------------------------------------ Fight off request when overloaded
                    471: 
                    472: sub overloaderror {
                    473:     my ($r,$checkserver)=@_;
                    474:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    475:     my $loadavg;
                    476:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  477:        open(my $loadfile,'/proc/loadavg');
1.283     www       478:        $loadavg=<$loadfile>;
                    479:        $loadavg =~ s/\s.*//g;
1.285     matthew   480:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  481:        close($loadfile);
1.283     www       482:     } else {
                    483:        $loadavg=&reply('load',$checkserver);
                    484:     }
1.285     matthew   485:     my $overload=$loadavg-100;
1.283     www       486:     if ($overload>0) {
1.285     matthew   487: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       488:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       489:         return 413;
1.283     www       490:     }    
                    491:     return '';
1.5       www       492: }
1.1       albertel  493: 
                    494: # ------------------------------ Find server with least workload from spare.tab
1.11      www       495: 
1.1       albertel  496: sub spareserver {
1.670     albertel  497:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  498:     my $spare_server;
1.370     albertel  499:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  500:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    501:                                                      :  $userloadpercent;
                    502:     
                    503:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    504: 	($spare_server, $lowest_load) =
                    505: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    506:     }
                    507: 
                    508:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    509: 
                    510:     if (!$found_server) {
                    511: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    512: 	    ($spare_server, $lowest_load) =
                    513: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    514: 	}
                    515:     }
                    516: 
                    517:     if (!$want_server_name) {
1.838     albertel  518: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  519:     }
                    520:     return $spare_server;
                    521: }
                    522: 
                    523: sub compare_server_load {
                    524:     my ($try_server, $spare_server, $lowest_load) = @_;
                    525: 
                    526:     my $loadans     = &reply('load',    $try_server);
                    527:     my $userloadans = &reply('userload',$try_server);
                    528: 
                    529:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    530: 	next; #didn't get a number from the server
                    531:     }
                    532: 
                    533:     my $load;
                    534:     if ($loadans =~ /\d/) {
                    535: 	if ($userloadans =~ /\d/) {
                    536: 	    #both are numbers, pick the bigger one
                    537: 	    $load = ($loadans > $userloadans) ? $loadans 
                    538: 		                              : $userloadans;
1.411     albertel  539: 	} else {
1.784     albertel  540: 	    $load = $loadans;
1.411     albertel  541: 	}
1.784     albertel  542:     } else {
                    543: 	$load = $userloadans;
                    544:     }
                    545: 
                    546:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    547: 	$spare_server = $try_server;
                    548: 	$lowest_load  = $load;
1.370     albertel  549:     }
1.784     albertel  550:     return ($spare_server,$lowest_load);
1.202     matthew   551: }
                    552: # --------------------------------------------- Try to change a user's password
                    553: 
                    554: sub changepass {
1.799     raeburn   555:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   556:     $currentpass = &escape($currentpass);
                    557:     $newpass     = &escape($newpass);
1.799     raeburn   558:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   559: 		       $server);
                    560:     if (! $answer) {
                    561: 	&logthis("No reply on password change request to $server ".
                    562: 		 "by $uname in domain $udom.");
                    563:     } elsif ($answer =~ "^ok") {
                    564:         &logthis("$uname in $udom successfully changed their password ".
                    565: 		 "on $server.");
                    566:     } elsif ($answer =~ "^pwchange_failure") {
                    567: 	&logthis("$uname in $udom was unable to change their password ".
                    568: 		 "on $server.  The action was blocked by either lcpasswd ".
                    569: 		 "or pwchange");
                    570:     } elsif ($answer =~ "^non_authorized") {
                    571:         &logthis("$uname in $udom did not get their password correct when ".
                    572: 		 "attempting to change it on $server.");
                    573:     } elsif ($answer =~ "^auth_mode_error") {
                    574:         &logthis("$uname in $udom attempted to change their password despite ".
                    575: 		 "not being locally or internally authenticated on $server.");
                    576:     } elsif ($answer =~ "^unknown_user") {
                    577:         &logthis("$uname in $udom attempted to change their password ".
                    578: 		 "on $server but were unable to because $server is not ".
                    579: 		 "their home server.");
                    580:     } elsif ($answer =~ "^refused") {
                    581: 	&logthis("$server refused to change $uname in $udom password because ".
                    582: 		 "it was sent an unencrypted request to change the password.");
                    583:     }
                    584:     return $answer;
1.1       albertel  585: }
                    586: 
1.169     harris41  587: # ----------------------- Try to determine user's current authentication scheme
                    588: 
                    589: sub queryauthenticate {
                    590:     my ($uname,$udom)=@_;
1.456     albertel  591:     my $uhome=&homeserver($uname,$udom);
                    592:     if (!$uhome) {
                    593: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    594: 	return 'no_host';
                    595:     }
                    596:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    597:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    598: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  599:     }
1.456     albertel  600:     return $answer;
1.169     harris41  601: }
                    602: 
1.1       albertel  603: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       604: 
1.1       albertel  605: sub authenticate {
                    606:     my ($uname,$upass,$udom)=@_;
1.807     albertel  607:     $upass=&escape($upass);
                    608:     $uname= &LONCAPA::clean_username($uname);
1.836     www       609:     my $uhome=&homeserver($uname,$udom,1);
                    610:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    611: # Maybe the machine was offline and only re-appeared again recently?
                    612:         &reconlonc();
                    613: # One more
                    614: 	my $uhome=&homeserver($uname,$udom,1);
                    615: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    616: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    617: 	}
1.471     albertel  618: 	return 'no_host';
1.1       albertel  619:     }
1.471     albertel  620:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    621:     if ($answer eq 'authorized') {
                    622: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    623: 	return $uhome; 
                    624:     }
                    625:     if ($answer eq 'non_authorized') {
                    626: 	&logthis("User $uname at $udom rejected by $uhome");
                    627: 	return 'no_host'; 
1.9       www       628:     }
1.471     albertel  629:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  630:     return 'no_host';
                    631: }
                    632: 
                    633: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       634: 
1.599     albertel  635: my %homecache;
1.1       albertel  636: sub homeserver {
1.230     stredwic  637:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  638:     my $index="$uname:$udom";
1.426     albertel  639: 
1.599     albertel  640:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  641: 
                    642:     my %servers = &get_servers($udom,'library');
                    643:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  644:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  645: 		 exists($badServerCache{$tryserver}));
1.841     albertel  646: 
                    647: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    648: 	if ($answer eq 'found') {
                    649: 	    delete($badServerCache{$tryserver}); 
                    650: 	    return $homecache{$index}=$tryserver;
                    651: 	} elsif ($answer eq 'no_host') {
                    652: 	    $badServerCache{$tryserver}=1;
                    653: 	}
1.1       albertel  654:     }    
                    655:     return 'no_host';
1.70      www       656: }
                    657: 
                    658: # ------------------------------------- Find the usernames behind a list of IDs
                    659: 
                    660: sub idget {
                    661:     my ($udom,@ids)=@_;
                    662:     my %returnhash=();
                    663:     
1.841     albertel  664:     my %servers = &get_servers($udom,'library');
                    665:     foreach my $tryserver (keys(%servers)) {
                    666: 	my $idlist=join('&',@ids);
                    667: 	$idlist=~tr/A-Z/a-z/; 
                    668: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    669: 	my @answer=();
                    670: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    671: 	    @answer=split(/\&/,$reply);
                    672: 	}                    ;
                    673: 	my $i;
                    674: 	for ($i=0;$i<=$#ids;$i++) {
                    675: 	    if ($answer[$i]) {
                    676: 		$returnhash{$ids[$i]}=$answer[$i];
                    677: 	    } 
                    678: 	}
                    679:     } 
1.70      www       680:     return %returnhash;
                    681: }
                    682: 
                    683: # ------------------------------------- Find the IDs behind a list of usernames
                    684: 
                    685: sub idrget {
                    686:     my ($udom,@unames)=@_;
                    687:     my %returnhash=();
1.800     albertel  688:     foreach my $uname (@unames) {
                    689:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  690:     }
1.70      www       691:     return %returnhash;
                    692: }
                    693: 
                    694: # ------------------------------- Store away a list of names and associated IDs
                    695: 
                    696: sub idput {
                    697:     my ($udom,%ids)=@_;
                    698:     my %servers=();
1.800     albertel  699:     foreach my $uname (keys(%ids)) {
                    700: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    701:         my $uhom=&homeserver($uname,$udom);
1.70      www       702:         if ($uhom ne 'no_host') {
1.800     albertel  703:             my $id=&escape($ids{$uname});
1.70      www       704:             $id=~tr/A-Z/a-z/;
1.800     albertel  705:             my $esc_unam=&escape($uname);
1.70      www       706: 	    if ($servers{$uhom}) {
1.800     albertel  707: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       708:             } else {
1.800     albertel  709:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       710:             }
                    711:         }
1.191     harris41  712:     }
1.800     albertel  713:     foreach my $server (keys(%servers)) {
                    714:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  715:     }
1.344     www       716: }
                    717: 
1.806     raeburn   718: # ------------------------------------------- get items from domain db files   
                    719: 
                    720: sub get_dom {
                    721:     my ($namespace,$storearr,$udom)=@_;
                    722:     my $items='';
                    723:     foreach my $item (@$storearr) {
                    724:         $items.=&escape($item).'&';
                    725:     }
                    726:     $items=~s/\&$//;
                    727:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  728:     if (defined(&domain($udom,'primary'))) {
                    729:         my $uhome=&domain($udom,'primary');
1.806     raeburn   730:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    731:         my @pairs=split(/\&/,$rep);
                    732:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    733:             return @pairs;
                    734:         }
                    735:         my %returnhash=();
                    736:         my $i=0;
                    737:         foreach my $item (@$storearr) {
                    738:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    739:             $i++;
                    740:         }
                    741:         return %returnhash;
                    742:     } else {
                    743:         &logthis("get_dom failed - no primary domain server for $udom");
                    744:     }
                    745: }
                    746: 
                    747: # -------------------------------------------- put items in domain db files 
                    748: 
                    749: sub put_dom {
                    750:     my ($namespace,$storehash,$udom)=@_;
                    751:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  752:     if (defined(&domain($udom,'primary'))) {
                    753:         my $uhome=&domain($udom,'primary');
1.806     raeburn   754:         my $items='';
                    755:         foreach my $item (keys(%$storehash)) {
                    756:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    757:         }
                    758:         $items=~s/\&$//;
                    759:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    760:     } else {
                    761:         &logthis("put_dom failed - no primary domain server for $udom");
                    762:     }
                    763: }
                    764: 
1.837     raeburn   765: sub retrieve_inst_usertypes {
                    766:     my ($udom) = @_;
                    767:     my (%returnhash,@order);
1.846     albertel  768:     if (defined(&domain($udom,'primary'))) {
                    769:         my $uhome=&domain($udom,'primary');
1.837     raeburn   770:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    771:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    772:         my @pairs=split(/\&/,$hashitems);
                    773:         foreach my $item (@pairs) {
                    774:             my ($key,$value)=split(/=/,$item,2);
                    775:             $key = &unescape($key);
                    776:             next if ($key =~ /^error: 2 /);
                    777:             $returnhash{$key}=&thaw_unescape($value);
                    778:         }
                    779:         my @esc_order = split(/\&/,$orderitems);
                    780:         foreach my $item (@esc_order) {
                    781:             push(@order,&unescape($item));
                    782:         }
                    783:     } else {
                    784:         &logthis("get_dom failed - no primary domain server for $udom");
                    785:     }
                    786:     return (\%returnhash,\@order);
                    787: }
                    788: 
1.344     www       789: # --------------------------------------------------- Assign a key to a student
                    790: 
                    791: sub assign_access_key {
1.364     www       792: #
                    793: # a valid key looks like uname:udom#comments
                    794: # comments are being appended
                    795: #
1.498     www       796:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    797:     $kdom=
1.620     albertel  798:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       799:     $knum=
1.620     albertel  800:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       801:     $cdom=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       803:     $cnum=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    805:     $udom=$env{'user.name'} unless (defined($udom));
                    806:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       807:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       808:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  809:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       810:                                                   # assigned to this person
                    811:                                                   # - this should not happen,
1.345     www       812:                                                   # unless something went wrong
                    813:                                                   # the first time around
                    814: # ready to assign
1.364     www       815:         $logentry=$1.'; '.$logentry;
1.496     www       816:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       817:                                                  $kdom,$knum) eq 'ok') {
1.345     www       818: # key now belongs to user
1.346     www       819: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       820:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    821:                 &appenv('environment.'.$envkey => $ckey);
                    822:                 return 'ok';
                    823:             } else {
                    824:                 return 
                    825:   'error: Count not permanently assign key, will need to be re-entered later.';
                    826: 	    }
                    827:         } else {
                    828:             return 'error: Could not assign key, try again later.';
                    829:         }
1.364     www       830:     } elsif (!$existing{$ckey}) {
1.345     www       831: # the key does not exist
                    832: 	return 'error: The key does not exist';
                    833:     } else {
                    834: # the key is somebody else's
                    835: 	return 'error: The key is already in use';
                    836:     }
1.344     www       837: }
                    838: 
1.364     www       839: # ------------------------------------------ put an additional comment on a key
                    840: 
                    841: sub comment_access_key {
                    842: #
                    843: # a valid key looks like uname:udom#comments
                    844: # comments are being appended
                    845: #
                    846:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    847:     $cdom=
1.620     albertel  848:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       849:     $cnum=
1.620     albertel  850:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       851:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    852:     if ($existing{$ckey}) {
                    853:         $existing{$ckey}.='; '.$logentry;
                    854: # ready to assign
1.367     www       855:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       856:                                                  $cdom,$cnum) eq 'ok') {
                    857: 	    return 'ok';
                    858:         } else {
                    859: 	    return 'error: Count not store comment.';
                    860:         }
                    861:     } else {
                    862: # the key does not exist
                    863: 	return 'error: The key does not exist';
                    864:     }
                    865: }
                    866: 
1.344     www       867: # ------------------------------------------------------ Generate a set of keys
                    868: 
                    869: sub generate_access_keys {
1.364     www       870:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       871:     $cdom=
1.620     albertel  872:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       873:     $cnum=
1.620     albertel  874:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       875:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       876:     unless (($cdom) && ($cnum)) { return 0; }
                    877:     if ($number>10000) { return 0; }
                    878:     sleep(2); # make sure don't get same seed twice
                    879:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    880:     my $total=0;
                    881:     for (my $i=1;$i<=$number;$i++) {
                    882:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    883:                   sprintf("%lx",int(100000*rand)).'-'.
                    884:                   sprintf("%lx",int(100000*rand));
                    885:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    886:        $newkey=~s/0/h/g; # and also 0 and O
                    887:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    888:        if ($existing{$newkey}) {
                    889:            $i--;
                    890:        } else {
1.364     www       891: 	  if (&put('accesskeys',
                    892:               { $newkey => '# generated '.localtime().
1.620     albertel  893:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       894:                            '; '.$logentry },
                    895: 		   $cdom,$cnum) eq 'ok') {
1.344     www       896:               $total++;
                    897: 	  }
                    898:        }
                    899:     }
1.620     albertel  900:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       901:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    902:     return $total;
                    903: }
                    904: 
                    905: # ------------------------------------------------------- Validate an accesskey
                    906: 
                    907: sub validate_access_key {
                    908:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    909:     $cdom=
1.620     albertel  910:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       911:     $cnum=
1.620     albertel  912:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    913:     $udom=$env{'user.domain'} unless (defined($udom));
                    914:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       915:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  916:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       917: }
                    918: 
                    919: # ------------------------------------- Find the section of student in a course
1.652     albertel  920: sub devalidate_getsection_cache {
                    921:     my ($udom,$unam,$courseid)=@_;
                    922:     my $hashid="$udom:$unam:$courseid";
                    923:     &devalidate_cache_new('getsection',$hashid);
                    924: }
1.298     matthew   925: 
1.815     albertel  926: sub courseid_to_courseurl {
                    927:     my ($courseid) = @_;
                    928:     #already url style courseid
                    929:     return $courseid if ($courseid =~ m{^/});
                    930: 
                    931:     if (exists($env{'course.'.$courseid.'.num'})) {
                    932: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    933: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    934: 	return "/$cdom/$cnum";
                    935:     }
                    936: 
                    937:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    938:     if (exists($courseinfo{'num'})) {
                    939: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    940:     }
                    941: 
                    942:     return undef;
                    943: }
                    944: 
1.298     matthew   945: sub getsection {
                    946:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  947:     my $cachetime=1800;
1.551     albertel  948: 
                    949:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  950:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  951:     if (defined($cached)) { return $result; }
                    952: 
1.298     matthew   953:     my %Pending; 
                    954:     my %Expired;
                    955:     #
                    956:     # Each role can either have not started yet (pending), be active, 
                    957:     #    or have expired.
                    958:     #
                    959:     # If there is an active role, we are done.
                    960:     #
                    961:     # If there is more than one role which has not started yet, 
                    962:     #     choose the one which will start sooner
                    963:     # If there is one role which has not started yet, return it.
                    964:     #
                    965:     # If there is more than one expired role, choose the one which ended last.
                    966:     # If there is a role which has expired, return it.
                    967:     #
1.815     albertel  968:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   969:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    970:     foreach my $key (keys(%roleshash)) {
1.479     albertel  971:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   972:         my $section=$1;
                    973:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   974:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   975:         my $now=time;
1.548     albertel  976:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   977:             $Expired{$end}=$section;
                    978:             next;
                    979:         }
1.548     albertel  980:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   981:             $Pending{$start}=$section;
                    982:             next;
                    983:         }
1.599     albertel  984:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   985:     }
                    986:     #
                    987:     # Presumedly there will be few matching roles from the above
                    988:     # loop and the sorting time will be negligible.
                    989:     if (scalar(keys(%Pending))) {
                    990:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  991:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   992:     } 
                    993:     if (scalar(keys(%Expired))) {
                    994:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    995:         my $time = pop(@sorted);
1.599     albertel  996:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   997:     }
1.599     albertel  998:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   999: }
1.70      www      1000: 
1.599     albertel 1001: sub save_cache {
                   1002:     &purge_remembered();
1.722     albertel 1003:     #&Apache::loncommon::validate_page();
1.620     albertel 1004:     undef(%env);
1.780     albertel 1005:     undef($env_loaded);
1.599     albertel 1006: }
1.452     albertel 1007: 
1.599     albertel 1008: my $to_remember=-1;
                   1009: my %remembered;
                   1010: my %accessed;
                   1011: my $kicks=0;
                   1012: my $hits=0;
                   1013: sub devalidate_cache_new {
                   1014:     my ($name,$id,$debug) = @_;
                   1015:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                   1016:     $id=&escape($name.':'.$id);
                   1017:     $memcache->delete($id);
                   1018:     delete($remembered{$id});
                   1019:     delete($accessed{$id});
                   1020: }
                   1021: 
                   1022: sub is_cached_new {
                   1023:     my ($name,$id,$debug) = @_;
                   1024:     $id=&escape($name.':'.$id);
                   1025:     if (exists($remembered{$id})) {
                   1026: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1027: 	$accessed{$id}=[&gettimeofday()];
                   1028: 	$hits++;
                   1029: 	return ($remembered{$id},1);
                   1030:     }
                   1031:     my $value = $memcache->get($id);
                   1032:     if (!(defined($value))) {
                   1033: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1034: 	return (undef,undef);
1.416     albertel 1035:     }
1.599     albertel 1036:     if ($value eq '__undef__') {
                   1037: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1038: 	$value=undef;
                   1039:     }
                   1040:     &make_room($id,$value,$debug);
                   1041:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1042:     return ($value,1);
                   1043: }
                   1044: 
                   1045: sub do_cache_new {
                   1046:     my ($name,$id,$value,$time,$debug) = @_;
                   1047:     $id=&escape($name.':'.$id);
                   1048:     my $setvalue=$value;
                   1049:     if (!defined($setvalue)) {
                   1050: 	$setvalue='__undef__';
                   1051:     }
1.623     albertel 1052:     if (!defined($time) ) {
                   1053: 	$time=600;
                   1054:     }
1.599     albertel 1055:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1056:     $memcache->set($id,$setvalue,$time);
                   1057:     # need to make a copy of $value
                   1058:     #&make_room($id,$value,$debug);
1.599     albertel 1059:     return $value;
                   1060: }
                   1061: 
                   1062: sub make_room {
                   1063:     my ($id,$value,$debug)=@_;
                   1064:     $remembered{$id}=$value;
                   1065:     if ($to_remember<0) { return; }
                   1066:     $accessed{$id}=[&gettimeofday()];
                   1067:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1068:     my $to_kick;
                   1069:     my $max_time=0;
                   1070:     foreach my $other (keys(%accessed)) {
                   1071: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1072: 	    $to_kick=$other;
                   1073: 	    $max_time=&tv_interval($accessed{$other});
                   1074: 	}
                   1075:     }
                   1076:     delete($remembered{$to_kick});
                   1077:     delete($accessed{$to_kick});
                   1078:     $kicks++;
                   1079:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1080:     return;
                   1081: }
                   1082: 
1.599     albertel 1083: sub purge_remembered {
1.604     albertel 1084:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1085:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1086:     undef(%remembered);
                   1087:     undef(%accessed);
1.428     albertel 1088: }
1.70      www      1089: # ------------------------------------- Read an entry from a user's environment
                   1090: 
                   1091: sub userenvironment {
                   1092:     my ($udom,$unam,@what)=@_;
                   1093:     my %returnhash=();
                   1094:     my @answer=split(/\&/,
                   1095:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1096:                       &homeserver($unam,$udom)));
                   1097:     my $i;
                   1098:     for ($i=0;$i<=$#what;$i++) {
                   1099: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1100:     }
                   1101:     return %returnhash;
1.1       albertel 1102: }
                   1103: 
1.617     albertel 1104: # ---------------------------------------------------------- Get a studentphoto
                   1105: sub studentphoto {
                   1106:     my ($udom,$unam,$ext) = @_;
                   1107:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1108:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1109:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1110:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1111:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1112:             } else {
                   1113:                 my ($result,$perm_reqd)=
1.707     albertel 1114: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1115:                 if ($result eq 'ok') {
                   1116:                     if (!($perm_reqd eq 'yes')) {
                   1117:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1118:                     }
                   1119:                 }
                   1120:             }
                   1121:         }
                   1122:     } else {
                   1123:         my ($result,$perm_reqd) = 
1.707     albertel 1124: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1125:         if ($result eq 'ok') {
                   1126:             if (!($perm_reqd eq 'yes')) {
                   1127:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1128:             }
                   1129:         }
                   1130:     }
                   1131:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1132: }
                   1133: 
                   1134: sub retrievestudentphoto {
                   1135:     my ($udom,$unam,$ext,$type) = @_;
                   1136:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1137:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1138:     if ($ret eq 'ok') {
                   1139:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1140:         if ($type eq 'thumbnail') {
                   1141:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1142:         }
                   1143:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1144:         return $tokenurl;
                   1145:     } else {
                   1146:         if ($type eq 'thumbnail') {
                   1147:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1148:         } else { 
                   1149:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1150:         }
1.617     albertel 1151:     }
                   1152: }
                   1153: 
1.263     www      1154: # -------------------------------------------------------------------- New chat
                   1155: 
                   1156: sub chatsend {
1.724     raeburn  1157:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1158:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1159:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1160:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1161:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1162: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1163: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1164: }
                   1165: 
                   1166: # ------------------------------------------ Find current version of a resource
                   1167: 
                   1168: sub getversion {
                   1169:     my $fname=&clutter(shift);
                   1170:     unless ($fname=~/^\/res\//) { return -1; }
                   1171:     return &currentversion(&filelocation('',$fname));
                   1172: }
                   1173: 
                   1174: sub currentversion {
                   1175:     my $fname=shift;
1.599     albertel 1176:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1177:     if (defined($cached)) { return $result; }
1.292     www      1178:     my $author=$fname;
                   1179:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1180:     my ($udom,$uname)=split(/\//,$author);
                   1181:     my $home=homeserver($uname,$udom);
                   1182:     if ($home eq 'no_host') { 
                   1183:         return -1; 
                   1184:     }
                   1185:     my $answer=reply("currentversion:$fname",$home);
                   1186:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1187: 	return -1;
                   1188:     }
1.599     albertel 1189:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1190: }
                   1191: 
1.1       albertel 1192: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1193: 
1.1       albertel 1194: sub subscribe {
                   1195:     my $fname=shift;
1.761     raeburn  1196:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1197:     $fname=~s/[\n\r]//g;
1.1       albertel 1198:     my $author=$fname;
                   1199:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1200:     my ($udom,$uname)=split(/\//,$author);
                   1201:     my $home=homeserver($uname,$udom);
1.335     albertel 1202:     if ($home eq 'no_host') {
                   1203:         return 'not_found';
1.1       albertel 1204:     }
                   1205:     my $answer=reply("sub:$fname",$home);
1.64      www      1206:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1207: 	$answer.=' by '.$home;
                   1208:     }
1.1       albertel 1209:     return $answer;
                   1210: }
                   1211:     
1.8       www      1212: # -------------------------------------------------------------- Replicate file
                   1213: 
                   1214: sub repcopy {
                   1215:     my $filename=shift;
1.23      www      1216:     $filename=~s/\/+/\//g;
1.607     raeburn  1217:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1218:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1219:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1220: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1221: 	return &repcopy_userfile($filename);
                   1222:     }
1.532     albertel 1223:     $filename=~s/[\n\r]//g;
1.8       www      1224:     my $transname="$filename.in.transfer";
1.828     www      1225: # FIXME: this should flock
1.607     raeburn  1226:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1227:     my $remoteurl=subscribe($filename);
1.64      www      1228:     if ($remoteurl =~ /^con_lost by/) {
                   1229: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1230:            return 'unavailable';
1.8       www      1231:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1232: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1233: 	   return 'not_found';
1.64      www      1234:     } elsif ($remoteurl =~ /^rejected by/) {
                   1235: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1236:            return 'forbidden';
1.20      www      1237:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1238:            return 'ok';
1.8       www      1239:     } else {
1.290     www      1240:         my $author=$filename;
                   1241:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1242:         my ($udom,$uname)=split(/\//,$author);
                   1243:         my $home=homeserver($uname,$udom);
                   1244:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1245:            my @parts=split(/\//,$filename);
                   1246:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1247:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1248:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1249: 	       return 'bad_request';
1.8       www      1250:            }
                   1251:            my $count;
                   1252:            for ($count=5;$count<$#parts;$count++) {
                   1253:                $path.="/$parts[$count]";
                   1254:                if ((-e $path)!=1) {
                   1255: 		   mkdir($path,0777);
                   1256:                }
                   1257:            }
                   1258:            my $ua=new LWP::UserAgent;
                   1259:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1260:            my $response=$ua->request($request,$transname);
                   1261:            if ($response->is_error()) {
                   1262: 	       unlink($transname);
                   1263:                my $message=$response->status_line;
1.672     albertel 1264:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1265:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1266:                return 'unavailable';
1.8       www      1267:            } else {
1.16      www      1268: 	       if ($remoteurl!~/\.meta$/) {
                   1269:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1270:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1271:                   if ($mresponse->is_error()) {
                   1272: 		      unlink($filename.'.meta');
                   1273:                       &logthis(
1.672     albertel 1274:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1275:                   }
                   1276: 	       }
1.8       www      1277:                rename($transname,$filename);
1.607     raeburn  1278:                return 'ok';
1.8       www      1279:            }
1.290     www      1280:        }
1.8       www      1281:     }
1.330     www      1282: }
                   1283: 
                   1284: # ------------------------------------------------ Get server side include body
                   1285: sub ssi_body {
1.381     albertel 1286:     my ($filelink,%form)=@_;
1.606     matthew  1287:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1288:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1289:     }
1.330     www      1290:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1291:                                      &ssi($filelink,%form));
1.778     albertel 1292:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1293:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1294:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1295:     return $output;
1.8       www      1296: }
                   1297: 
1.15      www      1298: # --------------------------------------------------------- Server Side Include
                   1299: 
1.782     albertel 1300: sub absolute_url {
                   1301:     my ($host_name) = @_;
                   1302:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1303:     if ($host_name eq '') {
                   1304: 	$host_name = $ENV{'SERVER_NAME'};
                   1305:     }
                   1306:     return $protocol.$host_name;
                   1307: }
                   1308: 
1.15      www      1309: sub ssi {
                   1310: 
1.23      www      1311:     my ($fn,%form)=@_;
1.15      www      1312: 
                   1313:     my $ua=new LWP::UserAgent;
1.23      www      1314:     
                   1315:     my $request;
1.711     albertel 1316: 
                   1317:     $form{'no_update_last_known'}=1;
                   1318: 
1.23      www      1319:     if (%form) {
1.782     albertel 1320:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1321:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1322:     } else {
1.782     albertel 1323:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1324:     }
                   1325: 
1.15      www      1326:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1327:     my $response=$ua->request($request);
                   1328: 
1.324     www      1329:     return $response->content;
                   1330: }
                   1331: 
                   1332: sub externalssi {
                   1333:     my ($url)=@_;
                   1334:     my $ua=new LWP::UserAgent;
                   1335:     my $request=new HTTP::Request('GET',$url);
                   1336:     my $response=$ua->request($request);
1.15      www      1337:     return $response->content;
                   1338: }
1.254     www      1339: 
1.492     albertel 1340: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1341: 
                   1342: sub allowuploaded {
                   1343:     my ($srcurl,$url)=@_;
                   1344:     $url=&clutter(&declutter($url));
                   1345:     my $dir=$url;
                   1346:     $dir=~s/\/[^\/]+$//;
                   1347:     my %httpref=();
                   1348:     my $httpurl=&hreflocation('',$url);
                   1349:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1350:     &Apache::lonnet::appenv(%httpref);
1.254     www      1351: }
1.477     raeburn  1352: 
1.478     albertel 1353: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1354: # input: action, courseID, current domain, intended
1.637     raeburn  1355: #        path to file, source of file, instruction to parse file for objects,
                   1356: #        ref to hash for embedded objects,
                   1357: #        ref to hash for codebase of java objects.
                   1358: #
1.485     raeburn  1359: # output: url to file (if action was uploaddoc), 
                   1360: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1361: #
1.478     albertel 1362: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1363: # course.
1.477     raeburn  1364: #
1.478     albertel 1365: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1366: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1367: #          course's home server.
1.477     raeburn  1368: #
1.478     albertel 1369: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1370: #          be copied from $source (current location) to 
                   1371: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1372: #         and will then be copied to
                   1373: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1374: #         course's home server.
1.485     raeburn  1375: #
1.481     raeburn  1376: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1377: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1378: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1379: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1380: #         in course's home server.
1.637     raeburn  1381: #
1.477     raeburn  1382: 
                   1383: sub process_coursefile {
1.638     albertel 1384:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1385:     my $fetchresult;
1.638     albertel 1386:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1387:     if ($action eq 'propagate') {
1.638     albertel 1388:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1389: 			     $home);
1.481     raeburn  1390:     } else {
1.477     raeburn  1391:         my $fpath = '';
                   1392:         my $fname = $file;
1.478     albertel 1393:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1394:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1395:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1396:         if ($action eq 'copy') {
                   1397:             if ($source eq '') {
                   1398:                 $fetchresult = 'no source file';
                   1399:                 return $fetchresult;
                   1400:             } else {
                   1401:                 my $destination = $filepath.'/'.$fname;
                   1402:                 rename($source,$destination);
                   1403:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1404:                                  $home);
1.481     raeburn  1405:             }
                   1406:         } elsif ($action eq 'uploaddoc') {
                   1407:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1408:             print $fh $env{'form.'.$source};
1.481     raeburn  1409:             close($fh);
1.637     raeburn  1410:             if ($parser eq 'parse') {
                   1411:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1412:                 unless ($parse_result eq 'ok') {
                   1413:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1414:                 }
                   1415:             }
1.477     raeburn  1416:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1417:                                  $home);
1.481     raeburn  1418:             if ($fetchresult eq 'ok') {
                   1419:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1420:             } else {
                   1421:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1422:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1423:                 return '/adm/notfound.html';
                   1424:             }
1.477     raeburn  1425:         }
                   1426:     }
1.485     raeburn  1427:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1428:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1429:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1430:     }
                   1431:     return $fetchresult;
                   1432: }
                   1433: 
1.637     raeburn  1434: sub build_filepath {
                   1435:     my ($fpath) = @_;
                   1436:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1437:     unless ($fpath eq '') {
                   1438:         my @parts=split('/',$fpath);
                   1439:         foreach my $part (@parts) {
                   1440:             $filepath.= '/'.$part;
                   1441:             if ((-e $filepath)!=1) {
                   1442:                 mkdir($filepath,0777);
                   1443:             }
                   1444:         }
                   1445:     }
                   1446:     return $filepath;
                   1447: }
                   1448: 
                   1449: sub store_edited_file {
1.638     albertel 1450:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1451:     my $file = $primary_url;
                   1452:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1453:     my $fpath = '';
                   1454:     my $fname = $file;
                   1455:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1456:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1457:     my $filepath = &build_filepath($fpath);
                   1458:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1459:     print $fh $content;
                   1460:     close($fh);
1.638     albertel 1461:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1462:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1463: 			  $home);
1.637     raeburn  1464:     if ($$fetchresult eq 'ok') {
                   1465:         return '/uploaded/'.$fpath.'/'.$fname;
                   1466:     } else {
1.638     albertel 1467:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1468: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1469:         return '/adm/notfound.html';
                   1470:     }
                   1471: }
                   1472: 
1.531     albertel 1473: sub clean_filename {
1.831     albertel 1474:     my ($fname,$args)=@_;
1.315     www      1475: # Replace Windows backslashes by forward slashes
1.257     www      1476:     $fname=~s/\\/\//g;
1.831     albertel 1477:     if (!$args->{'keep_path'}) {
                   1478:         # Get rid of everything but the actual filename
                   1479: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1480:     }
1.315     www      1481: # Replace spaces by underscores
                   1482:     $fname=~s/\s+/\_/g;
                   1483: # Replace all other weird characters by nothing
1.831     albertel 1484:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1485: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1486: # numbers
                   1487:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1488:     return $fname;
                   1489: }
                   1490: 
1.608     albertel 1491: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1492: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1493: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1494: #        $coursedoc - if true up to the current course
                   1495: #                     if false
                   1496: #        $subdir - directory in userfile to store the file into
                   1497: #        $parser, $allfiles, $codebase - unknown
                   1498: #
                   1499: # output: url of file in userspace, or error: <message> 
                   1500: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1501: 
                   1502: 
1.531     albertel 1503: sub userfileupload {
1.719     banghart 1504:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1505:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1506:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1507:     $fname=&clean_filename($fname);
1.315     www      1508: # See if there is anything left
1.257     www      1509:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1510:     chop($env{'form.'.$formname});
1.523     raeburn  1511:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1512:         my $now = time;
                   1513:         my $filepath = 'tmp/helprequests/'.$now;
                   1514:         my @parts=split(/\//,$filepath);
                   1515:         my $fullpath = $perlvar{'lonDaemons'};
                   1516:         for (my $i=0;$i<@parts;$i++) {
                   1517:             $fullpath .= '/'.$parts[$i];
                   1518:             if ((-e $fullpath)!=1) {
                   1519:                 mkdir($fullpath,0777);
                   1520:             }
                   1521:         }
                   1522:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1523:         print $fh $env{'form.'.$formname};
1.523     raeburn  1524:         close($fh);
1.741     raeburn  1525:         return $fullpath.'/'.$fname;
                   1526:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1527:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1528:                        '_'.$env{'user.domain'}.'/pending';
                   1529:         my @parts=split(/\//,$filepath);
                   1530:         my $fullpath = $perlvar{'lonDaemons'};
                   1531:         for (my $i=0;$i<@parts;$i++) {
                   1532:             $fullpath .= '/'.$parts[$i];
                   1533:             if ((-e $fullpath)!=1) {
                   1534:                 mkdir($fullpath,0777);
                   1535:             }
                   1536:         }
                   1537:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1538:         print $fh $env{'form.'.$formname};
                   1539:         close($fh);
                   1540:         return $fullpath.'/'.$fname;
1.523     raeburn  1541:     }
1.719     banghart 1542:     
1.258     www      1543: # Create the directory if not present
1.493     albertel 1544:     $fname="$subdir/$fname";
1.259     www      1545:     if ($coursedoc) {
1.638     albertel 1546: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1547: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1548:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1549:             return &finishuserfileupload($docuname,$docudom,
                   1550: 					 $formname,$fname,$parser,$allfiles,
                   1551: 					 $codebase);
1.481     raeburn  1552:         } else {
1.620     albertel 1553:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1554:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1555: 				       $fname,$formname,$parser,
                   1556: 				       $allfiles,$codebase);
1.481     raeburn  1557:         }
1.719     banghart 1558:     } elsif (defined($destuname)) {
                   1559:         my $docuname=$destuname;
                   1560:         my $docudom=$destudom;
                   1561: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1562: 				     $fname,$parser,$allfiles,$codebase);
                   1563:         
1.259     www      1564:     } else {
1.638     albertel 1565:         my $docuname=$env{'user.name'};
                   1566:         my $docudom=$env{'user.domain'};
1.714     raeburn  1567:         if (exists($env{'form.group'})) {
                   1568:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1569:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1570:         }
1.638     albertel 1571: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1572: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1573:     }
1.271     www      1574: }
                   1575: 
                   1576: sub finishuserfileupload {
1.638     albertel 1577:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1578:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1579:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1580:     my ($fnamepath,$file);
                   1581:     $file=$fname;
                   1582:     if ($fname=~m|/|) {
                   1583:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1584: 	$path.=$fnamepath.'/';
                   1585:     }
1.259     www      1586:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1587:     my $count;
                   1588:     for ($count=4;$count<=$#parts;$count++) {
                   1589:         $filepath.="/$parts[$count]";
                   1590:         if ((-e $filepath)!=1) {
                   1591: 	    mkdir($filepath,0777);
                   1592:         }
                   1593:     }
                   1594: # Save the file
                   1595:     {
1.701     albertel 1596: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1597: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1598: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1599: 	    return '/adm/notfound.html';
                   1600: 	}
                   1601: 	if (!print FH ($env{'form.'.$formname})) {
                   1602: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1603: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1604: 	    return '/adm/notfound.html';
                   1605: 	}
1.570     albertel 1606: 	close(FH);
1.258     www      1607:     }
1.637     raeburn  1608:     if ($parser eq 'parse') {
1.638     albertel 1609:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1610: 						   $codebase);
1.637     raeburn  1611:         unless ($parse_result eq 'ok') {
1.638     albertel 1612:             &logthis('Failed to parse '.$filepath.$file.
                   1613: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1614:         }
                   1615:     }
1.259     www      1616: # Notify homeserver to grep it
                   1617: #
1.638     albertel 1618:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1619:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1620:     if ($fetchresult eq 'ok') {
1.259     www      1621: #
1.258     www      1622: # Return the URL to it
1.494     albertel 1623:         return '/uploaded/'.$path.$file;
1.263     www      1624:     } else {
1.494     albertel 1625:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1626: 		 ': '.$fetchresult);
1.263     www      1627:         return '/adm/notfound.html';
                   1628:     }    
1.493     albertel 1629: }
                   1630: 
1.637     raeburn  1631: sub extract_embedded_items {
1.648     raeburn  1632:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1633:     my @state = ();
                   1634:     my %javafiles = (
                   1635:                       codebase => '',
                   1636:                       code => '',
                   1637:                       archive => ''
                   1638:                     );
                   1639:     my %mediafiles = (
                   1640:                       src => '',
                   1641:                       movie => '',
                   1642:                      );
1.648     raeburn  1643:     my $p;
                   1644:     if ($content) {
                   1645:         $p = HTML::LCParser->new($content);
                   1646:     } else {
                   1647:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1648:     }
1.641     albertel 1649:     while (my $t=$p->get_token()) {
1.640     albertel 1650: 	if ($t->[0] eq 'S') {
                   1651: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1652: 	    push (@state, $tagname);
1.648     raeburn  1653:             if (lc($tagname) eq 'allow') {
                   1654:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1655:             }
1.640     albertel 1656: 	    if (lc($tagname) eq 'img') {
                   1657: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1658: 	    }
1.645     raeburn  1659:             if (lc($tagname) eq 'script') {
                   1660:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1661:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1662:                 } else {
                   1663:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1664:                 }
                   1665:             }
                   1666:             if (lc($tagname) eq 'link') {
                   1667:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1668:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1669:                 }
                   1670:             }
1.640     albertel 1671: 	    if (lc($tagname) eq 'object' ||
                   1672: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1673: 		foreach my $item (keys(%javafiles)) {
                   1674: 		    $javafiles{$item} = '';
                   1675: 		}
                   1676: 	    }
                   1677: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1678: 		my $name = lc($attr->{'name'});
                   1679: 		foreach my $item (keys(%javafiles)) {
                   1680: 		    if ($name eq $item) {
                   1681: 			$javafiles{$item} = $attr->{'value'};
                   1682: 			last;
                   1683: 		    }
                   1684: 		}
                   1685: 		foreach my $item (keys(%mediafiles)) {
                   1686: 		    if ($name eq $item) {
                   1687: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1688: 			last;
                   1689: 		    }
                   1690: 		}
                   1691: 	    }
                   1692: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1693: 		foreach my $item (keys(%javafiles)) {
                   1694: 		    if ($attr->{$item}) {
                   1695: 			$javafiles{$item} = $attr->{$item};
                   1696: 			last;
                   1697: 		    }
                   1698: 		}
                   1699: 		foreach my $item (keys(%mediafiles)) {
                   1700: 		    if ($attr->{$item}) {
                   1701: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1702: 			last;
                   1703: 		    }
                   1704: 		}
                   1705: 	    }
                   1706: 	} elsif ($t->[0] eq 'E') {
                   1707: 	    my ($tagname) = ($t->[1]);
                   1708: 	    if ($javafiles{'codebase'} ne '') {
                   1709: 		$javafiles{'codebase'} .= '/';
                   1710: 	    }  
                   1711: 	    if (lc($tagname) eq 'applet' ||
                   1712: 		lc($tagname) eq 'object' ||
                   1713: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1714: 		) {
                   1715: 		foreach my $item (keys(%javafiles)) {
                   1716: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1717: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1718: 			&add_filetype($allfiles,$file,$item);
                   1719: 		    }
                   1720: 		}
                   1721: 	    } 
                   1722: 	    pop @state;
                   1723: 	}
                   1724:     }
1.637     raeburn  1725:     return 'ok';
                   1726: }
                   1727: 
1.639     albertel 1728: sub add_filetype {
                   1729:     my ($allfiles,$file,$type)=@_;
                   1730:     if (exists($allfiles->{$file})) {
                   1731: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1732: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1733: 	}
                   1734:     } else {
                   1735: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1736:     }
                   1737: }
                   1738: 
1.493     albertel 1739: sub removeuploadedurl {
                   1740:     my ($url)=@_;
                   1741:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1742:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1743: }
                   1744: 
                   1745: sub removeuserfile {
                   1746:     my ($docuname,$docudom,$fname)=@_;
                   1747:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1748:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1749:     if ($result eq 'ok') {
                   1750:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1751:             my $metafile = $fname.'.meta';
                   1752:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1753: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1754:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1755:             my $sqlresult = 
1.823     albertel 1756:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1757:                                         'portfolio_metadata',$group,
                   1758:                                         'delete');
1.798     raeburn  1759:         }
                   1760:     }
                   1761:     return $result;
1.257     www      1762: }
1.15      www      1763: 
1.530     albertel 1764: sub mkdiruserfile {
                   1765:     my ($docuname,$docudom,$dir)=@_;
                   1766:     my $home=&homeserver($docuname,$docudom);
                   1767:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1768: }
                   1769: 
1.531     albertel 1770: sub renameuserfile {
                   1771:     my ($docuname,$docudom,$old,$new)=@_;
                   1772:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1773:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1774:                         &escape("$old").':'.&escape("$new"),$home);
                   1775:     if ($result eq 'ok') {
                   1776:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1777:             my $oldmeta = $old.'.meta';
                   1778:             my $newmeta = $new.'.meta';
                   1779:             my $metaresult = 
                   1780:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1781: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1782:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1783:             my $sqlresult = 
1.823     albertel 1784:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1785:                                         'portfolio_metadata',$group,
                   1786:                                         'delete');
1.798     raeburn  1787:         }
                   1788:     }
                   1789:     return $result;
1.531     albertel 1790: }
                   1791: 
1.14      www      1792: # ------------------------------------------------------------------------- Log
                   1793: 
                   1794: sub log {
                   1795:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1796:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1797: }
                   1798: 
                   1799: # ------------------------------------------------------------------ Course Log
1.352     www      1800: #
                   1801: # This routine flushes several buffers of non-mission-critical nature
                   1802: #
1.157     www      1803: 
                   1804: sub flushcourselogs {
1.352     www      1805:     &logthis('Flushing log buffers');
                   1806: #
                   1807: # course logs
                   1808: # This is a log of all transactions in a course, which can be used
                   1809: # for data mining purposes
                   1810: #
                   1811: # It also collects the courseid database, which lists last transaction
                   1812: # times and course titles for all courseids
                   1813: #
                   1814:     my %courseidbuffer=();
1.800     albertel 1815:     foreach my $crsid (keys %courselogs) {
1.352     www      1816:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1817: 		          &escape($courselogs{$crsid}),
                   1818: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1819: 	    delete $courselogs{$crsid};
                   1820:         } else {
                   1821:             &logthis('Failed to flush log buffer for '.$crsid);
                   1822:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1823:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1824:                         " exceeded maximum size, deleting.</font>");
                   1825:                delete $courselogs{$crsid};
                   1826:             }
1.352     www      1827:         }
                   1828:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1829:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1830: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1831:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1832:         } else {
                   1833:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1834: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1835:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1836:         }
1.191     harris41 1837:     }
1.352     www      1838: #
                   1839: # Write course id database (reverse lookup) to homeserver of courses 
                   1840: # Is used in pickcourse
                   1841: #
1.840     albertel 1842:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1843:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1844: 		     $crs_home);
1.352     www      1845:     }
                   1846: #
                   1847: # File accesses
                   1848: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1849: #
1.449     matthew  1850:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1851:         if ($entry =~ /___count$/) {
                   1852:             my ($dom,$name);
1.807     albertel 1853:             ($dom,$name,undef)=
1.811     albertel 1854: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1855:             if (! defined($dom) || $dom eq '' || 
                   1856:                 ! defined($name) || $name eq '') {
1.620     albertel 1857:                 my $cid = $env{'request.course.id'};
                   1858:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1859:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1860:             }
1.450     matthew  1861:             my $value = $accesshash{$entry};
                   1862:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1863:             my %temphash=($url => $value);
1.449     matthew  1864:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1865:             if ($result eq 'ok') {
                   1866:                 delete $accesshash{$entry};
                   1867:             } elsif ($result eq 'unknown_cmd') {
                   1868:                 # Target server has old code running on it.
1.450     matthew  1869:                 my %temphash=($entry => $value);
1.449     matthew  1870:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1871:                     delete $accesshash{$entry};
                   1872:                 }
                   1873:             }
                   1874:         } else {
1.811     albertel 1875:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1876:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1877:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1878:                 delete $accesshash{$entry};
                   1879:             }
1.185     www      1880:         }
1.191     harris41 1881:     }
1.352     www      1882: #
                   1883: # Roles
                   1884: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1885: #
1.800     albertel 1886:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1887:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1888: 	    split(/\:/,$entry);
                   1889:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1890:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1891:                 $rudom,$runame) eq 'ok') {
                   1892: 	    delete $userrolehash{$entry};
                   1893:         }
                   1894:     }
1.662     raeburn  1895: #
                   1896: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1897: #
                   1898:     my %domrolebuffer = ();
                   1899:     foreach my $entry (keys %domainrolehash) {
                   1900:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1901:         if ($domrolebuffer{$rudom}) {
                   1902:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1903:                       '='.&escape($domainrolehash{$entry});
                   1904:         } else {
                   1905:             $domrolebuffer{$rudom}.=&escape($entry).
                   1906:                       '='.&escape($domainrolehash{$entry});
                   1907:         }
                   1908:         delete $domainrolehash{$entry};
                   1909:     }
                   1910:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 1911: 	my %servers = &get_servers($dom,'library');
                   1912: 	foreach my $tryserver (keys(%servers)) {
                   1913: 	    unless (&reply('domroleput:'.$dom.':'.
                   1914: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1915: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1916: 	    }
1.662     raeburn  1917:         }
                   1918:     }
1.186     www      1919:     $dumpcount++;
1.157     www      1920: }
                   1921: 
                   1922: sub courselog {
                   1923:     my $what=shift;
1.158     www      1924:     $what=time.':'.$what;
1.620     albertel 1925:     unless ($env{'request.course.id'}) { return ''; }
                   1926:     $coursedombuf{$env{'request.course.id'}}=
                   1927:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1928:     $coursenumbuf{$env{'request.course.id'}}=
                   1929:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1930:     $coursehombuf{$env{'request.course.id'}}=
                   1931:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1932:     $coursedescrbuf{$env{'request.course.id'}}=
                   1933:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1934:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1935:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1936:     $courseownerbuf{$env{'request.course.id'}}=
                   1937:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1938:     $coursetypebuf{$env{'request.course.id'}}=
                   1939:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1940:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1941: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1942:     } else {
1.620     albertel 1943: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1944:     }
1.620     albertel 1945:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1946: 	&flushcourselogs();
                   1947:     }
1.158     www      1948: }
                   1949: 
                   1950: sub courseacclog {
                   1951:     my $fnsymb=shift;
1.620     albertel 1952:     unless ($env{'request.course.id'}) { return ''; }
                   1953:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1954:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1955:         $what.=':POST';
1.583     matthew  1956:         # FIXME: Probably ought to escape things....
1.800     albertel 1957: 	foreach my $key (keys(%env)) {
                   1958:             if ($key=~/^form\.(.*)/) {
                   1959: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1960:             }
1.191     harris41 1961:         }
1.583     matthew  1962:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1963:         # FIXME: We should not be depending on a form parameter that someone
                   1964:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1965:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1966:             $what.= ':POST';
                   1967:             # FIXME: Probably ought to escape things....
                   1968:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1969:                                  'crsdiscuss') {
1.620     albertel 1970:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1971:             }
                   1972:         }
1.158     www      1973:     }
                   1974:     &courselog($what);
1.149     www      1975: }
                   1976: 
1.185     www      1977: sub countacc {
                   1978:     my $url=&declutter(shift);
1.458     matthew  1979:     return if (! defined($url) || $url eq '');
1.620     albertel 1980:     unless ($env{'request.course.id'}) { return ''; }
                   1981:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1982:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1983:     $accesshash{$key}++;
1.185     www      1984: }
1.349     www      1985: 
1.361     www      1986: sub linklog {
                   1987:     my ($from,$to)=@_;
                   1988:     $from=&declutter($from);
                   1989:     $to=&declutter($to);
                   1990:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1991:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1992: }
                   1993:   
1.349     www      1994: sub userrolelog {
                   1995:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1996:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1997:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1998:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1999:         ($trole=~/^ta/)) {
1.350     www      2000:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2001:        $userrolehash
                   2002:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2003:                     =$tend.':'.$tstart;
1.662     raeburn  2004:     }
                   2005:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2006:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2007:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2008:         ($trole=~/^sc/)) {
                   2009:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2010:        $domainrolehash
                   2011:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2012:                     = $tend.':'.$tstart;
                   2013:     }
1.351     www      2014: }
                   2015: 
                   2016: sub get_course_adv_roles {
                   2017:     my $cid=shift;
1.620     albertel 2018:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2019:     my %coursehash=&coursedescription($cid);
1.470     www      2020:     my %nothide=();
1.800     albertel 2021:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2022: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2023:     }
1.351     www      2024:     my %returnhash=();
                   2025:     my %dumphash=
                   2026:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2027:     my $now=time;
1.800     albertel 2028:     foreach my $entry (keys %dumphash) {
                   2029: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2030:         if (($tstart) && ($tstart<0)) { next; }
                   2031:         if (($tend) && ($tend<$now)) { next; }
                   2032:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2033:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2034: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2035: 	if ((&privileged($username,$domain)) && 
                   2036: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2037: 	if ($role eq 'cr') { next; }
1.351     www      2038:         my $key=&plaintext($role);
                   2039:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2040:         if ($returnhash{$key}) {
                   2041: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2042:         } else {
                   2043:             $returnhash{$key}=$username.':'.$domain;
                   2044:         }
1.400     www      2045:      }
                   2046:     return %returnhash;
                   2047: }
                   2048: 
                   2049: sub get_my_roles {
1.832     raeburn  2050:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
1.620     albertel 2051:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2052:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2053:     my %dumphash=
                   2054:             &dump('nohist_userroles',$udom,$uname);
                   2055:     my %returnhash=();
                   2056:     my $now=time;
1.800     albertel 2057:     foreach my $entry (keys(%dumphash)) {
                   2058: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2059:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2060:         my $status = 'active';
                   2061:         if (($tend) && ($tend<$now)) {
                   2062:             $status = 'previous';
                   2063:         } 
                   2064:         if (($tstart) && ($now<$tstart)) {
                   2065:             $status = 'future';
                   2066:         }
                   2067:         if (ref($types) eq 'ARRAY') {
                   2068:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2069:                 next;
                   2070:             } 
                   2071:         } else {
                   2072:             if ($status ne 'active') {
                   2073:                 next;
                   2074:             }
                   2075:         }
1.800     albertel 2076:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.832     raeburn  2077:         if (ref($roledoms) eq 'ARRAY') {
                   2078:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2079:                 next;
                   2080:             }
                   2081:         }
                   2082:         if (ref($roles) eq 'ARRAY') {
                   2083:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2084:                 next;
                   2085:             }
                   2086:         } 
1.400     www      2087: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2088:     }
1.373     www      2089:     return %returnhash;
1.399     www      2090: }
                   2091: 
                   2092: # ----------------------------------------------------- Frontpage Announcements
                   2093: #
                   2094: #
                   2095: 
                   2096: sub postannounce {
                   2097:     my ($server,$text)=@_;
1.844     albertel 2098:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2099:     unless ($text=~/\w/) { $text=''; }
                   2100:     return &reply('setannounce:'.&escape($text),$server);
                   2101: }
                   2102: 
                   2103: sub getannounce {
1.448     albertel 2104: 
                   2105:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2106: 	my $announcement='';
1.800     albertel 2107: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2108: 	close($fh);
1.399     www      2109: 	if ($announcement=~/\w/) { 
                   2110: 	    return 
                   2111:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2112:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2113: 	} else {
                   2114: 	    return '';
                   2115: 	}
                   2116:     } else {
                   2117: 	return '';
                   2118:     }
1.351     www      2119: }
1.353     www      2120: 
                   2121: # ---------------------------------------------------------- Course ID routines
                   2122: # Deal with domain's nohist_courseid.db files
                   2123: #
                   2124: 
                   2125: sub courseidput {
                   2126:     my ($domain,$what,$coursehome)=@_;
                   2127:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2128: }
                   2129: 
                   2130: sub courseiddump {
1.791     raeburn  2131:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2132:     my %returnhash=();
1.355     www      2133:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2134:     my %libserv = &all_library();
                   2135:     foreach my $tryserver (keys(%libserv)) {
                   2136:         if ( (  $hostidflag == 1 
                   2137: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2138: 	     || (!defined($hostidflag)) ) {
                   2139: 
                   2140: 	    if ($domfilter eq ''
                   2141: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2142: 	        foreach my $line (
1.844     albertel 2143:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2144: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2145:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2146:                                $tryserver))) {
1.800     albertel 2147: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2148:                     if (($key) && ($value)) {
1.516     raeburn  2149: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2150:                     }
1.353     www      2151:                 }
                   2152:             }
                   2153:         }
                   2154:     }
                   2155:     return %returnhash;
                   2156: }
                   2157: 
1.658     raeburn  2158: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2159: 
                   2160: sub dcmailput {
1.685     raeburn  2161:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2162:     my $status = &Apache::lonnet::critical(
1.740     www      2163:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2164:        &escape($message),$server);
1.662     raeburn  2165:     return $status;
                   2166: }
                   2167: 
1.658     raeburn  2168: sub dcmaildump {
                   2169:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2170:     my %returnhash=();
1.846     albertel 2171: 
                   2172:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2173:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2174:                                                          &escape($enddate).':';
                   2175: 	my @esc_senders=map { &escape($_)} @$senders;
                   2176: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2177: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2178:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2179:             if (($key) && ($value)) {
                   2180:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2181:             }
                   2182:         }
                   2183:     }
                   2184:     return %returnhash;
                   2185: }
1.662     raeburn  2186: # ---------------------------------------------------------- Domain roles
                   2187: 
                   2188: sub get_domain_roles {
                   2189:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2190:     if (undef($startdate) || $startdate eq '') {
                   2191:         $startdate = '.';
                   2192:     }
                   2193:     if (undef($enddate) || $enddate eq '') {
                   2194:         $enddate = '.';
                   2195:     }
                   2196:     my $rolelist = join(':',@{$roles});
                   2197:     my %personnel = ();
1.841     albertel 2198: 
                   2199:     my %servers = &get_servers($dom,'library');
                   2200:     foreach my $tryserver (keys(%servers)) {
                   2201: 	%{$personnel{$tryserver}}=();
                   2202: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2203: 					    &escape($startdate).':'.
                   2204: 					    &escape($enddate).':'.
                   2205: 					    &escape($rolelist), $tryserver))) {
                   2206: 	    my ($key,$value) = split(/\=/,$line,2);
                   2207: 	    if (($key) && ($value)) {
                   2208: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2209: 	    }
                   2210: 	}
1.662     raeburn  2211:     }
                   2212:     return %personnel;
                   2213: }
1.658     raeburn  2214: 
1.149     www      2215: # ----------------------------------------------------------- Check out an item
                   2216: 
1.504     albertel 2217: sub get_first_access {
                   2218:     my ($type,$argsymb)=@_;
1.790     albertel 2219:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2220:     if ($argsymb) { $symb=$argsymb; }
                   2221:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2222:     if ($type eq 'map') {
                   2223: 	$res=&symbread($map);
                   2224:     } else {
                   2225: 	$res=$symb;
                   2226:     }
                   2227:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2228:     return $times{"$courseid\0$res"};
1.504     albertel 2229: }
                   2230: 
                   2231: sub set_first_access {
                   2232:     my ($type)=@_;
1.790     albertel 2233:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2234:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2235:     if ($type eq 'map') {
                   2236: 	$res=&symbread($map);
                   2237:     } else {
                   2238: 	$res=$symb;
                   2239:     }
                   2240:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2241:     if (!$firstaccess) {
1.588     albertel 2242: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2243:     }
                   2244:     return 'already_set';
1.504     albertel 2245: }
                   2246: 
1.149     www      2247: sub checkout {
                   2248:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2249:     my $now=time;
                   2250:     my $lonhost=$perlvar{'lonHostID'};
                   2251:     my $infostr=&escape(
1.234     www      2252:                  'CHECKOUTTOKEN&'.
1.149     www      2253:                  $tuname.'&'.
                   2254:                  $tudom.'&'.
                   2255:                  $tcrsid.'&'.
                   2256:                  $symb.'&'.
                   2257: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2258:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2259:     if ($token=~/^error\:/) { 
1.672     albertel 2260:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2261:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2262:                  "</font>");
                   2263:         return ''; 
                   2264:     }
                   2265: 
1.149     www      2266:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2267:     $token=~tr/a-z/A-Z/;
                   2268: 
1.153     www      2269:     my %infohash=('resource.0.outtoken' => $token,
                   2270:                   'resource.0.checkouttime' => $now,
                   2271:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2272: 
                   2273:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2274:        return '';
1.151     www      2275:     } else {
1.672     albertel 2276:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2277:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2278:                  "</font>");
1.149     www      2279:     }    
                   2280: 
                   2281:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2282:                          &escape('Checkout '.$infostr.' - '.
                   2283:                                                  $token)) ne 'ok') {
                   2284: 	return '';
1.151     www      2285:     } else {
1.672     albertel 2286:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2287:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2288:                  "</font>");
1.149     www      2289:     }
1.151     www      2290:     return $token;
1.149     www      2291: }
                   2292: 
                   2293: # ------------------------------------------------------------ Check in an item
                   2294: 
                   2295: sub checkin {
                   2296:     my $token=shift;
1.150     www      2297:     my $now=time;
                   2298:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2299:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2300:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2301:     $dtoken=~s/\W/\_/g;
1.234     www      2302:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2303:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2304: 
1.154     www      2305:     unless (($tuname) && ($tudom)) {
                   2306:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2307:         return '';
                   2308:     }
                   2309:     
                   2310:     unless (&allowed('mgr',$tcrsid)) {
                   2311:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2312:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2313:         return '';
                   2314:     }
                   2315: 
1.153     www      2316:     my %infohash=('resource.0.intoken' => $token,
                   2317:                   'resource.0.checkintime' => $now,
                   2318:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2319: 
                   2320:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2321:        return '';
                   2322:     }    
                   2323: 
                   2324:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2325:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2326: 	return '';
                   2327:     }
                   2328: 
                   2329:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2330: }
                   2331: 
                   2332: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2333: 
                   2334: sub expirespread {
                   2335:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2336:     my $cid=$env{'request.course.id'}; 
1.110     www      2337:     if ($cid) {
                   2338:        my $now=time;
                   2339:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2340:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2341:                             $env{'course.'.$cid.'.num'}.
1.110     www      2342: 	        	    ':nohist_expirationdates:'.
                   2343:                             &escape($key).'='.$now,
1.620     albertel 2344:                             $env{'course.'.$cid.'.home'})
1.110     www      2345:     }
                   2346:     return 'ok';
1.14      www      2347: }
                   2348: 
1.109     www      2349: # ----------------------------------------------------- Devalidate Spreadsheets
                   2350: 
                   2351: sub devalidate {
1.325     www      2352:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2353:     my $cid=$env{'request.course.id'}; 
1.109     www      2354:     if ($cid) {
1.391     matthew  2355:         # delete the stored spreadsheets for
                   2356:         # - the student level sheet of this user in course's homespace
                   2357:         # - the assessment level sheet for this resource 
                   2358:         #   for this user in user's homespace
1.553     albertel 2359: 	# - current conditional state info
1.325     www      2360: 	my $key=$uname.':'.$udom.':';
1.109     www      2361:         my $status=
1.299     matthew  2362: 	    &del('nohist_calculatedsheets',
1.391     matthew  2363: 		 [$key.'studentcalc:'],
1.620     albertel 2364: 		 $env{'course.'.$cid.'.domain'},
                   2365: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2366: 		.' '.
                   2367: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2368: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2369:         unless ($status eq 'ok ok') {
                   2370:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2371:                     $uname.' at '.$udom.' for '.
1.109     www      2372: 		    $symb.': '.$status);
1.133     albertel 2373:         }
1.553     albertel 2374: 	&delenv('user.state.'.$cid);
1.109     www      2375:     }
                   2376: }
                   2377: 
1.265     albertel 2378: sub get_scalar {
                   2379:     my ($string,$end) = @_;
                   2380:     my $value;
                   2381:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2382: 	$value = $1;
                   2383:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2384: 	$value = $1;
                   2385:     }
                   2386:     return &unescape($value);
                   2387: }
                   2388: 
                   2389: sub array2str {
                   2390:   my (@array) = @_;
                   2391:   my $result=&arrayref2str(\@array);
                   2392:   $result=~s/^__ARRAY_REF__//;
                   2393:   $result=~s/__END_ARRAY_REF__$//;
                   2394:   return $result;
                   2395: }
                   2396: 
1.204     albertel 2397: sub arrayref2str {
                   2398:   my ($arrayref) = @_;
1.265     albertel 2399:   my $result='__ARRAY_REF__';
1.204     albertel 2400:   foreach my $elem (@$arrayref) {
1.265     albertel 2401:     if(ref($elem) eq 'ARRAY') {
                   2402:       $result.=&arrayref2str($elem).'&';
                   2403:     } elsif(ref($elem) eq 'HASH') {
                   2404:       $result.=&hashref2str($elem).'&';
                   2405:     } elsif(ref($elem)) {
                   2406:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2407:     } else {
                   2408:       $result.=&escape($elem).'&';
                   2409:     }
                   2410:   }
                   2411:   $result=~s/\&$//;
1.265     albertel 2412:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2413:   return $result;
                   2414: }
                   2415: 
1.168     albertel 2416: sub hash2str {
1.204     albertel 2417:   my (%hash) = @_;
                   2418:   my $result=&hashref2str(\%hash);
1.265     albertel 2419:   $result=~s/^__HASH_REF__//;
                   2420:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2421:   return $result;
                   2422: }
                   2423: 
                   2424: sub hashref2str {
                   2425:   my ($hashref)=@_;
1.265     albertel 2426:   my $result='__HASH_REF__';
1.800     albertel 2427:   foreach my $key (sort(keys(%$hashref))) {
                   2428:     if (ref($key) eq 'ARRAY') {
                   2429:       $result.=&arrayref2str($key).'=';
                   2430:     } elsif (ref($key) eq 'HASH') {
                   2431:       $result.=&hashref2str($key).'=';
                   2432:     } elsif (ref($key)) {
1.265     albertel 2433:       $result.='=';
1.800     albertel 2434:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2435:     } else {
1.800     albertel 2436: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2437:     }
                   2438: 
1.800     albertel 2439:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2440:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2441:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2442:       $result.=&hashref2str($hashref->{$key}).'&';
                   2443:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2444:        $result.='&';
1.800     albertel 2445:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2446:     } else {
1.800     albertel 2447:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2448:     }
                   2449:   }
1.168     albertel 2450:   $result=~s/\&$//;
1.265     albertel 2451:   $result .= '__END_HASH_REF__';
1.168     albertel 2452:   return $result;
                   2453: }
                   2454: 
                   2455: sub str2hash {
1.265     albertel 2456:     my ($string)=@_;
                   2457:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2458:     return %$hash;
                   2459: }
                   2460: 
                   2461: sub str2hashref {
1.168     albertel 2462:   my ($string) = @_;
1.265     albertel 2463: 
                   2464:   my %hash;
                   2465: 
                   2466:   if($string !~ /^__HASH_REF__/) {
                   2467:       if (! ($string eq '' || !defined($string))) {
                   2468: 	  $hash{'error'}='Not hash reference';
                   2469:       }
                   2470:       return (\%hash, $string);
                   2471:   }
                   2472: 
                   2473:   $string =~ s/^__HASH_REF__//;
                   2474: 
                   2475:   while($string !~ /^__END_HASH_REF__/) {
                   2476:       #key
                   2477:       my $key='';
                   2478:       if($string =~ /^__HASH_REF__/) {
                   2479:           ($key, $string)=&str2hashref($string);
                   2480:           if(defined($key->{'error'})) {
                   2481:               $hash{'error'}='Bad data';
                   2482:               return (\%hash, $string);
                   2483:           }
                   2484:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2485:           ($key, $string)=&str2arrayref($string);
                   2486:           if($key->[0] eq 'Array reference error') {
                   2487:               $hash{'error'}='Bad data';
                   2488:               return (\%hash, $string);
                   2489:           }
                   2490:       } else {
                   2491:           $string =~ s/^(.*?)=//;
1.267     albertel 2492: 	  $key=&unescape($1);
1.265     albertel 2493:       }
                   2494:       $string =~ s/^=//;
                   2495: 
                   2496:       #value
                   2497:       my $value='';
                   2498:       if($string =~ /^__HASH_REF__/) {
                   2499:           ($value, $string)=&str2hashref($string);
                   2500:           if(defined($value->{'error'})) {
                   2501:               $hash{'error'}='Bad data';
                   2502:               return (\%hash, $string);
                   2503:           }
                   2504:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2505:           ($value, $string)=&str2arrayref($string);
                   2506:           if($value->[0] eq 'Array reference error') {
                   2507:               $hash{'error'}='Bad data';
                   2508:               return (\%hash, $string);
                   2509:           }
                   2510:       } else {
                   2511: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2512:       }
                   2513:       $string =~ s/^&//;
                   2514: 
                   2515:       $hash{$key}=$value;
1.204     albertel 2516:   }
1.265     albertel 2517: 
                   2518:   $string =~ s/^__END_HASH_REF__//;
                   2519: 
                   2520:   return (\%hash, $string);
1.204     albertel 2521: }
                   2522: 
                   2523: sub str2array {
1.265     albertel 2524:     my ($string)=@_;
                   2525:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2526:     return @$array;
                   2527: }
                   2528: 
                   2529: sub str2arrayref {
1.204     albertel 2530:   my ($string) = @_;
1.265     albertel 2531:   my @array;
                   2532: 
                   2533:   if($string !~ /^__ARRAY_REF__/) {
                   2534:       if (! ($string eq '' || !defined($string))) {
                   2535: 	  $array[0]='Array reference error';
                   2536:       }
                   2537:       return (\@array, $string);
                   2538:   }
                   2539: 
                   2540:   $string =~ s/^__ARRAY_REF__//;
                   2541: 
                   2542:   while($string !~ /^__END_ARRAY_REF__/) {
                   2543:       my $value='';
                   2544:       if($string =~ /^__HASH_REF__/) {
                   2545:           ($value, $string)=&str2hashref($string);
                   2546:           if(defined($value->{'error'})) {
                   2547:               $array[0] ='Array reference error';
                   2548:               return (\@array, $string);
                   2549:           }
                   2550:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2551:           ($value, $string)=&str2arrayref($string);
                   2552:           if($value->[0] eq 'Array reference error') {
                   2553:               $array[0] ='Array reference error';
                   2554:               return (\@array, $string);
                   2555:           }
                   2556:       } else {
                   2557: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2558:       }
                   2559:       $string =~ s/^&//;
                   2560: 
                   2561:       push(@array, $value);
1.191     harris41 2562:   }
1.265     albertel 2563: 
                   2564:   $string =~ s/^__END_ARRAY_REF__//;
                   2565: 
                   2566:   return (\@array, $string);
1.168     albertel 2567: }
                   2568: 
1.167     albertel 2569: # -------------------------------------------------------------------Temp Store
                   2570: 
1.168     albertel 2571: sub tmpreset {
                   2572:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2573:   if (!$symb) {
                   2574:     $symb=&symbread();
1.620     albertel 2575:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2576:   }
                   2577:   $symb=escape($symb);
                   2578: 
1.620     albertel 2579:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2580:   $namespace=~s/\//\_/g;
                   2581:   $namespace=~s/\W//g;
                   2582: 
1.620     albertel 2583:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2584:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2585:   if ($domain eq 'public' && $stuname eq 'public') {
                   2586:       $stuname=$ENV{'REMOTE_ADDR'};
                   2587:   }
1.168     albertel 2588:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2589:   my %hash;
                   2590:   if (tie(%hash,'GDBM_File',
                   2591: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2592: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2593:     foreach my $key (keys %hash) {
1.180     albertel 2594:       if ($key=~ /:$symb/) {
1.168     albertel 2595: 	delete($hash{$key});
                   2596:       }
                   2597:     }
                   2598:   }
                   2599: }
                   2600: 
1.167     albertel 2601: sub tmpstore {
1.168     albertel 2602:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2603: 
                   2604:   if (!$symb) {
                   2605:     $symb=&symbread();
1.620     albertel 2606:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2607:   }
                   2608:   $symb=escape($symb);
                   2609: 
                   2610:   if (!$namespace) {
                   2611:     # I don't think we would ever want to store this for a course.
                   2612:     # it seems this will only be used if we don't have a course.
1.620     albertel 2613:     #$namespace=$env{'request.course.id'};
1.168     albertel 2614:     #if (!$namespace) {
1.620     albertel 2615:       $namespace=$env{'request.state'};
1.168     albertel 2616:     #}
                   2617:   }
                   2618:   $namespace=~s/\//\_/g;
                   2619:   $namespace=~s/\W//g;
1.620     albertel 2620:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2621:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2622:   if ($domain eq 'public' && $stuname eq 'public') {
                   2623:       $stuname=$ENV{'REMOTE_ADDR'};
                   2624:   }
1.168     albertel 2625:   my $now=time;
                   2626:   my %hash;
                   2627:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2628:   if (tie(%hash,'GDBM_File',
                   2629: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2630: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2631:     $hash{"version:$symb"}++;
                   2632:     my $version=$hash{"version:$symb"};
                   2633:     my $allkeys=''; 
                   2634:     foreach my $key (keys(%$storehash)) {
                   2635:       $allkeys.=$key.':';
1.591     albertel 2636:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2637:     }
                   2638:     $hash{"$version:$symb:timestamp"}=$now;
                   2639:     $allkeys.='timestamp';
                   2640:     $hash{"$version:keys:$symb"}=$allkeys;
                   2641:     if (untie(%hash)) {
                   2642:       return 'ok';
                   2643:     } else {
                   2644:       return "error:$!";
                   2645:     }
                   2646:   } else {
                   2647:     return "error:$!";
                   2648:   }
                   2649: }
1.167     albertel 2650: 
1.168     albertel 2651: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2652: 
1.168     albertel 2653: sub tmprestore {
                   2654:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2655: 
1.168     albertel 2656:   if (!$symb) {
                   2657:     $symb=&symbread();
1.620     albertel 2658:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2659:   }
                   2660:   $symb=escape($symb);
                   2661: 
1.620     albertel 2662:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2663: 
1.620     albertel 2664:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2665:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2666:   if ($domain eq 'public' && $stuname eq 'public') {
                   2667:       $stuname=$ENV{'REMOTE_ADDR'};
                   2668:   }
1.168     albertel 2669:   my %returnhash;
                   2670:   $namespace=~s/\//\_/g;
                   2671:   $namespace=~s/\W//g;
                   2672:   my %hash;
                   2673:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2674:   if (tie(%hash,'GDBM_File',
                   2675: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2676: 	  &GDBM_READER(),0640)) {
1.168     albertel 2677:     my $version=$hash{"version:$symb"};
                   2678:     $returnhash{'version'}=$version;
                   2679:     my $scope;
                   2680:     for ($scope=1;$scope<=$version;$scope++) {
                   2681:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2682:       my @keys=split(/:/,$vkeys);
                   2683:       my $key;
                   2684:       $returnhash{"$scope:keys"}=$vkeys;
                   2685:       foreach $key (@keys) {
1.591     albertel 2686: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2687: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2688:       }
                   2689:     }
1.168     albertel 2690:     if (!(untie(%hash))) {
                   2691:       return "error:$!";
                   2692:     }
                   2693:   } else {
                   2694:     return "error:$!";
                   2695:   }
                   2696:   return %returnhash;
1.167     albertel 2697: }
                   2698: 
1.9       www      2699: # ----------------------------------------------------------------------- Store
                   2700: 
                   2701: sub store {
1.124     www      2702:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2703:     my $home='';
                   2704: 
1.168     albertel 2705:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2706: 
1.213     www      2707:     $symb=&symbclean($symb);
1.122     albertel 2708:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2709: 
1.620     albertel 2710:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2711:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2712: 
                   2713:     &devalidate($symb,$stuname,$domain);
1.109     www      2714: 
                   2715:     $symb=escape($symb);
1.187     www      2716:     if (!$namespace) { 
1.620     albertel 2717:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2718:           return ''; 
                   2719:        } 
                   2720:     }
1.620     albertel 2721:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2722: 
                   2723:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2724:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2725: 
1.12      www      2726:     my $namevalue='';
1.800     albertel 2727:     foreach my $key (keys(%$storehash)) {
                   2728:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2729:     }
1.12      www      2730:     $namevalue=~s/\&$//;
1.187     www      2731:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2732:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2733: }
                   2734: 
1.47      www      2735: # -------------------------------------------------------------- Critical Store
                   2736: 
                   2737: sub cstore {
1.124     www      2738:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2739:     my $home='';
                   2740: 
1.168     albertel 2741:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2742: 
1.213     www      2743:     $symb=&symbclean($symb);
1.122     albertel 2744:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2745: 
1.620     albertel 2746:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2747:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2748: 
                   2749:     &devalidate($symb,$stuname,$domain);
1.109     www      2750: 
                   2751:     $symb=escape($symb);
1.187     www      2752:     if (!$namespace) { 
1.620     albertel 2753:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2754:           return ''; 
                   2755:        } 
                   2756:     }
1.620     albertel 2757:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2758: 
                   2759:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2760:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2761: 
1.47      www      2762:     my $namevalue='';
1.800     albertel 2763:     foreach my $key (keys(%$storehash)) {
                   2764:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2765:     }
1.47      www      2766:     $namevalue=~s/\&$//;
1.187     www      2767:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2768:     return critical
                   2769:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2770: }
                   2771: 
1.9       www      2772: # --------------------------------------------------------------------- Restore
                   2773: 
                   2774: sub restore {
1.124     www      2775:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2776:     my $home='';
                   2777: 
1.168     albertel 2778:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2779: 
1.122     albertel 2780:     if (!$symb) {
                   2781:       unless ($symb=escape(&symbread())) { return ''; }
                   2782:     } else {
1.213     www      2783:       $symb=&escape(&symbclean($symb));
1.122     albertel 2784:     }
1.188     www      2785:     if (!$namespace) { 
1.620     albertel 2786:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2787:           return ''; 
                   2788:        } 
                   2789:     }
1.620     albertel 2790:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2791:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2792:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2793:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2794: 
1.12      www      2795:     my %returnhash=();
1.800     albertel 2796:     foreach my $line (split(/\&/,$answer)) {
                   2797: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2798:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2799:     }
1.75      www      2800:     my $version;
                   2801:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2802:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2803:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2804:        }
1.75      www      2805:     }
1.13      www      2806:     return %returnhash;
1.34      www      2807: }
                   2808: 
                   2809: # ---------------------------------------------------------- Course Description
                   2810: 
                   2811: sub coursedescription {
1.731     albertel 2812:     my ($courseid,$args)=@_;
1.34      www      2813:     $courseid=~s/^\///;
1.49      www      2814:     $courseid=~s/\_/\//g;
1.34      www      2815:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2816:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2817:     my $normalid=$cdomain.'_'.$cnum;
                   2818:     # need to always cache even if we get errors otherwise we keep 
                   2819:     # trying and trying and trying to get the course description.
                   2820:     my %envhash=();
                   2821:     my %returnhash=();
1.731     albertel 2822:     
                   2823:     my $expiretime=600;
                   2824:     if ($env{'request.course.id'} eq $normalid) {
                   2825: 	$expiretime=120;
                   2826:     }
                   2827: 
                   2828:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2829:     if (!$args->{'freshen_cache'}
                   2830: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2831: 	foreach my $key (keys(%env)) {
                   2832: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2833: 	    my ($setting) = $1;
                   2834: 	    $returnhash{$setting} = $env{$key};
                   2835: 	}
                   2836: 	return %returnhash;
                   2837:     }
                   2838: 
                   2839:     # get the data agin
                   2840:     if (!$args->{'one_time'}) {
                   2841: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2842:     }
1.811     albertel 2843: 
1.34      www      2844:     if ($chome ne 'no_host') {
1.302     albertel 2845:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2846:        if (!exists($returnhash{'con_lost'})) {
                   2847:            $returnhash{'home'}= $chome;
                   2848: 	   $returnhash{'domain'} = $cdomain;
                   2849: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2850:            if (!defined($returnhash{'type'})) {
                   2851:                $returnhash{'type'} = 'Course';
                   2852:            }
1.130     albertel 2853:            while (my ($name,$value) = each %returnhash) {
1.53      www      2854:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2855:            }
1.270     www      2856:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2857:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2858: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2859:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2860:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2861:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2862:        }
                   2863:     }
1.731     albertel 2864:     if (!$args->{'one_time'}) {
                   2865: 	&appenv(%envhash);
                   2866:     }
1.302     albertel 2867:     return %returnhash;
1.461     www      2868: }
                   2869: 
                   2870: # -------------------------------------------------See if a user is privileged
                   2871: 
                   2872: sub privileged {
                   2873:     my ($username,$domain)=@_;
                   2874:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2875: 			&homeserver($username,$domain));
                   2876:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2877:     my $now=time;
                   2878:     if ($rolesdump ne '') {
1.800     albertel 2879:         foreach my $entry (split(/&/,$rolesdump)) {
                   2880: 	    if ($entry!~/^rolesdef_/) {
                   2881: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2882: 		$area=~s/\_\w\w$//;
                   2883: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2884: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2885: 		    my $active=1;
                   2886: 		    if ($tend) {
                   2887: 			if ($tend<$now) { $active=0; }
                   2888: 		    }
                   2889: 		    if ($tstart) {
                   2890: 			if ($tstart>$now) { $active=0; }
                   2891: 		    }
                   2892: 		    if ($active) { return 1; }
                   2893: 		}
                   2894: 	    }
                   2895: 	}
                   2896:     }
                   2897:     return 0;
1.9       www      2898: }
1.1       albertel 2899: 
1.103     harris41 2900: # -------------------------------------------------------- Get user privileges
1.11      www      2901: 
                   2902: sub rolesinit {
                   2903:     my ($domain,$username,$authhost)=@_;
                   2904:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2905:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2906:     my %allroles=();
1.678     raeburn  2907:     my %allgroups=();   
1.11      www      2908:     my $now=time;
1.743     albertel 2909:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2910:     my $group_privs;
1.11      www      2911: 
                   2912:     if ($rolesdump ne '') {
1.800     albertel 2913:         foreach my $entry (split(/&/,$rolesdump)) {
                   2914: 	  if ($entry!~/^rolesdef_/) {
                   2915:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2916: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2917:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2918: 	    if ($role=~/^cr/) { 
1.807     albertel 2919: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2920: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2921: 		    ($tend,$tstart)=split('_',$trest);
                   2922: 		} else {
                   2923: 		    $trole=$role;
                   2924: 		}
1.678     raeburn  2925:             } elsif ($role =~ m|^gr/|) {
                   2926:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2927:                 ($trole,$group_privs) = split(/\//,$trole);
                   2928:                 $group_privs = &unescape($group_privs);
1.587     albertel 2929: 	    } else {
                   2930: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2931: 	    }
1.743     albertel 2932: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2933: 					 $username);
                   2934: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2935:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2936:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2937:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2938: 		my $spec=$trole.'.'.$area;
                   2939: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2940: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2941:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2942:                 } elsif ($trole eq 'gr') {
                   2943:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2944: 		} else {
1.567     raeburn  2945:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2946: 		}
1.12      www      2947:             }
1.662     raeburn  2948:           }
1.191     harris41 2949:         }
1.743     albertel 2950:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2951:         $userroles{'user.adv'}    = $adv;
                   2952: 	$userroles{'user.author'} = $author;
1.620     albertel 2953:         $env{'user.adv'}=$adv;
1.11      www      2954:     }
1.743     albertel 2955:     return \%userroles;  
1.11      www      2956: }
                   2957: 
1.567     raeburn  2958: sub set_arearole {
                   2959:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2960: # log the associated role with the area
                   2961:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2962:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2963: }
                   2964: 
                   2965: sub custom_roleprivs {
                   2966:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2967:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2968:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 2969:     if (&hostname($homsvr) ne '') {
1.567     raeburn  2970:         my ($rdummy,$roledef)=
                   2971:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2972:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2973:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2974:             if (defined($syspriv)) {
                   2975:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2976:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2977:             }
                   2978:             if ($tdomain ne '') {
                   2979:                 if (defined($dompriv)) {
                   2980:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2981:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2982:                 }
                   2983:                 if (($trest ne '') && (defined($coursepriv))) {
                   2984:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2985:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2986:                 }
                   2987:             }
                   2988:         }
                   2989:     }
                   2990: }
                   2991: 
1.678     raeburn  2992: sub group_roleprivs {
                   2993:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2994:     my $access = 1;
                   2995:     my $now = time;
                   2996:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2997:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2998:     if ($access) {
1.811     albertel 2999:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3000:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3001:     }
                   3002: }
1.567     raeburn  3003: 
                   3004: sub standard_roleprivs {
                   3005:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3006:     if (defined($pr{$trole.':s'})) {
                   3007:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3008:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3009:     }
                   3010:     if ($tdomain ne '') {
                   3011:         if (defined($pr{$trole.':d'})) {
                   3012:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3013:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3014:         }
                   3015:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3016:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3017:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3018:         }
                   3019:     }
                   3020: }
                   3021: 
                   3022: sub set_userprivs {
1.678     raeburn  3023:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3024:     my $author=0;
                   3025:     my $adv=0;
1.678     raeburn  3026:     my %grouproles = ();
                   3027:     if (keys(%{$allgroups}) > 0) {
                   3028:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3029:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3030:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3031:                 $trole = $1;
                   3032:                 $area = $2;
1.681     raeburn  3033:                 $sec = $3;
                   3034:                 $extendedarea = $area.$sec;
                   3035:                 if (exists($$allgroups{$area})) {
                   3036:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3037:                         my $spec = $trole.'.'.$extendedarea;
                   3038:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3039:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3040:                     }
                   3041:                 }
                   3042:             }
                   3043:         }
                   3044:     }
1.800     albertel 3045:     foreach my $group (keys(%grouproles)) {
                   3046:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3047:     }
1.800     albertel 3048:     foreach my $role (keys(%{$allroles})) {
                   3049:         my %thesepriv;
                   3050:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3051:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3052:             if ($item ne '') {
                   3053:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3054:                 if ($restrictions eq '') {
                   3055:                     $thesepriv{$privilege}='F';
                   3056:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3057:                     $thesepriv{$privilege}.=$restrictions;
                   3058:                 }
                   3059:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3060:             }
                   3061:         }
                   3062:         my $thesestr='';
1.800     albertel 3063:         foreach my $priv (keys(%thesepriv)) {
                   3064: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3065: 	}
                   3066:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3067:     }
                   3068:     return ($author,$adv);
                   3069: }
                   3070: 
1.12      www      3071: # --------------------------------------------------------------- get interface
                   3072: 
                   3073: sub get {
1.131     albertel 3074:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3075:    my $items='';
1.800     albertel 3076:    foreach my $item (@$storearr) {
                   3077:        $items.=&escape($item).'&';
1.191     harris41 3078:    }
1.12      www      3079:    $items=~s/\&$//;
1.620     albertel 3080:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3081:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3082:    my $uhome=&homeserver($uname,$udomain);
                   3083: 
1.133     albertel 3084:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3085:    my @pairs=split(/\&/,$rep);
1.273     albertel 3086:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3087:      return @pairs;
                   3088:    }
1.15      www      3089:    my %returnhash=();
1.42      www      3090:    my $i=0;
1.800     albertel 3091:    foreach my $item (@$storearr) {
                   3092:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3093:       $i++;
1.191     harris41 3094:    }
1.15      www      3095:    return %returnhash;
1.27      www      3096: }
                   3097: 
                   3098: # --------------------------------------------------------------- del interface
                   3099: 
                   3100: sub del {
1.133     albertel 3101:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3102:    my $items='';
1.800     albertel 3103:    foreach my $item (@$storearr) {
                   3104:        $items.=&escape($item).'&';
1.191     harris41 3105:    }
1.27      www      3106:    $items=~s/\&$//;
1.620     albertel 3107:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3108:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3109:    my $uhome=&homeserver($uname,$udomain);
                   3110: 
                   3111:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3112: }
                   3113: 
                   3114: # -------------------------------------------------------------- dump interface
                   3115: 
                   3116: sub dump {
1.755     albertel 3117:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3118:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3119:     if (!$uname) { $uname=$env{'user.name'}; }
                   3120:     my $uhome=&homeserver($uname,$udomain);
                   3121:     if ($regexp) {
                   3122: 	$regexp=&escape($regexp);
                   3123:     } else {
                   3124: 	$regexp='.';
                   3125:     }
                   3126:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3127:     my @pairs=split(/\&/,$rep);
                   3128:     my %returnhash=();
                   3129:     foreach my $item (@pairs) {
                   3130: 	my ($key,$value)=split(/=/,$item,2);
                   3131: 	$key = &unescape($key);
                   3132: 	next if ($key =~ /^error: 2 /);
                   3133: 	$returnhash{$key}=&thaw_unescape($value);
                   3134:     }
                   3135:     return %returnhash;
1.407     www      3136: }
                   3137: 
1.717     albertel 3138: # --------------------------------------------------------- dumpstore interface
                   3139: 
                   3140: sub dumpstore {
                   3141:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3142:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3143:    if (!$uname) { $uname=$env{'user.name'}; }
                   3144:    my $uhome=&homeserver($uname,$udomain);
                   3145:    if ($regexp) {
                   3146:        $regexp=&escape($regexp);
                   3147:    } else {
                   3148:        $regexp='.';
                   3149:    }
                   3150:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3151:    my @pairs=split(/\&/,$rep);
                   3152:    my %returnhash=();
                   3153:    foreach my $item (@pairs) {
                   3154:        my ($key,$value)=split(/=/,$item,2);
                   3155:        next if ($key =~ /^error: 2 /);
                   3156:        $returnhash{$key}=&thaw_unescape($value);
                   3157:    }
                   3158:    return %returnhash;
1.717     albertel 3159: }
                   3160: 
1.407     www      3161: # -------------------------------------------------------------- keys interface
                   3162: 
                   3163: sub getkeys {
                   3164:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3165:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3166:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3167:    my $uhome=&homeserver($uname,$udomain);
                   3168:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3169:    my @keyarray=();
1.800     albertel 3170:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3171:       next if ($key =~ /^error: 2 /);
1.800     albertel 3172:       push(@keyarray,&unescape($key));
1.407     www      3173:    }
                   3174:    return @keyarray;
1.318     matthew  3175: }
                   3176: 
1.319     matthew  3177: # --------------------------------------------------------------- currentdump
                   3178: sub currentdump {
1.328     matthew  3179:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3180:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3181:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3182:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3183:    my $uhome = &homeserver($sname,$sdom);
                   3184:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3185:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3186:    #
1.318     matthew  3187:    my %returnhash=();
1.319     matthew  3188:    #
                   3189:    if ($rep eq "unknown_cmd") { 
                   3190:        # an old lond will not know currentdump
                   3191:        # Do a dump and make it look like a currentdump
1.822     albertel 3192:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3193:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3194:        my %hash = @tmp;
                   3195:        @tmp=();
1.424     matthew  3196:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3197:    } else {
                   3198:        my @pairs=split(/\&/,$rep);
1.800     albertel 3199:        foreach my $pair (@pairs) {
                   3200:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3201:            my ($symb,$param) = split(/:/,$key);
                   3202:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3203:                                                         &thaw_unescape($value);
1.319     matthew  3204:        }
1.191     harris41 3205:    }
1.12      www      3206:    return %returnhash;
1.424     matthew  3207: }
                   3208: 
                   3209: sub convert_dump_to_currentdump{
                   3210:     my %hash = %{shift()};
                   3211:     my %returnhash;
                   3212:     # Code ripped from lond, essentially.  The only difference
                   3213:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3214:     # we might run in to problems with parameter names =~ /^v\./
                   3215:     while (my ($key,$value) = each(%hash)) {
                   3216:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3217: 	$symb  = &unescape($symb);
                   3218: 	$param = &unescape($param);
1.424     matthew  3219:         next if ($v eq 'version' || $symb eq 'keys');
                   3220:         next if (exists($returnhash{$symb}) &&
                   3221:                  exists($returnhash{$symb}->{$param}) &&
                   3222:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3223:         $returnhash{$symb}->{$param}=$value;
                   3224:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3225:     }
                   3226:     #
                   3227:     # Remove all of the keys in the hashes which keep track of
                   3228:     # the version of the parameter.
                   3229:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3230:         # use a foreach because we are going to delete from the hash.
                   3231:         foreach my $key (keys(%$param_hash)) {
                   3232:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3233:         }
                   3234:     }
                   3235:     return \%returnhash;
1.12      www      3236: }
                   3237: 
1.627     albertel 3238: # ------------------------------------------------------ critical inc interface
                   3239: 
                   3240: sub cinc {
                   3241:     return &inc(@_,'critical');
                   3242: }
                   3243: 
1.449     matthew  3244: # --------------------------------------------------------------- inc interface
                   3245: 
                   3246: sub inc {
1.627     albertel 3247:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3248:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3249:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3250:     my $uhome=&homeserver($uname,$udomain);
                   3251:     my $items='';
                   3252:     if (! ref($store)) {
                   3253:         # got a single value, so use that instead
                   3254:         $items = &escape($store).'=&';
                   3255:     } elsif (ref($store) eq 'SCALAR') {
                   3256:         $items = &escape($$store).'=&';        
                   3257:     } elsif (ref($store) eq 'ARRAY') {
                   3258:         $items = join('=&',map {&escape($_);} @{$store});
                   3259:     } elsif (ref($store) eq 'HASH') {
                   3260:         while (my($key,$value) = each(%{$store})) {
                   3261:             $items.= &escape($key).'='.&escape($value).'&';
                   3262:         }
                   3263:     }
                   3264:     $items=~s/\&$//;
1.627     albertel 3265:     if ($critical) {
                   3266: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3267:     } else {
                   3268: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3269:     }
1.449     matthew  3270: }
                   3271: 
1.12      www      3272: # --------------------------------------------------------------- put interface
                   3273: 
                   3274: sub put {
1.134     albertel 3275:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3276:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3277:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3278:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3279:    my $items='';
1.800     albertel 3280:    foreach my $item (keys(%$storehash)) {
                   3281:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3282:    }
1.12      www      3283:    $items=~s/\&$//;
1.134     albertel 3284:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3285: }
                   3286: 
1.631     albertel 3287: # ------------------------------------------------------------ newput interface
                   3288: 
                   3289: sub newput {
                   3290:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3291:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3292:    if (!$uname) { $uname=$env{'user.name'}; }
                   3293:    my $uhome=&homeserver($uname,$udomain);
                   3294:    my $items='';
                   3295:    foreach my $key (keys(%$storehash)) {
                   3296:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3297:    }
                   3298:    $items=~s/\&$//;
                   3299:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3300: }
                   3301: 
                   3302: # ---------------------------------------------------------  putstore interface
                   3303: 
1.524     raeburn  3304: sub putstore {
1.715     albertel 3305:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3306:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3307:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3308:    my $uhome=&homeserver($uname,$udomain);
                   3309:    my $items='';
1.715     albertel 3310:    foreach my $key (keys(%$storehash)) {
                   3311:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3312:    }
1.715     albertel 3313:    $items=~s/\&$//;
1.716     albertel 3314:    my $esc_symb=&escape($symb);
                   3315:    my $esc_v=&escape($version);
1.715     albertel 3316:    my $reply =
1.716     albertel 3317:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3318: 	      $uhome);
                   3319:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3320:        # gfall back to way things use to be done
1.715     albertel 3321:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3322: 			    $uname);
1.524     raeburn  3323:    }
1.715     albertel 3324:    return $reply;
                   3325: }
                   3326: 
                   3327: sub old_putstore {
1.716     albertel 3328:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3329:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3330:     if (!$uname) { $uname=$env{'user.name'}; }
                   3331:     my $uhome=&homeserver($uname,$udomain);
                   3332:     my %newstorehash;
1.800     albertel 3333:     foreach my $item (keys(%$storehash)) {
                   3334: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3335: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3336:     }
                   3337:     my $items='';
                   3338:     my %allitems = ();
1.800     albertel 3339:     foreach my $item (keys(%newstorehash)) {
                   3340: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3341: 	    my $key = $1.':keys:'.$2;
                   3342: 	    $allitems{$key} .= $3.':';
                   3343: 	}
1.800     albertel 3344: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3345:     }
1.800     albertel 3346:     foreach my $item (keys(%allitems)) {
                   3347: 	$allitems{$item} =~ s/\:$//;
                   3348: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3349:     }
                   3350:     $items=~s/\&$//;
                   3351:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3352: }
                   3353: 
1.47      www      3354: # ------------------------------------------------------ critical put interface
                   3355: 
                   3356: sub cput {
1.134     albertel 3357:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3358:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3359:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3360:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3361:    my $items='';
1.800     albertel 3362:    foreach my $item (keys(%$storehash)) {
                   3363:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3364:    }
1.47      www      3365:    $items=~s/\&$//;
1.134     albertel 3366:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3367: }
                   3368: 
                   3369: # -------------------------------------------------------------- eget interface
                   3370: 
                   3371: sub eget {
1.133     albertel 3372:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3373:    my $items='';
1.800     albertel 3374:    foreach my $item (@$storearr) {
                   3375:        $items.=&escape($item).'&';
1.191     harris41 3376:    }
1.12      www      3377:    $items=~s/\&$//;
1.620     albertel 3378:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3379:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3380:    my $uhome=&homeserver($uname,$udomain);
                   3381:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3382:    my @pairs=split(/\&/,$rep);
                   3383:    my %returnhash=();
1.42      www      3384:    my $i=0;
1.800     albertel 3385:    foreach my $item (@$storearr) {
                   3386:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3387:       $i++;
1.191     harris41 3388:    }
1.12      www      3389:    return %returnhash;
                   3390: }
                   3391: 
1.667     albertel 3392: # ------------------------------------------------------------ tmpput interface
                   3393: sub tmpput {
1.802     raeburn  3394:     my ($storehash,$server,$context)=@_;
1.667     albertel 3395:     my $items='';
1.800     albertel 3396:     foreach my $item (keys(%$storehash)) {
                   3397: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3398:     }
                   3399:     $items=~s/\&$//;
1.802     raeburn  3400:     if (defined($context)) {
                   3401:         $items .= ':'.&escape($context);
                   3402:     }
1.667     albertel 3403:     return &reply("tmpput:$items",$server);
                   3404: }
                   3405: 
                   3406: # ------------------------------------------------------------ tmpget interface
                   3407: sub tmpget {
1.688     albertel 3408:     my ($token,$server)=@_;
                   3409:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3410:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3411:     my %returnhash;
                   3412:     foreach my $item (split(/\&/,$rep)) {
                   3413: 	my ($key,$value)=split(/=/,$item);
                   3414: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3415:     }
                   3416:     return %returnhash;
                   3417: }
                   3418: 
1.688     albertel 3419: # ------------------------------------------------------------ tmpget interface
                   3420: sub tmpdel {
                   3421:     my ($token,$server)=@_;
                   3422:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3423:     return &reply("tmpdel:$token",$server);
                   3424: }
                   3425: 
1.765     albertel 3426: # -------------------------------------------------- portfolio access checking
                   3427: 
                   3428: sub portfolio_access {
1.766     albertel 3429:     my ($requrl) = @_;
1.765     albertel 3430:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3431:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3432:     if ($result) {
                   3433:         my %setters;
                   3434:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3435:             my ($startblock,$endblock) =
                   3436:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3437:             if ($startblock && $endblock) {
                   3438:                 return 'B';
                   3439:             }
                   3440:         } else {
                   3441:             my ($startblock,$endblock) =
                   3442:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3443:             if ($startblock && $endblock) {
                   3444:                 return 'B';
                   3445:             }
                   3446:         }
                   3447:     }
1.765     albertel 3448:     if ($result eq 'ok') {
1.766     albertel 3449:        return 'F';
1.765     albertel 3450:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3451:        return 'A';
1.765     albertel 3452:     }
1.766     albertel 3453:     return '';
1.765     albertel 3454: }
                   3455: 
                   3456: sub get_portfolio_access {
1.767     albertel 3457:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3458: 
                   3459:     if (!ref($access_hash)) {
                   3460: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3461: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3462: 						   $file_name);
                   3463: 	$access_hash = $access_controls{$file_name};
                   3464:     }
                   3465: 
1.765     albertel 3466:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3467:     my $now = time;
                   3468:     if (ref($access_hash) eq 'HASH') {
                   3469:         foreach my $key (keys(%{$access_hash})) {
                   3470:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3471:             if ($start > $now) {
                   3472:                 next;
                   3473:             }
                   3474:             if ($end && $end<$now) {
                   3475:                 next;
                   3476:             }
                   3477:             if ($scope eq 'public') {
                   3478:                 $public = $key;
                   3479:                 last;
                   3480:             } elsif ($scope eq 'guest') {
                   3481:                 $guest = $key;
                   3482:             } elsif ($scope eq 'domains') {
                   3483:                 push(@domains,$key);
                   3484:             } elsif ($scope eq 'users') {
                   3485:                 push(@users,$key);
                   3486:             } elsif ($scope eq 'course') {
                   3487:                 push(@courses,$key);
                   3488:             } elsif ($scope eq 'group') {
                   3489:                 push(@groups,$key);
                   3490:             }
                   3491:         }
                   3492:         if ($public) {
                   3493:             return 'ok';
                   3494:         }
                   3495:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3496:             if ($guest) {
                   3497:                 return $guest;
                   3498:             }
                   3499:         } else {
                   3500:             if (@domains > 0) {
                   3501:                 foreach my $domkey (@domains) {
                   3502:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3503:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3504:                             return 'ok';
                   3505:                         }
                   3506:                     }
                   3507:                 }
                   3508:             }
                   3509:             if (@users > 0) {
                   3510:                 foreach my $userkey (@users) {
                   3511:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3512:                         return 'ok';
                   3513:                     }
                   3514:                 }
                   3515:             }
                   3516:             my %roleshash;
                   3517:             my @courses_and_groups = @courses;
                   3518:             push(@courses_and_groups,@groups); 
                   3519:             if (@courses_and_groups > 0) {
                   3520:                 my (%allgroups,%allroles); 
                   3521:                 my ($start,$end,$role,$sec,$group);
                   3522:                 foreach my $envkey (%env) {
1.811     albertel 3523:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3524:                         my $cid = $2.'_'.$3; 
                   3525:                         if ($1 eq 'gr') {
                   3526:                             $group = $4;
                   3527:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3528:                         } else {
                   3529:                             if ($4 eq '') {
                   3530:                                 $sec = 'none';
                   3531:                             } else {
                   3532:                                 $sec = $4;
                   3533:                             }
                   3534:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3535:                         }
1.811     albertel 3536:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3537:                         my $cid = $2.'_'.$3;
                   3538:                         if ($4 eq '') {
                   3539:                             $sec = 'none';
                   3540:                         } else {
                   3541:                             $sec = $4;
                   3542:                         }
                   3543:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3544:                     }
                   3545:                 }
                   3546:                 if (keys(%allroles) == 0) {
                   3547:                     return;
                   3548:                 }
                   3549:                 foreach my $key (@courses_and_groups) {
                   3550:                     my %content = %{$$access_hash{$key}};
                   3551:                     my $cnum = $content{'number'};
                   3552:                     my $cdom = $content{'domain'};
                   3553:                     my $cid = $cdom.'_'.$cnum;
                   3554:                     if (!exists($allroles{$cid})) {
                   3555:                         next;
                   3556:                     }    
                   3557:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3558:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3559:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3560:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3561:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3562:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3563:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3564:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3565:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3566:                                         if (grep/^all$/,@sections) {
                   3567:                                             return 'ok';
                   3568:                                         } else {
                   3569:                                             if (grep/^$sec$/,@sections) {
                   3570:                                                 return 'ok';
                   3571:                                             }
                   3572:                                         }
                   3573:                                     }
                   3574:                                 }
                   3575:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3576:                                     if (grep/^none$/,@groups) {
                   3577:                                         return 'ok';
                   3578:                                     }
                   3579:                                 } else {
                   3580:                                     if (grep/^all$/,@groups) {
                   3581:                                         return 'ok';
                   3582:                                     } 
                   3583:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3584:                                         if (grep/^$group$/,@groups) {
                   3585:                                             return 'ok';
                   3586:                                         }
                   3587:                                     }
                   3588:                                 } 
                   3589:                             }
                   3590:                         }
                   3591:                     }
                   3592:                 }
                   3593:             }
                   3594:             if ($guest) {
                   3595:                 return $guest;
                   3596:             }
                   3597:         }
                   3598:     }
                   3599:     return;
                   3600: }
                   3601: 
                   3602: sub course_group_datechecker {
                   3603:     my ($dates,$now,$status) = @_;
                   3604:     my ($start,$end) = split(/\./,$dates);
                   3605:     if (!$start && !$end) {
                   3606:         return 'ok';
                   3607:     }
                   3608:     if (grep/^active$/,@{$status}) {
                   3609:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3610:             return 'ok';
                   3611:         }
                   3612:     }
                   3613:     if (grep/^previous$/,@{$status}) {
                   3614:         if ($end > $now ) {
                   3615:             return 'ok';
                   3616:         }
                   3617:     }
                   3618:     if (grep/^future$/,@{$status}) {
                   3619:         if ($start > $now) {
                   3620:             return 'ok';
                   3621:         }
                   3622:     }
                   3623:     return; 
                   3624: }
                   3625: 
                   3626: sub parse_portfolio_url {
                   3627:     my ($url) = @_;
                   3628: 
                   3629:     my ($type,$udom,$unum,$group,$file_name);
                   3630:     
1.823     albertel 3631:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3632: 	$type = 1;
                   3633:         $udom = $1;
                   3634:         $unum = $2;
                   3635:         $file_name = $3;
1.823     albertel 3636:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3637: 	$type = 2;
                   3638:         $udom = $1;
                   3639:         $unum = $2;
                   3640:         $group = $3;
                   3641:         $file_name = $3.'/'.$4;
                   3642:     }
                   3643:     if (wantarray) {
                   3644: 	return ($type,$udom,$unum,$file_name,$group);
                   3645:     }
                   3646:     return $type;
                   3647: }
                   3648: 
                   3649: sub is_portfolio_url {
                   3650:     my ($url) = @_;
                   3651:     return scalar(&parse_portfolio_url($url));
                   3652: }
                   3653: 
1.798     raeburn  3654: sub is_portfolio_file {
                   3655:     my ($file) = @_;
1.820     raeburn  3656:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3657:         return 1;
                   3658:     }
                   3659:     return;
                   3660: }
                   3661: 
                   3662: 
1.341     www      3663: # ---------------------------------------------- Custom access rule evaluation
                   3664: 
                   3665: sub customaccess {
                   3666:     my ($priv,$uri)=@_;
1.807     albertel 3667:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3668:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3669:     $udom = &LONCAPA::clean_domain($udom);
                   3670:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3671:     my $access=0;
1.800     albertel 3672:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3673: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3674:         if ($role) {
                   3675: 	   if ($role ne $urole) { next; }
                   3676:         }
1.800     albertel 3677:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3678:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3679:             if ($tdom) {
                   3680: 		if ($tdom ne $udom) { next; }
                   3681:             }
                   3682:             if ($tcrs) {
                   3683: 		if ($tcrs ne $ucrs) { next; }
                   3684:             }
                   3685:             if ($tsec) {
                   3686: 		if ($tsec ne $usec) { next; }
                   3687:             }
                   3688:             $access=($effect eq 'allow');
                   3689:             last;
1.342     www      3690:         }
1.402     bowersj2 3691: 	if ($realm eq '' && $role eq '') {
                   3692:             $access=($effect eq 'allow');
                   3693: 	}
1.341     www      3694:     }
                   3695:     return $access;
                   3696: }
                   3697: 
1.103     harris41 3698: # ------------------------------------------------- Check for a user privilege
1.12      www      3699: 
                   3700: sub allowed {
1.810     raeburn  3701:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3702:     my $ver_orguri=$uri;
1.439     www      3703:     $uri=&deversion($uri);
1.152     www      3704:     my $orguri=$uri;
1.52      www      3705:     $uri=&declutter($uri);
1.809     raeburn  3706: 
1.810     raeburn  3707:     if ($priv eq 'evb') {
                   3708: # Evade communication block restrictions for specified role in a course
                   3709:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3710:             return $1;
                   3711:         } else {
                   3712:             return;
                   3713:         }
                   3714:     }
                   3715: 
1.620     albertel 3716:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3717: # Free bre access to adm and meta resources
1.775     albertel 3718:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3719: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3720: 	&& ($priv eq 'bre')) {
1.14      www      3721: 	return 'F';
1.159     www      3722:     }
                   3723: 
1.545     banghart 3724: # Free bre access to user's own portfolio contents
1.714     raeburn  3725:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3726:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3727: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3728:         my %setters;
                   3729:         my ($startblock,$endblock) = 
                   3730:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3731:         if ($startblock && $endblock) {
                   3732:             return 'B';
                   3733:         } else {
                   3734:             return 'F';
                   3735:         }
1.545     banghart 3736:     }
                   3737: 
1.762     raeburn  3738: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3739:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3740:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3741:         if (exists($env{'request.course.id'})) {
                   3742:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3743:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3744:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3745:                 my $courseprivid=$env{'request.course.id'};
                   3746:                 $courseprivid=~s/\_/\//;
                   3747:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3748:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3749:                     return $1; 
1.762     raeburn  3750:                 } else {
                   3751:                     if ($env{'request.course.sec'}) {
                   3752:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3753:                     }
                   3754:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3755:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3756:                         return $2;
                   3757:                     }
1.714     raeburn  3758:                 }
                   3759:             }
                   3760:         }
                   3761:     }
                   3762: 
1.159     www      3763: # Free bre to public access
                   3764: 
                   3765:     if ($priv eq 'bre') {
1.238     www      3766:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3767: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3768:            return 'F'; 
                   3769:         }
1.238     www      3770:         if ($copyright eq 'priv') {
                   3771:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3772: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3773: 		return '';
                   3774:             }
                   3775:         }
                   3776:         if ($copyright eq 'domain') {
                   3777:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3778: 	    unless (($env{'user.domain'} eq $1) ||
                   3779:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3780: 		return '';
                   3781:             }
1.262     matthew  3782:         }
1.620     albertel 3783:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3784:             # Library role, so allow browsing of resources in this domain.
                   3785:             return 'F';
1.238     www      3786:         }
1.341     www      3787:         if ($copyright eq 'custom') {
                   3788: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3789:         }
1.14      www      3790:     }
1.264     matthew  3791:     # Domain coordinator is trying to create a course
1.620     albertel 3792:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3793:         # uri is the requested domain in this case.
                   3794:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3795:         # a role of dc for the domain in question.
1.620     albertel 3796:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3797:     }
1.29      www      3798: 
1.52      www      3799:     my $thisallowed='';
                   3800:     my $statecond=0;
                   3801:     my $courseprivid='';
                   3802: 
                   3803: # Course
                   3804: 
1.620     albertel 3805:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3806:        $thisallowed.=$1;
                   3807:     }
1.29      www      3808: 
1.52      www      3809: # Domain
                   3810: 
1.620     albertel 3811:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3812:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3813:        $thisallowed.=$1;
                   3814:     }
1.52      www      3815: 
                   3816: # Course: uri itself is a course
1.66      www      3817:     my $courseuri=$uri;
                   3818:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3819:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3820: 
1.620     albertel 3821:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3822:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3823:        $thisallowed.=$1;
                   3824:     }
1.29      www      3825: 
1.665     albertel 3826: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3827: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3828:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3829: 	$thisallowed='';
1.671     raeburn  3830:         my ($match)=&is_on_map($uri);
                   3831:         if ($match) {
                   3832:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3833:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3834:                 $thisallowed.=$1;
                   3835:             }
                   3836:         } else {
1.705     albertel 3837:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3838:             if ($refuri) {
                   3839:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3840:                     $thisallowed='F';
1.671     raeburn  3841:                 } else {
                   3842:                     $refuri=&declutter($refuri);
                   3843:                     my ($match) = &is_on_map($refuri);
                   3844:                     if ($match) {
                   3845:                         $thisallowed='F';
                   3846:                     }
1.669     raeburn  3847:                 }
1.671     raeburn  3848:             }
                   3849:         }
1.314     www      3850:     }
1.492     albertel 3851: 
1.766     albertel 3852:     if ($priv eq 'bre'
                   3853: 	&& $thisallowed ne 'F' 
                   3854: 	&& $thisallowed ne '2'
                   3855: 	&& &is_portfolio_url($uri)) {
                   3856: 	$thisallowed = &portfolio_access($uri);
                   3857:     }
                   3858:     
1.52      www      3859: # Full access at system, domain or course-wide level? Exit.
1.29      www      3860: 
                   3861:     if ($thisallowed=~/F/) {
                   3862: 	return 'F';
                   3863:     }
                   3864: 
1.52      www      3865: # If this is generating or modifying users, exit with special codes
1.29      www      3866: 
1.643     www      3867:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3868: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3869: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3870: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3871: 	    unless ($auname) { return $thisallowed; }
                   3872: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3873: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3874: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3875: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3876: 	}
1.52      www      3877: 	return $thisallowed;
                   3878:     }
                   3879: #
1.103     harris41 3880: # Gathered so far: system, domain and course wide privileges
1.52      www      3881: #
                   3882: # Course: See if uri or referer is an individual resource that is part of 
                   3883: # the course
                   3884: 
1.620     albertel 3885:     if ($env{'request.course.id'}) {
1.232     www      3886: 
1.620     albertel 3887:        $courseprivid=$env{'request.course.id'};
                   3888:        if ($env{'request.course.sec'}) {
                   3889:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3890:        }
                   3891:        $courseprivid=~s/\_/\//;
                   3892:        my $checkreferer=1;
1.232     www      3893:        my ($match,$cond)=&is_on_map($uri);
                   3894:        if ($match) {
                   3895:            $statecond=$cond;
1.620     albertel 3896:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3897:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3898:                $thisallowed.=$1;
                   3899:                $checkreferer=0;
                   3900:            }
1.29      www      3901:        }
1.83      www      3902:        
1.148     www      3903:        if ($checkreferer) {
1.620     albertel 3904: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3905:             unless ($refuri) {
1.800     albertel 3906:                 foreach my $key (keys(%env)) {
                   3907: 		    if ($key=~/^httpref\..*\*/) {
                   3908: 			my $pattern=$key;
1.156     www      3909:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3910:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3911:                         $pattern=~s/\//\\\//g;
1.152     www      3912:                         if ($orguri=~/$pattern/) {
1.800     albertel 3913: 			    $refuri=$env{$key};
1.148     www      3914:                         }
                   3915:                     }
1.191     harris41 3916:                 }
1.148     www      3917:             }
1.232     www      3918: 
1.148     www      3919:          if ($refuri) { 
1.152     www      3920: 	  $refuri=&declutter($refuri);
1.232     www      3921:           my ($match,$cond)=&is_on_map($refuri);
                   3922:             if ($match) {
                   3923:               my $refstatecond=$cond;
1.620     albertel 3924:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3925:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3926:                   $thisallowed.=$1;
1.53      www      3927:                   $uri=$refuri;
                   3928:                   $statecond=$refstatecond;
1.52      www      3929:               }
                   3930:           }
1.148     www      3931:         }
1.29      www      3932:        }
1.52      www      3933:    }
1.29      www      3934: 
1.52      www      3935: #
1.103     harris41 3936: # Gathered now: all privileges that could apply, and condition number
1.52      www      3937: # 
                   3938: #
                   3939: # Full or no access?
                   3940: #
1.29      www      3941: 
1.52      www      3942:     if ($thisallowed=~/F/) {
                   3943: 	return 'F';
                   3944:     }
1.29      www      3945: 
1.52      www      3946:     unless ($thisallowed) {
                   3947:         return '';
                   3948:     }
1.29      www      3949: 
1.52      www      3950: # Restrictions exist, deal with them
                   3951: #
                   3952: #   C:according to course preferences
                   3953: #   R:according to resource settings
                   3954: #   L:unless locked
                   3955: #   X:according to user session state
                   3956: #
                   3957: 
                   3958: # Possibly locked functionality, check all courses
1.54      www      3959: # Locks might take effect only after 10 minutes cache expiration for other
                   3960: # courses, and 2 minutes for current course
1.52      www      3961: 
                   3962:     my $envkey;
                   3963:     if ($thisallowed=~/L/) {
1.620     albertel 3964:         foreach $envkey (keys %env) {
1.54      www      3965:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3966:                my $courseid=$2;
                   3967:                my $roleid=$1.'.'.$2;
1.92      www      3968:                $courseid=~s/^\///;
1.54      www      3969:                my $expiretime=600;
1.620     albertel 3970:                if ($env{'request.role'} eq $roleid) {
1.54      www      3971: 		  $expiretime=120;
                   3972:                }
                   3973: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3974:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3975:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3976: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3977:                }
1.620     albertel 3978:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3979:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3980: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3981:                        &log($env{'user.domain'},$env{'user.name'},
                   3982:                             $env{'user.home'},
1.57      www      3983:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3984:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3985:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3986: 		       return '';
                   3987:                    }
                   3988:                }
1.620     albertel 3989:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3990:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3991: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3992:                        &log($env{'user.domain'},$env{'user.name'},
                   3993:                             $env{'user.home'},
1.57      www      3994:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3995:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3996:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3997: 		       return '';
                   3998:                    }
                   3999:                }
                   4000: 	   }
1.29      www      4001:        }
1.52      www      4002:     }
                   4003:    
                   4004: #
                   4005: # Rest of the restrictions depend on selected course
                   4006: #
                   4007: 
1.620     albertel 4008:     unless ($env{'request.course.id'}) {
1.766     albertel 4009: 	if ($thisallowed eq 'A') {
                   4010: 	    return 'A';
1.814     raeburn  4011:         } elsif ($thisallowed eq 'B') {
                   4012:             return 'B';
1.766     albertel 4013: 	} else {
                   4014: 	    return '1';
                   4015: 	}
1.52      www      4016:     }
1.29      www      4017: 
1.52      www      4018: #
                   4019: # Now user is definitely in a course
                   4020: #
1.53      www      4021: 
                   4022: 
                   4023: # Course preferences
                   4024: 
                   4025:    if ($thisallowed=~/C/) {
1.620     albertel 4026:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4027:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4028:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4029: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4030: 	   if ($priv ne 'pch') { 
                   4031: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4032: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4033: 			$env{'request.course.id'});
                   4034: 	   }
1.237     www      4035:            return '';
                   4036:        }
                   4037: 
1.620     albertel 4038:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4039: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4040: 	   if ($priv ne 'pch') { 
                   4041: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4042: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4043: 			$env{'request.course.id'});
                   4044: 	   }
1.54      www      4045:            return '';
                   4046:        }
1.53      www      4047:    }
                   4048: 
                   4049: # Resource preferences
                   4050: 
                   4051:    if ($thisallowed=~/R/) {
1.620     albertel 4052:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4053:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4054: 	   if ($priv ne 'pch') { 
                   4055: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4056: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4057: 	   }
                   4058: 	   return '';
1.54      www      4059:        }
1.53      www      4060:    }
1.30      www      4061: 
1.246     www      4062: # Restricted by state or randomout?
1.30      www      4063: 
1.52      www      4064:    if ($thisallowed=~/X/) {
1.620     albertel 4065:       if ($env{'acc.randomout'}) {
1.579     albertel 4066: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4067:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4068:             return ''; 
                   4069:          }
1.247     www      4070:       }
                   4071:       if (&condval($statecond)) {
1.52      www      4072: 	 return '2';
                   4073:       } else {
                   4074:          return '';
                   4075:       }
                   4076:    }
1.30      www      4077: 
1.766     albertel 4078:     if ($thisallowed eq 'A') {
                   4079: 	return 'A';
1.814     raeburn  4080:     } elsif ($thisallowed eq 'B') {
                   4081:         return 'B';
1.766     albertel 4082:     }
1.52      www      4083:    return 'F';
1.232     www      4084: }
                   4085: 
1.710     albertel 4086: sub split_uri_for_cond {
                   4087:     my $uri=&deversion(&declutter(shift));
                   4088:     my @uriparts=split(/\//,$uri);
                   4089:     my $filename=pop(@uriparts);
                   4090:     my $pathname=join('/',@uriparts);
                   4091:     return ($pathname,$filename);
                   4092: }
1.232     www      4093: # --------------------------------------------------- Is a resource on the map?
                   4094: 
                   4095: sub is_on_map {
1.710     albertel 4096:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4097:     #Trying to find the conditional for the file
1.620     albertel 4098:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4099: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4100:     if ($match) {
1.289     bowersj2 4101: 	return (1,$1);
                   4102:     } else {
1.434     www      4103: 	return (0,0);
1.289     bowersj2 4104:     }
1.12      www      4105: }
                   4106: 
1.427     www      4107: # --------------------------------------------------------- Get symb from alias
                   4108: 
                   4109: sub get_symb_from_alias {
                   4110:     my $symb=shift;
                   4111:     my ($map,$resid,$url)=&decode_symb($symb);
                   4112: # Already is a symb
                   4113:     if ($url) { return $symb; }
                   4114: # Must be an alias
                   4115:     my $aliassymb='';
                   4116:     my %bighash;
1.620     albertel 4117:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4118:                             &GDBM_READER(),0640)) {
                   4119:         my $rid=$bighash{'mapalias_'.$symb};
                   4120: 	if ($rid) {
                   4121: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4122: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4123: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4124: 	}
                   4125:         untie %bighash;
                   4126:     }
                   4127:     return $aliassymb;
                   4128: }
                   4129: 
1.12      www      4130: # ----------------------------------------------------------------- Define Role
                   4131: 
                   4132: sub definerole {
                   4133:   if (allowed('mcr','/')) {
                   4134:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4135:     foreach my $role (split(':',$sysrole)) {
                   4136: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4137:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4138:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4139: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4140:                return "refused:s:$crole&$cqual"; 
                   4141:             }
                   4142:         }
1.191     harris41 4143:     }
1.800     albertel 4144:     foreach my $role (split(':',$domrole)) {
                   4145: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4146:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4147:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4148: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4149:                return "refused:d:$crole&$cqual"; 
                   4150:             }
                   4151:         }
1.191     harris41 4152:     }
1.800     albertel 4153:     foreach my $role (split(':',$courole)) {
                   4154: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4155:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4156:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4157: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4158:                return "refused:c:$crole&$cqual"; 
                   4159:             }
                   4160:         }
1.191     harris41 4161:     }
1.620     albertel 4162:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4163:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4164: 	        "rolesdef_$rolename=".
                   4165:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4166:     return reply($command,$env{'user.home'});
1.12      www      4167:   } else {
                   4168:     return 'refused';
                   4169:   }
1.105     harris41 4170: }
                   4171: 
                   4172: # ---------------- Make a metadata query against the network of library servers
                   4173: 
                   4174: sub metadata_query {
1.244     matthew  4175:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4176:     my %rhash;
1.845     albertel 4177:     my %libserv = &all_library();
1.244     matthew  4178:     my @server_list = (defined($server_array) ? @$server_array
                   4179:                                               : keys(%libserv) );
                   4180:     for my $server (@server_list) {
1.118     harris41 4181: 	unless ($custom or $customshow) {
                   4182: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4183: 	    $rhash{$server}=$reply;
                   4184: 	}
                   4185: 	else {
                   4186: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4187: 			     &escape($custom).':'.&escape($customshow),
                   4188: 			     $server);
                   4189: 	    $rhash{$server}=$reply;
                   4190: 	}
1.112     harris41 4191:     }
1.118     harris41 4192:     return \%rhash;
1.240     www      4193: }
                   4194: 
                   4195: # ----------------------------------------- Send log queries and wait for reply
                   4196: 
                   4197: sub log_query {
                   4198:     my ($uname,$udom,$query,%filters)=@_;
                   4199:     my $uhome=&homeserver($uname,$udom);
                   4200:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4201:     my $uhost=&hostname($uhome);
1.800     albertel 4202:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4203:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4204:                        $uhome);
1.479     albertel 4205:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4206:     return get_query_reply($queryid);
                   4207: }
                   4208: 
1.818     raeburn  4209: # -------------------------- Update MySQL table for portfolio file
                   4210: 
                   4211: sub update_portfolio_table {
1.821     raeburn  4212:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4213:     my $homeserver = &homeserver($uname,$udom);
                   4214:     my $queryid=
1.821     raeburn  4215:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4216:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4217:     my $reply = &get_query_reply($queryid);
                   4218:     return $reply;
                   4219: }
                   4220: 
1.508     raeburn  4221: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4222: 
                   4223: sub fetch_enrollment_query {
1.511     raeburn  4224:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4225:     my $homeserver;
1.547     raeburn  4226:     my $maxtries = 1;
1.508     raeburn  4227:     if ($context eq 'automated') {
                   4228:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4229:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4230:     } else {
                   4231:         $homeserver = &homeserver($cnum,$dom);
                   4232:     }
1.838     albertel 4233:     my $host=&hostname($homeserver);
1.506     raeburn  4234:     my $cmd = '';
1.800     albertel 4235:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4236:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4237:     }
                   4238:     $cmd =~ s/%%$//;
                   4239:     $cmd = &escape($cmd);
                   4240:     my $query = 'fetchenrollment';
1.620     albertel 4241:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4242:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4243:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4244:         return 'error: '.$queryid;
                   4245:     }
1.506     raeburn  4246:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4247:     my $tries = 1;
                   4248:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4249:         $reply = &get_query_reply($queryid);
                   4250:         $tries ++;
                   4251:     }
1.526     raeburn  4252:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4253:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4254:     } else {
1.515     raeburn  4255:         my @responses = split/:/,$reply;
                   4256:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4257:             foreach my $line (@responses) {
                   4258:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4259:                 $$replyref{$key} = $value;
                   4260:             }
                   4261:         } else {
1.506     raeburn  4262:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4263:             foreach my $line (@responses) {
                   4264:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4265:                 $$replyref{$key} = $value;
                   4266:                 if ($value > 0) {
1.800     albertel 4267:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4268:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4269:                         my $destname = $pathname.'/'.$filename;
                   4270:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4271:                         if ($xml_classlist =~ /^error/) {
                   4272:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4273:                         } else {
1.506     raeburn  4274:                             if ( open(FILE,">$destname") ) {
                   4275:                                 print FILE &unescape($xml_classlist);
                   4276:                                 close(FILE);
1.526     raeburn  4277:                             } else {
                   4278:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4279:                             }
                   4280:                         }
                   4281:                     }
                   4282:                 }
                   4283:             }
                   4284:         }
                   4285:         return 'ok';
                   4286:     }
                   4287:     return 'error';
                   4288: }
                   4289: 
1.242     www      4290: sub get_query_reply {
                   4291:     my $queryid=shift;
1.240     www      4292:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4293:     my $reply='';
                   4294:     for (1..100) {
                   4295: 	sleep 2;
                   4296:         if (-e $replyfile.'.end') {
1.448     albertel 4297: 	    if (open(my $fh,$replyfile)) {
1.240     www      4298:                $reply.=<$fh>;
1.448     albertel 4299:                close($fh);
1.240     www      4300: 	   } else { return 'error: reply_file_error'; }
1.242     www      4301:            return &unescape($reply);
                   4302: 	}
1.240     www      4303:     }
1.242     www      4304:     return 'timeout:'.$queryid;
1.240     www      4305: }
                   4306: 
                   4307: sub courselog_query {
1.241     www      4308: #
                   4309: # possible filters:
                   4310: # url: url or symb
                   4311: # username
                   4312: # domain
                   4313: # action: view, submit, grade
                   4314: # start: timestamp
                   4315: # end: timestamp
                   4316: #
1.240     www      4317:     my (%filters)=@_;
1.620     albertel 4318:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4319:     if ($filters{'url'}) {
                   4320: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4321:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4322:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4323:     }
1.620     albertel 4324:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4325:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4326:     return &log_query($cname,$cdom,'courselog',%filters);
                   4327: }
                   4328: 
                   4329: sub userlog_query {
                   4330:     my ($uname,$udom,%filters)=@_;
                   4331:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4332: }
                   4333: 
1.506     raeburn  4334: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4335: 
                   4336: sub auto_run {
1.508     raeburn  4337:     my ($cnum,$cdom) = @_;
                   4338:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4339:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4340:     return $response;
                   4341: }
1.776     albertel 4342: 
1.506     raeburn  4343: sub auto_get_sections {
1.508     raeburn  4344:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4345:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4346:     my @secs = ();
1.511     raeburn  4347:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4348:     unless ($response eq 'refused') {
                   4349:         @secs = split/:/,$response;
                   4350:     }
                   4351:     return @secs;
                   4352: }
1.776     albertel 4353: 
1.506     raeburn  4354: sub auto_new_course {
1.508     raeburn  4355:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4356:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4357:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4358:     return $response;
                   4359: }
1.776     albertel 4360: 
1.506     raeburn  4361: sub auto_validate_courseID {
1.508     raeburn  4362:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4363:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4364:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4365:     return $response;
                   4366: }
1.776     albertel 4367: 
1.506     raeburn  4368: sub auto_create_password {
1.508     raeburn  4369:     my ($cnum,$cdom,$authparam) = @_;
                   4370:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4371:     my $create_passwd = 0;
                   4372:     my $authchk = '';
1.511     raeburn  4373:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4374:     if ($response eq 'refused') {
                   4375:         $authchk = 'refused';
                   4376:     } else {
                   4377:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4378:     }
                   4379:     return ($authparam,$create_passwd,$authchk);
                   4380: }
                   4381: 
1.706     raeburn  4382: sub auto_photo_permission {
                   4383:     my ($cnum,$cdom,$students) = @_;
                   4384:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4385:     my ($outcome,$perm_reqd,$conditions) = 
                   4386: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4387:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4388: 	return (undef,undef);
                   4389:     }
1.706     raeburn  4390:     return ($outcome,$perm_reqd,$conditions);
                   4391: }
                   4392: 
                   4393: sub auto_checkphotos {
                   4394:     my ($uname,$udom,$pid) = @_;
                   4395:     my $homeserver = &homeserver($uname,$udom);
                   4396:     my ($result,$resulttype);
                   4397:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4398: 				   &escape($uname).':'.&escape($pid),
                   4399: 				   $homeserver));
1.709     albertel 4400:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4401: 	return (undef,undef);
                   4402:     }
1.706     raeburn  4403:     if ($outcome) {
                   4404:         ($result,$resulttype) = split(/:/,$outcome);
                   4405:     } 
                   4406:     return ($result,$resulttype);
                   4407: }
                   4408: 
                   4409: sub auto_photochoice {
                   4410:     my ($cnum,$cdom) = @_;
                   4411:     my $homeserver = &homeserver($cnum,$cdom);
                   4412:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4413: 						       &escape($cdom),
                   4414: 						       $homeserver)));
1.709     albertel 4415:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4416: 	return (undef,undef);
                   4417:     }
1.706     raeburn  4418:     return ($update,$comment);
                   4419: }
                   4420: 
                   4421: sub auto_photoupdate {
                   4422:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4423:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4424:     my $host=&hostname($homeserver);
1.706     raeburn  4425:     my $cmd = '';
                   4426:     my $maxtries = 1;
1.800     albertel 4427:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4428:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4429:     }
                   4430:     $cmd =~ s/%%$//;
                   4431:     $cmd = &escape($cmd);
                   4432:     my $query = 'institutionalphotos';
                   4433:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4434:     unless ($queryid=~/^\Q$host\E\_/) {
                   4435:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4436:         return 'error: '.$queryid;
                   4437:     }
                   4438:     my $reply = &get_query_reply($queryid);
                   4439:     my $tries = 1;
                   4440:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4441:         $reply = &get_query_reply($queryid);
                   4442:         $tries ++;
                   4443:     }
                   4444:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4445:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4446:     } else {
                   4447:         my @responses = split(/:/,$reply);
                   4448:         my $outcome = shift(@responses); 
                   4449:         foreach my $item (@responses) {
                   4450:             my ($key,$value) = split(/=/,$item);
                   4451:             $$photo{$key} = $value;
                   4452:         }
                   4453:         return $outcome;
                   4454:     }
                   4455:     return 'error';
                   4456: }
                   4457: 
1.521     raeburn  4458: sub auto_instcode_format {
1.793     albertel 4459:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4460: 	$cat_order) = @_;
1.521     raeburn  4461:     my $courses = '';
1.772     raeburn  4462:     my @homeservers;
1.521     raeburn  4463:     if ($caller eq 'global') {
1.841     albertel 4464: 	my %servers = &get_servers($codedom,'library');
                   4465: 	foreach my $tryserver (keys(%servers)) {
                   4466: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4467: 		push(@homeservers,$tryserver);
                   4468: 	    }
1.584     raeburn  4469:         }
1.521     raeburn  4470:     } else {
1.772     raeburn  4471:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4472:     }
1.793     albertel 4473:     foreach my $code (keys(%{$instcodes})) {
                   4474:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4475:     }
                   4476:     chop($courses);
1.772     raeburn  4477:     my $ok_response = 0;
                   4478:     my $response;
                   4479:     while (@homeservers > 0 && $ok_response == 0) {
                   4480:         my $server = shift(@homeservers); 
                   4481:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4482:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4483:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4484: 		split/:/,$response;
1.772     raeburn  4485:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4486:             push(@{$codetitles},&str2array($codetitles_str));
                   4487:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4488:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4489:             $ok_response = 1;
                   4490:         }
                   4491:     }
                   4492:     if ($ok_response) {
1.521     raeburn  4493:         return 'ok';
1.772     raeburn  4494:     } else {
                   4495:         return $response;
1.521     raeburn  4496:     }
                   4497: }
                   4498: 
1.792     raeburn  4499: sub auto_instcode_defaults {
                   4500:     my ($domain,$returnhash,$code_order) = @_;
                   4501:     my @homeservers;
1.841     albertel 4502: 
                   4503:     my %servers = &get_servers($domain,'library');
                   4504:     foreach my $tryserver (keys(%servers)) {
                   4505: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4506: 	    push(@homeservers,$tryserver);
                   4507: 	}
1.792     raeburn  4508:     }
1.841     albertel 4509: 
1.792     raeburn  4510:     my $response;
1.841     albertel 4511:     foreach my $server (@homeservers) {
1.792     raeburn  4512:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4513:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4514: 	
                   4515: 	foreach my $pair (split(/\&/,$response)) {
                   4516: 	    my ($name,$value)=split(/\=/,$pair);
                   4517: 	    if ($name eq 'code_order') {
                   4518: 		@{$code_order} = split(/\&/,&unescape($value));
                   4519: 	    } else {
                   4520: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4521: 	    }
                   4522: 	}
                   4523: 	return 'ok';
1.792     raeburn  4524:     }
1.841     albertel 4525: 
                   4526:     return $response;
1.792     raeburn  4527: } 
                   4528: 
1.777     albertel 4529: sub auto_validate_class_sec {
1.773     raeburn  4530:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4531:     my $homeserver = &homeserver($cnum,$cdom);
                   4532:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4533:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4534:     return $response;
                   4535: }
                   4536: 
1.679     raeburn  4537: # ------------------------------------------------------- Course Group routines
                   4538: 
                   4539: sub get_coursegroups {
1.809     raeburn  4540:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4541:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4542: }
                   4543: 
1.679     raeburn  4544: sub modify_coursegroup {
                   4545:     my ($cdom,$cnum,$groupsettings) = @_;
                   4546:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4547: }
                   4548: 
1.809     raeburn  4549: sub toggle_coursegroup_status {
                   4550:     my ($cdom,$cnum,$group,$action) = @_;
                   4551:     my ($from_namespace,$to_namespace);
                   4552:     if ($action eq 'delete') {
                   4553:         $from_namespace = 'coursegroups';
                   4554:         $to_namespace = 'deleted_groups';
                   4555:     } else {
                   4556:         $from_namespace = 'deleted_groups';
                   4557:         $to_namespace = 'coursegroups';
                   4558:     }
                   4559:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4560:     if (my $tmp = &error(%curr_group)) {
                   4561:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4562:         return ('read error',$tmp);
                   4563:     } else {
                   4564:         my %savedsettings = %curr_group; 
1.809     raeburn  4565:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4566:         my $deloutcome;
                   4567:         if ($result eq 'ok') {
1.809     raeburn  4568:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4569:         } else {
                   4570:             return ('write error',$result);
                   4571:         }
                   4572:         if ($deloutcome eq 'ok') {
                   4573:             return 'ok';
                   4574:         } else {
                   4575:             return ('delete error',$deloutcome);
                   4576:         }
                   4577:     }
                   4578: }
                   4579: 
1.679     raeburn  4580: sub modify_group_roles {
                   4581:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4582:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4583:     my $role = 'gr/'.&escape($userprivs);
                   4584:     my ($uname,$udom) = split(/:/,$user);
                   4585:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4586:     if ($result eq 'ok') {
                   4587:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4588:     }
1.679     raeburn  4589:     return $result;
                   4590: }
                   4591: 
                   4592: sub modify_coursegroup_membership {
                   4593:     my ($cdom,$cnum,$membership) = @_;
                   4594:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4595:     return $result;
                   4596: }
                   4597: 
1.682     raeburn  4598: sub get_active_groups {
                   4599:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4600:     my $now = time;
                   4601:     my %groups = ();
                   4602:     foreach my $key (keys(%env)) {
1.811     albertel 4603:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4604:             my ($start,$end) = split(/\./,$env{$key});
                   4605:             if (($end!=0) && ($end<$now)) { next; }
                   4606:             if (($start!=0) && ($start>$now)) { next; }
                   4607:             if ($1 eq $cdom && $2 eq $cnum) {
                   4608:                 $groups{$3} = $env{$key} ;
                   4609:             }
                   4610:         }
                   4611:     }
                   4612:     return %groups;
                   4613: }
                   4614: 
1.683     raeburn  4615: sub get_group_membership {
                   4616:     my ($cdom,$cnum,$group) = @_;
                   4617:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4618: }
                   4619: 
                   4620: sub get_users_groups {
                   4621:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4622:     my @usersgroups;
1.683     raeburn  4623:     my $cachetime=1800;
                   4624: 
                   4625:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4626:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4627:     if (defined($cached)) {
1.734     albertel 4628:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4629:     } else {  
                   4630:         $grouplist = '';
1.816     raeburn  4631:         my $courseurl = &courseid_to_courseurl($courseid);
                   4632:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4633:         my $access_end = $env{'course.'.$courseid.
                   4634:                               '.default_enrollment_end_date'};
                   4635:         my $now = time;
                   4636:         foreach my $key (keys(%roleshash)) {
                   4637:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4638:                 my $group = $1;
                   4639:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4640:                     my $start = $2;
                   4641:                     my $end = $1;
                   4642:                     if ($start == -1) { next; } # deleted from group
                   4643:                     if (($start!=0) && ($start>$now)) { next; }
                   4644:                     if (($end!=0) && ($end<$now)) {
                   4645:                         if ($access_end && $access_end < $now) {
                   4646:                             if ($access_end - $end < 86400) {
                   4647:                                 push(@usersgroups,$group);
1.733     raeburn  4648:                             }
                   4649:                         }
1.817     raeburn  4650:                         next;
1.733     raeburn  4651:                     }
1.817     raeburn  4652:                     push(@usersgroups,$group);
1.683     raeburn  4653:                 }
                   4654:             }
                   4655:         }
1.817     raeburn  4656:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4657:         $grouplist = join(':',@usersgroups);
                   4658:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4659:     }
1.733     raeburn  4660:     return @usersgroups;
1.683     raeburn  4661: }
                   4662: 
                   4663: sub devalidate_getgroups_cache {
                   4664:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4665:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4666: 
1.683     raeburn  4667:     my $hashid="$udom:$uname:$courseid";
                   4668:     &devalidate_cache_new('getgroups',$hashid);
                   4669: }
                   4670: 
1.12      www      4671: # ------------------------------------------------------------------ Plain Text
                   4672: 
                   4673: sub plaintext {
1.742     raeburn  4674:     my ($short,$type,$cid) = @_;
1.758     albertel 4675:     if ($short =~ /^cr/) {
                   4676: 	return (split('/',$short))[-1];
                   4677:     }
1.742     raeburn  4678:     if (!defined($cid)) {
                   4679:         $cid = $env{'request.course.id'};
                   4680:     }
                   4681:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4682:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4683:                                           '.plaintext'});
                   4684:     }
                   4685:     my %rolenames = (
                   4686:                       Course => 'std',
                   4687:                       Group => 'alt1',
                   4688:                     );
                   4689:     if (defined($type) && 
                   4690:          defined($rolenames{$type}) && 
                   4691:          defined($prp{$short}{$rolenames{$type}})) {
                   4692:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4693:     } else {
                   4694:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4695:     }
1.12      www      4696: }
                   4697: 
                   4698: # ----------------------------------------------------------------- Assign Role
                   4699: 
                   4700: sub assignrole {
1.357     www      4701:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4702:     my $mrole;
                   4703:     if ($role =~ /^cr\//) {
1.393     www      4704:         my $cwosec=$url;
1.811     albertel 4705:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4706: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4707:            &logthis('Refused custom assignrole: '.
                   4708:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4709: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4710:            return 'refused'; 
                   4711:         }
1.21      www      4712:         $mrole='cr';
1.678     raeburn  4713:     } elsif ($role =~ /^gr\//) {
                   4714:         my $cwogrp=$url;
1.811     albertel 4715:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4716:         unless (&allowed('mdg',$cwogrp)) {
                   4717:             &logthis('Refused group assignrole: '.
                   4718:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4719:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4720:             return 'refused';
                   4721:         }
                   4722:         $mrole='gr';
1.21      www      4723:     } else {
1.82      www      4724:         my $cwosec=$url;
1.811     albertel 4725:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4726:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4727:            &logthis('Refused assignrole: '.
                   4728:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4729: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4730:            return 'refused'; 
                   4731:         }
1.21      www      4732:         $mrole=$role;
                   4733:     }
1.620     albertel 4734:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4735:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4736:     if ($end) { $command.='_'.$end; }
1.21      www      4737:     if ($start) {
                   4738: 	if ($end) { 
1.81      www      4739:            $command.='_'.$start; 
1.21      www      4740:         } else {
1.81      www      4741:            $command.='_0_'.$start;
1.21      www      4742:         }
                   4743:     }
1.739     raeburn  4744:     my $origstart = $start;
                   4745:     my $origend = $end;
1.357     www      4746: # actually delete
                   4747:     if ($deleteflag) {
1.373     www      4748: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4749: # modify command to delete the role
1.620     albertel 4750:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4751:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4752: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4753: # set start and finish to negative values for userrolelog
                   4754:            $start=-1;
                   4755:            $end=-1;
                   4756:         }
                   4757:     }
                   4758: # send command
1.349     www      4759:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4760: # log new user role if status is ok
1.349     www      4761:     if ($answer eq 'ok') {
1.663     raeburn  4762: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4763: # for course roles, perform group memberships changes triggered by role change.
                   4764:         unless ($role =~ /^gr/) {
                   4765:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4766:                                              $origstart);
                   4767:         }
1.349     www      4768:     }
                   4769:     return $answer;
1.169     harris41 4770: }
                   4771: 
                   4772: # -------------------------------------------------- Modify user authentication
1.197     www      4773: # Overrides without validation
                   4774: 
1.169     harris41 4775: sub modifyuserauth {
                   4776:     my ($udom,$uname,$umode,$upass)=@_;
                   4777:     my $uhome=&homeserver($uname,$udom);
1.197     www      4778:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4779:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4780:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4781:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4782:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4783: 		     &escape($upass),$uhome);
1.620     albertel 4784:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4785:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4786:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4787:     &log($udom,,$uname,$uhome,
1.620     albertel 4788:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4789:                                      $env{'user.name'}.', '.$umode.
1.197     www      4790:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4791:     unless ($reply eq 'ok') {
1.197     www      4792:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4793: 	return 'error: '.$reply;
                   4794:     }   
1.170     harris41 4795:     return 'ok';
1.80      www      4796: }
                   4797: 
1.81      www      4798: # --------------------------------------------------------------- Modify a user
1.80      www      4799: 
1.81      www      4800: sub modifyuser {
1.206     matthew  4801:     my ($udom,    $uname, $uid,
                   4802:         $umode,   $upass, $first,
                   4803:         $middle,  $last,  $gene,
1.387     www      4804:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4805:     $udom= &LONCAPA::clean_domain($udom);
                   4806:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4807:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4808:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4809: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4810:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4811:                                      ' desiredhome not specified'). 
1.620     albertel 4812:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4813:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4814:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4815: # ----------------------------------------------------------------- Create User
1.406     albertel 4816:     if (($uhome eq 'no_host') && 
                   4817: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4818:         my $unhome='';
1.844     albertel 4819:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4820:             $unhome = $desiredhome;
1.620     albertel 4821: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4822: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4823:         } else { # load balancing routine for determining $unhome
1.81      www      4824:             my $loadm=10000000;
1.841     albertel 4825: 	    my %servers = &get_servers($udom,'library');
                   4826: 	    foreach my $tryserver (keys(%servers)) {
                   4827: 		my $answer=reply('load',$tryserver);
                   4828: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4829: 		    $loadm=$answer;
                   4830: 		    $unhome=$tryserver;
                   4831: 		}
1.80      www      4832: 	    }
                   4833:         }
                   4834:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4835: 	    return 'error: unable to find a home server for '.$uname.
                   4836:                    ' in domain '.$udom;
1.80      www      4837:         }
                   4838:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4839:                          &escape($upass),$unhome);
                   4840: 	unless ($reply eq 'ok') {
                   4841:             return 'error: '.$reply;
                   4842:         }   
1.230     stredwic 4843:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4844:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4845: 	    return 'error: unable verify users home machine.';
1.80      www      4846:         }
1.209     matthew  4847:     }   # End of creation of new user
1.80      www      4848: # ---------------------------------------------------------------------- Add ID
                   4849:     if ($uid) {
                   4850:        $uid=~tr/A-Z/a-z/;
                   4851:        my %uidhash=&idrget($udom,$uname);
1.196     www      4852:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4853:          && (!$forceid)) {
1.80      www      4854: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4855: 	      return 'error: user id "'.$uid.'" does not match '.
                   4856:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4857:           }
                   4858:        } else {
                   4859: 	  &idput($udom,($uname => $uid));
                   4860:        }
                   4861:     }
                   4862: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4863:     my @tmp=&get('environment',
1.134     albertel 4864: 		   ['firstname','middlename','lastname','generation'],
                   4865: 		   $udom,$uname);
1.313     matthew  4866:     my %names;
                   4867:     if ($tmp[0] =~ m/^error:.*/) { 
                   4868:         %names=(); 
                   4869:     } else {
                   4870:         %names = @tmp;
                   4871:     }
1.388     www      4872: #
                   4873: # Make sure to not trash student environment if instructor does not bother
                   4874: # to supply name and email information
                   4875: #
                   4876:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4877:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4878:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4879:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4880:     if ($email) {
                   4881:        $email=~s/[^\w\@\.\-\,]//gs;
                   4882:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4883: 			   $names{'critnotification'} = $email;
                   4884: 			   $names{'permanentemail'} = $email; }
                   4885:     }
1.134     albertel 4886:     my $reply = &put('environment', \%names, $udom,$uname);
                   4887:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4888:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4889:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4890:              $umode.', '.$first.', '.$middle.', '.
                   4891: 	     $last.', '.$gene.' by '.
1.620     albertel 4892:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4893:     return 'ok';
1.80      www      4894: }
                   4895: 
1.81      www      4896: # -------------------------------------------------------------- Modify student
1.80      www      4897: 
1.81      www      4898: sub modifystudent {
                   4899:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4900:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4901:     if (!$cid) {
1.620     albertel 4902: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4903: 	    return 'not_in_class';
                   4904: 	}
1.80      www      4905:     }
                   4906: # --------------------------------------------------------------- Make the user
1.81      www      4907:     my $reply=&modifyuser
1.209     matthew  4908: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4909:          $desiredhome,$email);
1.80      www      4910:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4911:     # This will cause &modify_student_enrollment to get the uid from the
                   4912:     # students environment
                   4913:     $uid = undef if (!$forceid);
1.455     albertel 4914:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4915: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4916:     return $reply;
                   4917: }
                   4918: 
                   4919: sub modify_student_enrollment {
1.515     raeburn  4920:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4921:     my ($cdom,$cnum,$chome);
                   4922:     if (!$cid) {
1.620     albertel 4923: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4924: 	    return 'not_in_class';
                   4925: 	}
1.620     albertel 4926: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4927: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4928:     } else {
                   4929: 	($cdom,$cnum)=split(/_/,$cid);
                   4930:     }
1.620     albertel 4931:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4932:     if (!$chome) {
1.457     raeburn  4933: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4934:     }
1.455     albertel 4935:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4936:     # Make sure the user exists
1.81      www      4937:     my $uhome=&homeserver($uname,$udom);
                   4938:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4939: 	return 'error: no such user';
                   4940:     }
1.297     matthew  4941:     # Get student data if we were not given enough information
                   4942:     if (!defined($first)  || $first  eq '' || 
                   4943:         !defined($last)   || $last   eq '' || 
                   4944:         !defined($uid)    || $uid    eq '' || 
                   4945:         !defined($middle) || $middle eq '' || 
                   4946:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4947:         # They did not supply us with enough data to enroll the student, so
                   4948:         # we need to pick up more information.
1.297     matthew  4949:         my %tmp = &get('environment',
1.294     matthew  4950:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4951:                        ,$udom,$uname);
                   4952: 
1.800     albertel 4953:         #foreach my $key (keys(%tmp)) {
                   4954:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4955:         #}
1.294     matthew  4956:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4957:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4958:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4959:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4960:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4961:     }
1.556     albertel 4962:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4963:     my $reply=cput('classlist',
                   4964: 		   {"$uname:$udom" => 
1.515     raeburn  4965: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4966: 		   $cdom,$cnum);
1.81      www      4967:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4968: 	return 'error: '.$reply;
1.652     albertel 4969:     } else {
                   4970: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4971:     }
1.297     matthew  4972:     # Add student role to user
1.83      www      4973:     my $uurl='/'.$cid;
1.81      www      4974:     $uurl=~s/\_/\//g;
                   4975:     if ($usec) {
                   4976: 	$uurl.='/'.$usec;
                   4977:     }
                   4978:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4979: }
                   4980: 
1.556     albertel 4981: sub format_name {
                   4982:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4983:     my $name;
                   4984:     if ($first ne 'lastname') {
                   4985: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4986:     } else {
                   4987: 	if ($lastname=~/\S/) {
                   4988: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4989: 	    $name=~s/\s+,/,/;
                   4990: 	} else {
                   4991: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4992: 	}
                   4993:     }
                   4994:     $name=~s/^\s+//;
                   4995:     $name=~s/\s+$//;
                   4996:     $name=~s/\s+/ /g;
                   4997:     return $name;
                   4998: }
                   4999: 
1.84      www      5000: # ------------------------------------------------- Write to course preferences
                   5001: 
                   5002: sub writecoursepref {
                   5003:     my ($courseid,%prefs)=@_;
                   5004:     $courseid=~s/^\///;
                   5005:     $courseid=~s/\_/\//g;
                   5006:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5007:     my $chome=homeserver($cnum,$cdomain);
                   5008:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5009: 	return 'error: no such course';
                   5010:     }
                   5011:     my $cstring='';
1.800     albertel 5012:     foreach my $pref (keys(%prefs)) {
                   5013: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5014:     }
1.84      www      5015:     $cstring=~s/\&$//;
                   5016:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5017: }
                   5018: 
                   5019: # ---------------------------------------------------------- Make/modify course
                   5020: 
                   5021: sub createcourse {
1.741     raeburn  5022:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5023:         $course_owner,$crstype)=@_;
1.84      www      5024:     $url=&declutter($url);
                   5025:     my $cid='';
1.264     matthew  5026:     unless (&allowed('ccc',$udom)) {
1.84      www      5027:         return 'refused';
                   5028:     }
                   5029: # ------------------------------------------------------------------- Create ID
1.674     www      5030:    my $uname=int(1+rand(9)).
                   5031:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5032:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5033:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5034: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5035:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5036:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5037:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5038:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5039:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5040:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5041:            return 'error: unable to generate unique course-ID';
                   5042:        } 
                   5043:    }
1.264     matthew  5044: # ------------------------------------------------ Check supplied server name
1.620     albertel 5045:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5046:     if (! &is_library($course_server)) {
1.264     matthew  5047:         return 'error:bad server name '.$course_server;
                   5048:     }
1.84      www      5049: # ------------------------------------------------------------- Make the course
                   5050:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5051:                       $course_server);
1.84      www      5052:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5053:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5054:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5055: 	return 'error: no such course';
                   5056:     }
1.271     www      5057: # ----------------------------------------------------------------- Course made
1.516     raeburn  5058: # log existence
                   5059:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5060:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5061:                   &escape($crstype),$uhome);
1.358     www      5062:     &flushcourselogs();
                   5063: # set toplevel url
1.271     www      5064:     my $topurl=$url;
                   5065:     unless ($nonstandard) {
                   5066: # ------------------------------------------ For standard courses, make top url
                   5067:         my $mapurl=&clutter($url);
1.278     www      5068:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5069:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5070: <map>
                   5071: <resource id="1" type="start"></resource>
                   5072: <resource id="2" src="$mapurl"></resource>
                   5073: <resource id="3" type="finish"></resource>
                   5074: <link index="1" from="1" to="2"></link>
                   5075: <link index="2" from="2" to="3"></link>
                   5076: </map>
                   5077: ENDINITMAP
                   5078:         $topurl=&declutter(
1.638     albertel 5079:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5080:                           );
                   5081:     }
                   5082: # ----------------------------------------------------------- Write preferences
1.84      www      5083:     &writecoursepref($udom.'_'.$uname,
                   5084:                      ('description' => $description,
1.271     www      5085:                       'url'         => $topurl));
1.84      www      5086:     return '/'.$udom.'/'.$uname;
                   5087: }
                   5088: 
1.813     albertel 5089: sub is_course {
                   5090:     my ($cdom,$cnum) = @_;
                   5091:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5092: 				undef,'.');
                   5093:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5094:         return 1;
                   5095:     }
                   5096:     return 0;
                   5097: }
                   5098: 
1.21      www      5099: # ---------------------------------------------------------- Assign Custom Role
                   5100: 
                   5101: sub assigncustomrole {
1.357     www      5102:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5103:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5104:                        $end,$start,$deleteflag);
1.21      www      5105: }
                   5106: 
                   5107: # ----------------------------------------------------------------- Revoke Role
                   5108: 
                   5109: sub revokerole {
1.357     www      5110:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5111:     my $now=time;
1.357     www      5112:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5113: }
                   5114: 
                   5115: # ---------------------------------------------------------- Revoke Custom Role
                   5116: 
                   5117: sub revokecustomrole {
1.357     www      5118:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5119:     my $now=time;
1.357     www      5120:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5121:            $deleteflag);
1.17      www      5122: }
                   5123: 
1.533     banghart 5124: # ------------------------------------------------------------ Disk usage
1.535     albertel 5125: sub diskusage {
1.533     banghart 5126:     my ($udom,$uname,$directoryRoot)=@_;
                   5127:     $directoryRoot =~ s/\/$//;
1.535     albertel 5128:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5129:     return $listing;
1.512     banghart 5130: }
                   5131: 
1.566     banghart 5132: sub is_locked {
                   5133:     my ($file_name, $domain, $user) = @_;
                   5134:     my @check;
                   5135:     my $is_locked;
                   5136:     push @check, $file_name;
1.613     albertel 5137:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5138: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5139:     my ($tmp)=keys(%locked);
                   5140:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5141:     
1.566     banghart 5142:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5143:         $is_locked = 'false';
                   5144:         foreach my $entry (@{$locked{$file_name}}) {
                   5145:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5146:                $is_locked = 'true';
                   5147:                last;
1.745     raeburn  5148:            }
                   5149:        }
1.566     banghart 5150:     } else {
                   5151:         $is_locked = 'false';
                   5152:     }
                   5153: }
                   5154: 
1.759     albertel 5155: sub declutter_portfile {
                   5156:     my ($file) = @_;
1.833     albertel 5157:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5158:     return $file;
                   5159: }
                   5160: 
1.559     banghart 5161: # ------------------------------------------------------------- Mark as Read Only
                   5162: 
                   5163: sub mark_as_readonly {
                   5164:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5165:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5166:     my ($tmp)=keys(%current_permissions);
                   5167:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5168:     foreach my $file (@{$files}) {
1.759     albertel 5169: 	$file = &declutter_portfile($file);
1.561     banghart 5170:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5171:     }
1.613     albertel 5172:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5173:     return;
                   5174: }
                   5175: 
1.572     banghart 5176: # ------------------------------------------------------------Save Selected Files
                   5177: 
                   5178: sub save_selected_files {
                   5179:     my ($user, $path, @files) = @_;
                   5180:     my $filename = $user."savedfiles";
1.573     banghart 5181:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5182:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5183:     foreach my $file (@files) {
1.620     albertel 5184:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5185:     }
                   5186:     foreach my $file (@other_files) {
1.574     banghart 5187:         print (OUT $file."\n");
1.572     banghart 5188:     }
1.574     banghart 5189:     close (OUT);
1.572     banghart 5190:     return 'ok';
                   5191: }
                   5192: 
1.574     banghart 5193: sub clear_selected_files {
                   5194:     my ($user) = @_;
                   5195:     my $filename = $user."savedfiles";
                   5196:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5197:     print (OUT undef);
                   5198:     close (OUT);
                   5199:     return ("ok");    
                   5200: }
                   5201: 
1.572     banghart 5202: sub files_in_path {
                   5203:     my ($user, $path) = @_;
                   5204:     my $filename = $user."savedfiles";
                   5205:     my %return_files;
1.574     banghart 5206:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5207:     while (my $line_in = <IN>) {
1.574     banghart 5208:         chomp ($line_in);
                   5209:         my @paths_and_file = split (m!/!, $line_in);
                   5210:         my $file_part = pop (@paths_and_file);
                   5211:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5212:         $path_part.='/';
                   5213:         my $path_and_file = $path_part.$file_part;
                   5214:         if ($path_part eq $path) {
                   5215:             $return_files{$file_part}= 'selected';
                   5216:         }
                   5217:     }
1.574     banghart 5218:     close (IN);
                   5219:     return (\%return_files);
1.572     banghart 5220: }
                   5221: 
                   5222: # called in portfolio select mode, to show files selected NOT in current directory
                   5223: sub files_not_in_path {
                   5224:     my ($user, $path) = @_;
                   5225:     my $filename = $user."savedfiles";
                   5226:     my @return_files;
                   5227:     my $path_part;
1.800     albertel 5228:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5229:     while (my $line = <IN>) {
1.572     banghart 5230:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5231:         my @paths_and_file = split(m|/|, $line);
                   5232:         my $file_part = pop(@paths_and_file);
                   5233:         chomp($file_part);
                   5234:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5235:         $path_part .= '/';
                   5236:         my $path_and_file = $path_part.$file_part;
                   5237:         if ($path_part ne $path) {
1.800     albertel 5238:             push(@return_files, ($path_and_file));
1.572     banghart 5239:         }
                   5240:     }
1.800     albertel 5241:     close(OUT);
1.574     banghart 5242:     return (@return_files);
1.572     banghart 5243: }
                   5244: 
1.745     raeburn  5245: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5246: 
1.745     raeburn  5247: sub get_portfile_permissions {
                   5248:     my ($domain,$user) = @_;
1.613     albertel 5249:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5250:     my ($tmp)=keys(%current_permissions);
                   5251:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5252:     return \%current_permissions;
                   5253: }
                   5254: 
                   5255: #---------------------------------------------Get portfolio file access controls
                   5256: 
1.749     raeburn  5257: sub get_access_controls {
1.745     raeburn  5258:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5259:     my %access;
                   5260:     my $real_file = $file;
                   5261:     $file =~ s/\.meta$//;
1.745     raeburn  5262:     if (defined($file)) {
1.749     raeburn  5263:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5264:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5265:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5266:             }
                   5267:         }
1.745     raeburn  5268:     } else {
1.749     raeburn  5269:         foreach my $key (keys(%{$current_permissions})) {
                   5270:             if ($key =~ /\0accesscontrol$/) {
                   5271:                 if (defined($group)) {
                   5272:                     if ($key !~ m-^\Q$group\E/-) {
                   5273:                         next;
                   5274:                     }
                   5275:                 }
                   5276:                 my ($fullpath) = split(/\0/,$key);
                   5277:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5278:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5279:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5280:                     }
                   5281:                 }
                   5282:             }
                   5283:         }
                   5284:     }
                   5285:     return %access;
                   5286: }
                   5287: 
                   5288: sub modify_access_controls {
                   5289:     my ($file_name,$changes,$domain,$user)=@_;
                   5290:     my ($outcome,$deloutcome);
                   5291:     my %store_permissions;
                   5292:     my %new_values;
                   5293:     my %new_control;
                   5294:     my %translation;
                   5295:     my @deletions = ();
                   5296:     my $now = time;
                   5297:     if (exists($$changes{'activate'})) {
                   5298:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5299:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5300:             my $numnew = scalar(@newitems);
                   5301:             for (my $i=0; $i<$numnew; $i++) {
                   5302:                 my $newkey = $newitems[$i];
                   5303:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5304:                 if ($newkey =~ /^\d+:/) { 
                   5305:                     $newkey =~ s/^(\d+)/$newid/;
                   5306:                     $translation{$1} = $newid;
                   5307:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5308:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5309:                     $translation{$1} = $newid;
                   5310:                 }
1.749     raeburn  5311:                 $new_values{$file_name."\0".$newkey} = 
                   5312:                                           $$changes{'activate'}{$newitems[$i]};
                   5313:                 $new_control{$newkey} = $now;
                   5314:             }
                   5315:         }
                   5316:     }
                   5317:     my %todelete;
                   5318:     my %changed_items;
                   5319:     foreach my $action ('delete','update') {
                   5320:         if (exists($$changes{$action})) {
                   5321:             if (ref($$changes{$action}) eq 'HASH') {
                   5322:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5323:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5324:                     if ($action eq 'delete') { 
                   5325:                         $todelete{$itemnum} = 1;
                   5326:                     } else {
                   5327:                         $changed_items{$itemnum} = $key;
                   5328:                     }
                   5329:                 }
1.745     raeburn  5330:             }
                   5331:         }
1.749     raeburn  5332:     }
                   5333:     # get lock on access controls for file.
                   5334:     my $lockhash = {
                   5335:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5336:                                                        ':'.$env{'user.domain'},
                   5337:                    }; 
                   5338:     my $tries = 0;
                   5339:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5340:    
                   5341:     while (($gotlock ne 'ok') && $tries <3) {
                   5342:         $tries ++;
                   5343:         sleep 1;
                   5344:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5345:     }
                   5346:     if ($gotlock eq 'ok') {
                   5347:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5348:         my ($tmp)=keys(%curr_permissions);
                   5349:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5350:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5351:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5352:             if (ref($curr_controls) eq 'HASH') {
                   5353:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5354:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5355:                     if (defined($todelete{$itemnum})) {
                   5356:                         push(@deletions,$file_name."\0".$control_item);
                   5357:                     } else {
                   5358:                         if (defined($changed_items{$itemnum})) {
                   5359:                             $new_control{$changed_items{$itemnum}} = $now;
                   5360:                             push(@deletions,$file_name."\0".$control_item);
                   5361:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5362:                         } else {
                   5363:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5364:                         }
                   5365:                     }
1.745     raeburn  5366:                 }
                   5367:             }
                   5368:         }
1.749     raeburn  5369:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5370:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5371:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5372:         #  remove lock
                   5373:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5374:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5375:         my ($file,$group);
                   5376:         if (&is_course($domain,$user)) {
                   5377:             ($group,$file) = split(/\//,$file_name,2);
                   5378:         } else {
                   5379:             $file = $file_name;
                   5380:         }
                   5381:         my $sqlresult =
                   5382:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5383:                                     $group);
1.749     raeburn  5384:     } else {
                   5385:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5386:     }
1.749     raeburn  5387:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5388: }
                   5389: 
1.827     raeburn  5390: sub make_public_indefinitely {
                   5391:     my ($requrl) = @_;
                   5392:     my $now = time;
                   5393:     my $action = 'activate';
                   5394:     my $aclnum = 0;
                   5395:     if (&is_portfolio_url($requrl)) {
                   5396:         my (undef,$udom,$unum,$file_name,$group) =
                   5397:             &parse_portfolio_url($requrl);
                   5398:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5399:         my %access_controls = &get_access_controls($current_perms,
                   5400:                                                    $group,$file_name);
                   5401:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5402:             my ($num,$scope,$end,$start) = 
                   5403:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5404:             if ($scope eq 'public') {
                   5405:                 if ($start <= $now && $end == 0) {
                   5406:                     $action = 'none';
                   5407:                 } else {
                   5408:                     $action = 'update';
                   5409:                     $aclnum = $num;
                   5410:                 }
                   5411:                 last;
                   5412:             }
                   5413:         }
                   5414:         if ($action eq 'none') {
                   5415:              return 'ok';
                   5416:         } else {
                   5417:             my %changes;
                   5418:             my $newend = 0;
                   5419:             my $newstart = $now;
                   5420:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5421:             $changes{$action}{$newkey} = {
                   5422:                 type => 'public',
                   5423:                 time => {
                   5424:                     start => $newstart,
                   5425:                     end   => $newend,
                   5426:                 },
                   5427:             };
                   5428:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5429:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5430:             return $outcome;
                   5431:         }
                   5432:     } else {
                   5433:         return 'invalid';
                   5434:     }
                   5435: }
                   5436: 
1.745     raeburn  5437: #------------------------------------------------------Get Marked as Read Only
                   5438: 
                   5439: sub get_marked_as_readonly {
                   5440:     my ($domain,$user,$what,$group) = @_;
                   5441:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5442:     my @readonly_files;
1.629     banghart 5443:     my $cmp1=$what;
                   5444:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5445:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5446:         if (defined($group)) {
                   5447:             if ($file_name !~ m-^\Q$group\E/-) {
                   5448:                 next;
                   5449:             }
                   5450:         }
1.561     banghart 5451:         if (ref($value) eq "ARRAY"){
                   5452:             foreach my $stored_what (@{$value}) {
1.629     banghart 5453:                 my $cmp2=$stored_what;
1.759     albertel 5454:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5455:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5456:                 }
1.629     banghart 5457:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5458:                     push(@readonly_files, $file_name);
1.745     raeburn  5459:                     last;
1.563     banghart 5460:                 } elsif (!defined($what)) {
                   5461:                     push(@readonly_files, $file_name);
1.745     raeburn  5462:                     last;
1.561     banghart 5463:                 }
                   5464:             }
1.745     raeburn  5465:         }
1.561     banghart 5466:     }
                   5467:     return @readonly_files;
                   5468: }
1.577     banghart 5469: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5470: 
1.577     banghart 5471: sub get_marked_as_readonly_hash {
1.745     raeburn  5472:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5473:     my %readonly_files;
1.745     raeburn  5474:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5475:         if (defined($group)) {
                   5476:             if ($file_name !~ m-^\Q$group\E/-) {
                   5477:                 next;
                   5478:             }
                   5479:         }
1.577     banghart 5480:         if (ref($value) eq "ARRAY"){
                   5481:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5482:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5483:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5484:                         if ($lock_descriptor eq 'graded') {
                   5485:                             $readonly_files{$file_name} = 'graded';
                   5486:                         } elsif ($lock_descriptor eq 'handback') {
                   5487:                             $readonly_files{$file_name} = 'handback';
                   5488:                         } else {
                   5489:                             if (!exists($readonly_files{$file_name})) {
                   5490:                                 $readonly_files{$file_name} = 'locked';
                   5491:                             }
                   5492:                         }
1.745     raeburn  5493:                     }
1.750     banghart 5494:                 } 
1.577     banghart 5495:             }
                   5496:         } 
                   5497:     }
                   5498:     return %readonly_files;
                   5499: }
1.559     banghart 5500: # ------------------------------------------------------------ Unmark as Read Only
                   5501: 
                   5502: sub unmark_as_readonly {
1.629     banghart 5503:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5504:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5505:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5506:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5507:     my $symb_crs = $what;
                   5508:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5509:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5510:     my ($tmp)=keys(%current_permissions);
                   5511:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5512:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5513:     foreach my $file (@readonly_files) {
1.759     albertel 5514: 	my $clean_file = &declutter_portfile($file);
                   5515: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5516: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5517:         my @new_locks;
                   5518:         my @del_keys;
                   5519:         if (ref($current_locks) eq "ARRAY"){
                   5520:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5521:                 my $compare=$locker;
1.749     raeburn  5522:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5523:                     $compare=join('',@{$locker});
1.746     raeburn  5524:                     if ($compare ne $symb_crs) {
                   5525:                         push(@new_locks, $locker);
                   5526:                     }
1.563     banghart 5527:                 }
                   5528:             }
1.650     albertel 5529:             if (scalar(@new_locks) > 0) {
1.563     banghart 5530:                 $current_permissions{$file} = \@new_locks;
                   5531:             } else {
                   5532:                 push(@del_keys, $file);
1.613     albertel 5533:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5534:                 delete($current_permissions{$file});
1.563     banghart 5535:             }
                   5536:         }
1.561     banghart 5537:     }
1.613     albertel 5538:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5539:     return;
                   5540: }
1.512     banghart 5541: 
1.17      www      5542: # ------------------------------------------------------------ Directory lister
                   5543: 
                   5544: sub dirlist {
1.253     stredwic 5545:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5546: 
1.18      www      5547:     $uri=~s/^\///;
                   5548:     $uri=~s/\/$//;
1.253     stredwic 5549:     my ($udom, $uname);
                   5550:     (undef,$udom,$uname)=split(/\//,$uri);
                   5551:     if(defined($userdomain)) {
                   5552:         $udom = $userdomain;
                   5553:     }
                   5554:     if(defined($username)) {
                   5555:         $uname = $username;
                   5556:     }
                   5557: 
                   5558:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5559:     if(defined($alternateDirectoryRoot)) {
                   5560:         $dirRoot = $alternateDirectoryRoot;
                   5561:         $dirRoot =~ s/\/$//;
1.751     banghart 5562:     }
1.253     stredwic 5563: 
                   5564:     if($udom) {
                   5565:         if($uname) {
1.800     albertel 5566:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5567: 				 &homeserver($uname,$udom));
1.605     matthew  5568:             my @listing_results;
                   5569:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5570:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5571: 				  &homeserver($uname,$udom));
1.605     matthew  5572:                 @listing_results = split(/:/,$listing);
                   5573:             } else {
                   5574:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5575:             }
                   5576:             return @listing_results;
1.253     stredwic 5577:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5578:             my %allusers;
1.841     albertel 5579: 	    my %servers = &get_servers($udom,'library');
                   5580: 	    foreach my $tryserver (keys(%servers)) {
                   5581: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5582: 				     $udom, $tryserver);
                   5583: 		my @listing_results;
                   5584: 		if ($listing eq 'unknown_cmd') {
                   5585: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5586: 				      $udom, $tryserver);
                   5587: 		    @listing_results = split(/:/,$listing);
                   5588: 		} else {
                   5589: 		    @listing_results =
                   5590: 			map { &unescape($_); } split(/:/,$listing);
                   5591: 		}
                   5592: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5593: 		    $listing_results[0] ne 'empty'       &&
                   5594: 		    $listing_results[0] ne 'con_lost') {
                   5595: 		    foreach my $line (@listing_results) {
                   5596: 			my ($entry) = split(/&/,$line,2);
                   5597: 			$allusers{$entry} = 1;
                   5598: 		    }
                   5599: 		}
1.253     stredwic 5600:             }
                   5601:             my $alluserstr='';
1.800     albertel 5602:             foreach my $user (sort(keys(%allusers))) {
                   5603:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5604:             }
                   5605:             $alluserstr=~s/:$//;
                   5606:             return split(/:/,$alluserstr);
                   5607:         } else {
1.800     albertel 5608:             return ('missing user name');
1.253     stredwic 5609:         }
                   5610:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5611:         my @all_domains = sort(&all_domains());
                   5612:          foreach my $domain (@all_domains) {
                   5613:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5614:          }
                   5615:          return @all_domains;
                   5616:      } else {
1.800     albertel 5617:         return ('missing domain');
1.275     stredwic 5618:     }
                   5619: }
                   5620: 
                   5621: # --------------------------------------------- GetFileTimestamp
                   5622: # This function utilizes dirlist and returns the date stamp for
                   5623: # when it was last modified.  It will also return an error of -1
                   5624: # if an error occurs
                   5625: 
1.410     matthew  5626: ##
                   5627: ## FIXME: This subroutine assumes its caller knows something about the
                   5628: ## directory structure of the home server for the student ($root).
                   5629: ## Not a good assumption to make.  Since this is for looking up files
                   5630: ## in user directories, the full path should be constructed by lond, not
                   5631: ## whatever machine we request data from.
                   5632: ##
1.275     stredwic 5633: sub GetFileTimestamp {
                   5634:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5635:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5636:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5637:     my $subdir=$studentName.'__';
                   5638:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5639:     my $proname="$studentDomain/$subdir/$studentName";
                   5640:     $proname .= '/'.$filename;
1.375     matthew  5641:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5642:                                               $studentName, $root);
1.275     stredwic 5643:     my @stats = split('&', $fileStat);
                   5644:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5645:         # @stats contains first the filename, then the stat output
                   5646:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5647:     } else {
                   5648:         return -1;
1.253     stredwic 5649:     }
1.26      www      5650: }
                   5651: 
1.712     albertel 5652: sub stat_file {
                   5653:     my ($uri) = @_;
1.787     albertel 5654:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5655: 
1.712     albertel 5656:     my ($udom,$uname,$file,$dir);
                   5657:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5658: 	($udom,$uname,$file) =
1.811     albertel 5659: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5660: 	$file = 'userfiles/'.$file;
1.740     www      5661: 	$dir = &propath($udom,$uname);
1.712     albertel 5662:     }
                   5663:     if ($uri =~ m-^/res/-) {
                   5664: 	($udom,$uname) = 
1.807     albertel 5665: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5666: 	$file = $uri;
                   5667:     }
                   5668: 
                   5669:     if (!$udom || !$uname || !$file) {
                   5670: 	# unable to handle the uri
                   5671: 	return ();
                   5672:     }
                   5673: 
                   5674:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5675:     my @stats = split('&', $result);
1.721     banghart 5676:     
1.712     albertel 5677:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5678: 	shift(@stats); #filename is first
                   5679: 	return @stats;
                   5680:     }
                   5681:     return ();
                   5682: }
                   5683: 
1.26      www      5684: # -------------------------------------------------------- Value of a Condition
                   5685: 
1.713     albertel 5686: # gets the value of a specific preevaluated condition
                   5687: #    stored in the string  $env{user.state.<cid>}
                   5688: # or looks up a condition reference in the bighash and if if hasn't
                   5689: # already been evaluated recurses into docondval to get the value of
                   5690: # the condition, then memoizing it to 
                   5691: #   $env{user.state.<cid>.<condition>}
1.40      www      5692: sub directcondval {
                   5693:     my $number=shift;
1.620     albertel 5694:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5695: 	&Apache::lonuserstate::evalstate();
                   5696:     }
1.713     albertel 5697:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5698: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5699:     } elsif ($number =~ /^_/) {
                   5700: 	my $sub_condition;
                   5701: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5702: 		&GDBM_READER(),0640)) {
                   5703: 	    $sub_condition=$bighash{'conditions'.$number};
                   5704: 	    untie(%bighash);
                   5705: 	}
                   5706: 	my $value = &docondval($sub_condition);
                   5707: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5708: 	return $value;
                   5709:     }
1.620     albertel 5710:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5711:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5712:     } else {
                   5713:        return 2;
                   5714:     }
                   5715: }
                   5716: 
1.713     albertel 5717: # get the collection of conditions for this resource
1.26      www      5718: sub condval {
                   5719:     my $condidx=shift;
1.54      www      5720:     my $allpathcond='';
1.713     albertel 5721:     foreach my $cond (split(/\|/,$condidx)) {
                   5722: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5723: 	    $allpathcond.=
                   5724: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5725: 	}
1.191     harris41 5726:     }
1.54      www      5727:     $allpathcond=~s/\|$//;
1.713     albertel 5728:     return &docondval($allpathcond);
                   5729: }
                   5730: 
                   5731: #evaluates an expression of conditions
                   5732: sub docondval {
                   5733:     my ($allpathcond) = @_;
                   5734:     my $result=0;
                   5735:     if ($env{'request.course.id'}
                   5736: 	&& defined($allpathcond)) {
                   5737: 	my $operand='|';
                   5738: 	my @stack;
                   5739: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5740: 	    if ($chunk eq '(') {
                   5741: 		push @stack,($operand,$result);
                   5742: 	    } elsif ($chunk eq ')') {
                   5743: 		my $before=pop @stack;
                   5744: 		if (pop @stack eq '&') {
                   5745: 		    $result=$result>$before?$before:$result;
                   5746: 		} else {
                   5747: 		    $result=$result>$before?$result:$before;
                   5748: 		}
                   5749: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5750: 		$operand=$chunk;
                   5751: 	    } else {
                   5752: 		my $new=directcondval($chunk);
                   5753: 		if ($operand eq '&') {
                   5754: 		    $result=$result>$new?$new:$result;
                   5755: 		} else {
                   5756: 		    $result=$result>$new?$result:$new;
                   5757: 		}
                   5758: 	    }
                   5759: 	}
1.26      www      5760:     }
                   5761:     return $result;
1.421     albertel 5762: }
                   5763: 
                   5764: # ---------------------------------------------------- Devalidate courseresdata
                   5765: 
                   5766: sub devalidatecourseresdata {
                   5767:     my ($coursenum,$coursedomain)=@_;
                   5768:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5769:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5770: }
                   5771: 
1.763     www      5772: 
1.200     www      5773: # --------------------------------------------------- Course Resourcedata Query
                   5774: 
1.624     albertel 5775: sub get_courseresdata {
                   5776:     my ($coursenum,$coursedomain)=@_;
1.200     www      5777:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5778:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5779:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5780:     my %dumpreply;
1.417     albertel 5781:     unless (defined($cached)) {
1.624     albertel 5782: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5783: 	$result=\%dumpreply;
1.251     albertel 5784: 	my ($tmp) = keys(%dumpreply);
                   5785: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5786: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5787: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5788: 	    return $tmp;
1.416     albertel 5789: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5790: 	    $result=undef;
1.599     albertel 5791: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5792: 	}
                   5793:     }
1.624     albertel 5794:     return $result;
                   5795: }
                   5796: 
1.633     albertel 5797: sub devalidateuserresdata {
                   5798:     my ($uname,$udom)=@_;
                   5799:     my $hashid="$udom:$uname";
                   5800:     &devalidate_cache_new('userres',$hashid);
                   5801: }
                   5802: 
1.624     albertel 5803: sub get_userresdata {
                   5804:     my ($uname,$udom)=@_;
                   5805:     #most student don\'t have any data set, check if there is some data
                   5806:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5807: 
                   5808:     my $hashid="$udom:$uname";
                   5809:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5810:     if (!defined($cached)) {
                   5811: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5812: 	$result=\%resourcedata;
                   5813: 	&do_cache_new('userres',$hashid,$result,600);
                   5814:     }
                   5815:     my ($tmp)=keys(%$result);
                   5816:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5817: 	return $result;
                   5818:     }
                   5819:     #error 2 occurs when the .db doesn't exist
                   5820:     if ($tmp!~/error: 2 /) {
1.672     albertel 5821: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5822: 		 " Trying to get resource data for ".
                   5823: 		 $uname." at ".$udom.": ".
                   5824: 		 $tmp."</font>");
                   5825:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5826: 	#&EXT_cache_set($udom,$uname);
                   5827: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5828: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5829:     }
                   5830:     return $tmp;
                   5831: }
                   5832: 
                   5833: sub resdata {
                   5834:     my ($name,$domain,$type,@which)=@_;
                   5835:     my $result;
                   5836:     if ($type eq 'course') {
                   5837: 	$result=&get_courseresdata($name,$domain);
                   5838:     } elsif ($type eq 'user') {
                   5839: 	$result=&get_userresdata($name,$domain);
                   5840:     }
                   5841:     if (!ref($result)) { return $result; }    
1.251     albertel 5842:     foreach my $item (@which) {
1.417     albertel 5843: 	if (defined($result->{$item})) {
                   5844: 	    return $result->{$item};
1.251     albertel 5845: 	}
1.250     albertel 5846:     }
1.291     albertel 5847:     return undef;
1.200     www      5848: }
                   5849: 
1.379     matthew  5850: #
                   5851: # EXT resource caching routines
                   5852: #
                   5853: 
                   5854: sub clear_EXT_cache_status {
1.383     albertel 5855:     &delenv('cache.EXT.');
1.379     matthew  5856: }
                   5857: 
                   5858: sub EXT_cache_status {
                   5859:     my ($target_domain,$target_user) = @_;
1.383     albertel 5860:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5861:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5862:         # We know already the user has no data
                   5863:         return 1;
                   5864:     } else {
                   5865:         return 0;
                   5866:     }
                   5867: }
                   5868: 
                   5869: sub EXT_cache_set {
                   5870:     my ($target_domain,$target_user) = @_;
1.383     albertel 5871:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5872:     #&appenv($cachename => time);
1.379     matthew  5873: }
                   5874: 
1.28      www      5875: # --------------------------------------------------------- Value of a Variable
1.58      www      5876: sub EXT {
1.715     albertel 5877: 
1.395     albertel 5878:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5879:     unless ($varname) { return ''; }
1.218     albertel 5880:     #get real user name/domain, courseid and symb
                   5881:     my $courseid;
1.359     albertel 5882:     my $publicuser;
1.427     www      5883:     if ($symbparm) {
                   5884: 	$symbparm=&get_symb_from_alias($symbparm);
                   5885:     }
1.218     albertel 5886:     if (!($uname && $udom)) {
1.790     albertel 5887:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5888:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5889:     } else {
1.620     albertel 5890: 	$courseid=$env{'request.course.id'};
1.218     albertel 5891:     }
1.48      www      5892:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5893:     my $rest;
1.320     albertel 5894:     if (defined($therest[0])) {
1.48      www      5895:        $rest=join('.',@therest);
                   5896:     } else {
                   5897:        $rest='';
                   5898:     }
1.320     albertel 5899: 
1.57      www      5900:     my $qualifierrest=$qualifier;
                   5901:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5902:     my $spacequalifierrest=$space;
                   5903:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5904:     if ($realm eq 'user') {
1.48      www      5905: # --------------------------------------------------------------- user.resource
                   5906: 	if ($space eq 'resource') {
1.651     albertel 5907: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5908: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5909: 		 &&
1.744     albertel 5910: 		 ($symbparm eq &symbread()) ) {	
                   5911: 		# if we are in the middle of processing the resource the
                   5912: 		# get the value we are planning on committing
                   5913:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5914:                     return $Apache::lonhomework::results{$qualifierrest};
                   5915:                 } else {
                   5916:                     return $Apache::lonhomework::history{$qualifierrest};
                   5917:                 }
1.335     albertel 5918: 	    } else {
1.359     albertel 5919: 		my %restored;
1.620     albertel 5920: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5921: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5922: 		} else {
                   5923: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5924: 		}
1.335     albertel 5925: 		return $restored{$qualifierrest};
                   5926: 	    }
1.48      www      5927: # ----------------------------------------------------------------- user.access
                   5928:         } elsif ($space eq 'access') {
1.218     albertel 5929: 	    # FIXME - not supporting calls for a specific user
1.48      www      5930:             return &allowed($qualifier,$rest);
                   5931: # ------------------------------------------ user.preferences, user.environment
                   5932:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5933: 	    if (($uname eq $env{'user.name'}) &&
                   5934: 		($udom eq $env{'user.domain'})) {
                   5935: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5936: 	    } else {
1.359     albertel 5937: 		my %returnhash;
                   5938: 		if (!$publicuser) {
                   5939: 		    %returnhash=&userenvironment($udom,$uname,
                   5940: 						 $qualifierrest);
                   5941: 		}
1.218     albertel 5942: 		return $returnhash{$qualifierrest};
                   5943: 	    }
1.48      www      5944: # ----------------------------------------------------------------- user.course
                   5945:         } elsif ($space eq 'course') {
1.218     albertel 5946: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5947:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5948: # ------------------------------------------------------------------- user.role
                   5949:         } elsif ($space eq 'role') {
1.218     albertel 5950: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5951:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5952:             if ($qualifier eq 'value') {
                   5953: 		return $role;
                   5954:             } elsif ($qualifier eq 'extent') {
                   5955:                 return $where;
                   5956:             }
                   5957: # ----------------------------------------------------------------- user.domain
                   5958:         } elsif ($space eq 'domain') {
1.218     albertel 5959:             return $udom;
1.48      www      5960: # ------------------------------------------------------------------- user.name
                   5961:         } elsif ($space eq 'name') {
1.218     albertel 5962:             return $uname;
1.48      www      5963: # ---------------------------------------------------- Any other user namespace
1.29      www      5964:         } else {
1.359     albertel 5965: 	    my %reply;
                   5966: 	    if (!$publicuser) {
                   5967: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5968: 	    }
                   5969: 	    return $reply{$qualifierrest};
1.48      www      5970:         }
1.236     www      5971:     } elsif ($realm eq 'query') {
                   5972: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5973:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5974: 						[$spacequalifierrest]);
1.620     albertel 5975: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5976:    } elsif ($realm eq 'request') {
1.48      www      5977: # ------------------------------------------------------------- request.browser
                   5978:         if ($space eq 'browser') {
1.430     www      5979: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5980: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5981: 		    return 1;
                   5982: 		} else {
                   5983: 		    return 0;
                   5984: 		}
                   5985: 	    } else {
1.620     albertel 5986: 		return $env{'browser.'.$qualifier};
1.430     www      5987: 	    }
1.57      www      5988: # ------------------------------------------------------------ request.filename
                   5989:         } else {
1.620     albertel 5990:             return $env{'request.'.$spacequalifierrest};
1.29      www      5991:         }
1.28      www      5992:     } elsif ($realm eq 'course') {
1.48      www      5993: # ---------------------------------------------------------- course.description
1.620     albertel 5994:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5995:     } elsif ($realm eq 'resource') {
1.165     www      5996: 
1.620     albertel 5997: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5998: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5999: 	}
1.693     albertel 6000: 
                   6001: 	if ($space eq 'title') {
                   6002: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6003: 	    return &gettitle($symbparm);
                   6004: 	}
                   6005: 	
                   6006: 	if ($space eq 'map') {
                   6007: 	    my ($map) = &decode_symb($symbparm);
                   6008: 	    return &symbread($map);
                   6009: 	}
                   6010: 
                   6011: 	my ($section, $group, @groups);
1.593     albertel 6012: 	my ($courselevelm,$courselevel);
1.539     albertel 6013: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6014: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6015: 
1.218     albertel 6016: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6017: 
1.60      www      6018: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6019: 	    my $symbp=$symbparm;
1.735     albertel 6020: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6021: 
                   6022: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6023: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6024: 
1.620     albertel 6025: 	    if (($env{'user.name'} eq $uname) &&
                   6026: 		($env{'user.domain'} eq $udom)) {
                   6027: 		$section=$env{'request.course.sec'};
1.733     raeburn  6028:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6029:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6030: 	    } else {
1.539     albertel 6031: 		if (! defined($usection)) {
1.551     albertel 6032: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6033: 		} else {
                   6034: 		    $section = $usection;
                   6035: 		}
1.733     raeburn  6036:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6037: 	    }
                   6038: 
                   6039: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6040: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6041: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6042: 
1.593     albertel 6043: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6044: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6045: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6046: 
1.60      www      6047: # ----------------------------------------------------------- first, check user
1.624     albertel 6048: 
                   6049: 	    my $userreply=&resdata($uname,$udom,'user',
                   6050: 				       ($courselevelr,$courselevelm,
                   6051: 					$courselevel));
                   6052: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6053: 
1.594     albertel 6054: # ------------------------------------------------ second, check some of course
1.684     raeburn  6055:             my $coursereply;
1.691     raeburn  6056:             if (@groups > 0) {
                   6057:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6058:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6059:                 if (defined($coursereply)) { return $coursereply; }
                   6060:             }
1.96      www      6061: 
1.684     raeburn  6062: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6063: 				     $env{'course.'.$courseid.'.domain'},
                   6064: 				     'course',
                   6065: 				     ($seclevelr,$seclevelm,$seclevel,
                   6066: 				      $courselevelr));
1.287     albertel 6067: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6068: 
1.60      www      6069: # ------------------------------------------------------ third, check map parms
1.218     albertel 6070: 	    my %parmhash=();
                   6071: 	    my $thisparm='';
                   6072: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6073: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6074: 		    &GDBM_READER(),0640)) {
1.218     albertel 6075: 		$thisparm=$parmhash{$symbparm};
                   6076: 		untie(%parmhash);
                   6077: 	    }
                   6078: 	    if ($thisparm) { return $thisparm; }
                   6079: 	}
1.594     albertel 6080: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6081: 
1.218     albertel 6082: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6083: 	my $filename;
                   6084: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6085: 	if ($symbparm) {
1.409     www      6086: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6087: 	} else {
1.620     albertel 6088: 	    $filename=$env{'request.filename'};
1.282     albertel 6089: 	}
                   6090: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6091: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6092: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6093: 	if (defined($metadata)) { return $metadata; }
1.142     www      6094: 
1.594     albertel 6095: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6096: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6097: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6098: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6099: 				     $env{'course.'.$courseid.'.domain'},
                   6100: 				     'course',
                   6101: 				     ($courselevelm,$courselevel));
1.593     albertel 6102: 	    if (defined($coursereply)) { return $coursereply; }
                   6103: 	}
1.145     www      6104: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6105: 	unless ($space eq '0') {
1.336     albertel 6106: 	    my @parts=split(/_/,$space);
                   6107: 	    my $id=pop(@parts);
                   6108: 	    my $part=join('_',@parts);
                   6109: 	    if ($part eq '') { $part='0'; }
                   6110: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6111: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6112: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6113: 	}
1.395     albertel 6114: 	if ($recurse) { return undef; }
                   6115: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6116: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6117: 
1.48      www      6118: # ---------------------------------------------------- Any other user namespace
                   6119:     } elsif ($realm eq 'environment') {
                   6120: # ----------------------------------------------------------------- environment
1.620     albertel 6121: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6122: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6123: 	} else {
1.770     albertel 6124: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6125: 		return '';
                   6126: 	    }
1.219     albertel 6127: 	    my %returnhash=&userenvironment($udom,$uname,
                   6128: 					    $spacequalifierrest);
                   6129: 	    return $returnhash{$spacequalifierrest};
                   6130: 	}
1.28      www      6131:     } elsif ($realm eq 'system') {
1.48      www      6132: # ----------------------------------------------------------------- system.time
                   6133: 	if ($space eq 'time') {
                   6134: 	    return time;
                   6135:         }
1.696     albertel 6136:     } elsif ($realm eq 'server') {
                   6137: # ----------------------------------------------------------------- system.time
                   6138: 	if ($space eq 'name') {
                   6139: 	    return $ENV{'SERVER_NAME'};
                   6140:         }
1.28      www      6141:     }
1.48      www      6142:     return '';
1.61      www      6143: }
                   6144: 
1.691     raeburn  6145: sub check_group_parms {
                   6146:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6147:     my @groupitems = ();
                   6148:     my $resultitem;
                   6149:     my @levels = ($symbparm,$mapparm,$what);
                   6150:     foreach my $group (@{$groups}) {
                   6151:         foreach my $level (@levels) {
                   6152:              my $item = $courseid.'.['.$group.'].'.$level;
                   6153:              push(@groupitems,$item);
                   6154:         }
                   6155:     }
                   6156:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6157:                             $env{'course.'.$courseid.'.domain'},
                   6158:                                      'course',@groupitems);
                   6159:     return $coursereply;
                   6160: }
                   6161: 
                   6162: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6163:     my ($courseid,@groups) = @_;
                   6164:     @groups = sort(@groups);
1.691     raeburn  6165:     return @groups;
                   6166: }
                   6167: 
1.395     albertel 6168: sub packages_tab_default {
                   6169:     my ($uri,$varname)=@_;
                   6170:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6171: 
                   6172:     my (@extension,@specifics,$do_default);
                   6173:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6174: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6175: 	if ($pack_type eq 'default') {
                   6176: 	    $do_default=1;
                   6177: 	} elsif ($pack_type eq 'extension') {
                   6178: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.848   ! albertel 6179: 	} elsif ($pack_part eq $part) {
        !          6180: 	    # only look at packages defaults for packages that this id is
1.738     albertel 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: {
1.846     albertel 7570:     my %domain;
                   7571: 
1.448     albertel 7572:     my $fh;
                   7573:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7574: 	while (my $line = <$fh>) {
1.846     albertel 7575: 	    next if ($line =~ /^(\#|\s*$ )/);
1.403     www      7576: 
1.846     albertel 7577: 	    chomp($line);
                   7578: 	    my ($name,@elements) =  split(/:/,$line,9);
                   7579: 	    my %this_domain;
                   7580: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7581: 			       'lang_def', 'city', 'longi', 'lati',
                   7582: 			       'primary') {
                   7583: 		$this_domain{$field} = shift(@elements);
                   7584: 	    }
                   7585: 	    $domain{$name} = \%this_domain;
1.327     albertel 7586: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7587: 	}
1.327     albertel 7588:     }
1.448     albertel 7589:     close ($fh);
1.846     albertel 7590: 
                   7591:     sub domain {
                   7592: 	my ($name,$what) = @_;
                   7593: 	return if ( !exists($domain{$name}) );
                   7594: 
                   7595: 	if (!$what) {
                   7596: 	    return $domain{$name}{'description'};
                   7597: 	}
                   7598: 	return $domain{$name}{$what};
                   7599:     }
1.327     albertel 7600: }
                   7601: 
                   7602: 
1.1       albertel 7603: # ------------------------------------------------------------- Read hosts file
                   7604: {
1.838     albertel 7605:     my %hostname;
1.844     albertel 7606:     my %hostdom;
1.845     albertel 7607:     my %libserv;
1.448     albertel 7608:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7609: 
                   7610:     while (my $configline=<$config>) {
1.303     matthew  7611:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7612:        chomp($configline);
1.595     albertel 7613:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7614:        $name=~s/\s//g;
1.595     albertel 7615:        if ($id && $domain && $role && $name) {
1.252     albertel 7616: 	 $hostname{$id}=$name;
                   7617: 	 $hostdom{$id}=$domain;
                   7618: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7619:        }
1.1       albertel 7620:     }
1.448     albertel 7621:     close($config);
1.619     albertel 7622:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7623:     #&get_iphost();
1.838     albertel 7624: 
                   7625:     sub hostname {
                   7626: 	my ($lonid) = @_;
                   7627: 	return $hostname{$lonid};
                   7628:     }
1.845     albertel 7629: 
1.838     albertel 7630:     sub all_hostnames {
                   7631: 	return %hostname;
                   7632:     }
1.845     albertel 7633: 
                   7634:     sub is_library {
                   7635: 	return exists($libserv{$_[0]});
                   7636:     }
                   7637: 
                   7638:     sub all_library {
                   7639: 	return %libserv;
                   7640:     }
                   7641: 
1.841     albertel 7642:     sub get_servers {
                   7643: 	my ($domain,$type) = @_;
                   7644: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7645: 	                                          : %hostname;
                   7646: 	my %result;
1.842     albertel 7647: 	if (ref($domain) eq 'ARRAY') {
                   7648: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7649: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7650: 		    $result{$host} = $hostname;
                   7651: 		}
                   7652: 	    }
                   7653: 	} else {
                   7654: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7655: 		if ($hostdom{$host} eq $domain) {
                   7656: 		    $result{$host} = $hostname;
                   7657: 		}
1.841     albertel 7658: 	    }
                   7659: 	}
                   7660: 	return %result;
                   7661:     }
1.845     albertel 7662: 
1.844     albertel 7663:     sub host_domain {
                   7664: 	my ($lonid) = @_;
                   7665: 	return $hostdom{$lonid};
                   7666:     }
                   7667: 
1.841     albertel 7668:     sub all_domains {
                   7669: 	my %seen;
                   7670: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7671: 	return @uniq;
                   7672:     }
1.1       albertel 7673: }
                   7674: 
1.847     albertel 7675: { 
                   7676:     my %iphost;
                   7677:     sub get_hosts_from_ip {
                   7678: 	my ($ip) = @_;
                   7679: 	my %iphosts = &get_iphost();
                   7680: 	if (ref($iphosts{$ip})) {
                   7681: 	    return @{$iphosts{$ip}};
                   7682: 	}
                   7683: 	return;
1.839     albertel 7684:     }
1.847     albertel 7685:     
                   7686:     sub get_iphost {
                   7687: 	if (%iphost) { return %iphost; }
                   7688: 	my %name_to_ip;
                   7689: 	my %hostname = &all_hostnames();
                   7690: 	foreach my $id (keys(%hostname)) {
                   7691: 	    my $name=$hostname{$id};
                   7692: 	    my $ip;
                   7693: 	    if (!exists($name_to_ip{$name})) {
                   7694: 		$ip = gethostbyname($name);
                   7695: 		if (!$ip || length($ip) ne 4) {
                   7696: 		    &logthis("Skipping host $id name $name no IP found");
                   7697: 		    next;
                   7698: 		}
                   7699: 		$ip=inet_ntoa($ip);
                   7700: 		$name_to_ip{$name} = $ip;
                   7701: 	    } else {
                   7702: 		$ip = $name_to_ip{$name};
1.653     albertel 7703: 	    }
1.847     albertel 7704: 	    push(@{$iphost{$ip}},$id);
1.598     albertel 7705: 	}
1.847     albertel 7706: 	return %iphost;
1.598     albertel 7707:     }
                   7708: }
                   7709: 
1.1       albertel 7710: # ------------------------------------------------------ Read spare server file
                   7711: {
1.448     albertel 7712:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7713: 
                   7714:     while (my $configline=<$config>) {
                   7715:        chomp($configline);
1.284     matthew  7716:        if ($configline) {
1.784     albertel 7717: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7718: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7719: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7720:        }
                   7721:     }
1.448     albertel 7722:     close($config);
1.1       albertel 7723: }
1.11      www      7724: # ------------------------------------------------------------ Read permissions
                   7725: {
1.448     albertel 7726:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7727: 
                   7728:     while (my $configline=<$config>) {
1.448     albertel 7729: 	chomp($configline);
                   7730: 	if ($configline) {
                   7731: 	    my ($role,$perm)=split(/ /,$configline);
                   7732: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7733: 	}
1.11      www      7734:     }
1.448     albertel 7735:     close($config);
1.11      www      7736: }
                   7737: 
                   7738: # -------------------------------------------- Read plain texts for permissions
                   7739: {
1.448     albertel 7740:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7741: 
                   7742:     while (my $configline=<$config>) {
1.448     albertel 7743: 	chomp($configline);
                   7744: 	if ($configline) {
1.742     raeburn  7745: 	    my ($short,@plain)=split(/:/,$configline);
                   7746:             %{$prp{$short}} = ();
                   7747: 	    if (@plain > 0) {
                   7748:                 $prp{$short}{'std'} = $plain[0];
                   7749:                 for (my $i=1; $i<@plain; $i++) {
                   7750:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7751:                 }
                   7752:             }
1.448     albertel 7753: 	}
1.135     www      7754:     }
1.448     albertel 7755:     close($config);
1.135     www      7756: }
                   7757: 
                   7758: # ---------------------------------------------------------- Read package table
                   7759: {
1.448     albertel 7760:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7761: 
                   7762:     while (my $configline=<$config>) {
1.483     albertel 7763: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7764: 	chomp($configline);
                   7765: 	my ($short,$plain)=split(/:/,$configline);
                   7766: 	my ($pack,$name)=split(/\&/,$short);
                   7767: 	if ($plain ne '') {
                   7768: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7769: 	    $packagetab{$short}=$plain; 
                   7770: 	}
1.11      www      7771:     }
1.448     albertel 7772:     close($config);
1.329     matthew  7773: }
                   7774: 
                   7775: # ------------- set up temporary directory
                   7776: {
                   7777:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7778: 
1.11      www      7779: }
                   7780: 
1.794     albertel 7781: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7782: 				'compress_threshold'=> 20_000,
                   7783:  			        });
1.185     www      7784: 
1.281     www      7785: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7786: $dumpcount=0;
1.22      www      7787: 
1.163     harris41 7788: &logtouch();
1.672     albertel 7789: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7790: $readit=1;
1.564     albertel 7791:     {
                   7792: 	use integer;
                   7793: 	my $test=(2**32)+1;
1.568     albertel 7794: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7795: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7796:     }
1.195     www      7797: }
1.1       albertel 7798: }
1.179     www      7799: 
1.1       albertel 7800: 1;
1.191     harris41 7801: __END__
                   7802: 
1.243     albertel 7803: =pod
                   7804: 
1.191     harris41 7805: =head1 NAME
                   7806: 
1.243     albertel 7807: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7808: 
                   7809: =head1 SYNOPSIS
                   7810: 
1.243     albertel 7811: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7812: 
                   7813:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7814: 
1.243     albertel 7815: Common parameters:
                   7816: 
                   7817: =over 4
                   7818: 
                   7819: =item *
                   7820: 
                   7821: $uname : an internal username (if $cname expecting a course Id specifically)
                   7822: 
                   7823: =item *
                   7824: 
                   7825: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7826: 
                   7827: =item *
                   7828: 
                   7829: $symb : a resource instance identifier
                   7830: 
                   7831: =item *
                   7832: 
                   7833: $namespace : the name of a .db file that contains the data needed or
                   7834: being set.
                   7835: 
                   7836: =back
                   7837: 
1.394     bowersj2 7838: =head1 OVERVIEW
1.191     harris41 7839: 
1.394     bowersj2 7840: lonnet provides subroutines which interact with the
                   7841: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7842: about classes, users, and resources.
1.243     albertel 7843: 
                   7844: For many of these objects you can also use this to store data about
                   7845: them or modify them in various ways.
1.191     harris41 7846: 
1.394     bowersj2 7847: =head2 Symbs
1.191     harris41 7848: 
1.394     bowersj2 7849: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7850: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7851: map, the resource number of the resource in the map, and the URL of
                   7852: the resource itself. The latter is somewhat redundant, but might help
                   7853: if maps change.
                   7854: 
                   7855: An example is
                   7856: 
                   7857:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7858: 
                   7859: The respective map entry is
                   7860: 
                   7861:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7862:   title="Problem 2">
                   7863:  </resource>
                   7864: 
                   7865: Symbs are used by the random number generator, as well as to store and
                   7866: restore data specific to a certain instance of for example a problem.
                   7867: 
                   7868: =head2 Storing And Retrieving Data
                   7869: 
                   7870: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7871: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7872: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7873: is is the non-critical message twin of cstore. These functions are for
                   7874: handlers to store a perl hash to a user's permanent data space in an
                   7875: easy manner, and to retrieve it again on another call. It is expected
                   7876: that a handler would use this once at the beginning to retrieve data,
                   7877: and then again once at the end to send only the new data back.
                   7878: 
                   7879: The data is stored in the user's data directory on the user's
                   7880: homeserver under the ID of the course.
                   7881: 
                   7882: The hash that is returned by restore will have all of the previous
                   7883: value for all of the elements of the hash.
                   7884: 
                   7885: Example:
                   7886: 
                   7887:  #creating a hash
                   7888:  my %hash;
                   7889:  $hash{'foo'}='bar';
                   7890: 
                   7891:  #storing it
                   7892:  &Apache::lonnet::cstore(\%hash);
                   7893: 
                   7894:  #changing a value
                   7895:  $hash{'foo'}='notbar';
                   7896: 
                   7897:  #adding a new value
                   7898:  $hash{'bar'}='foo';
                   7899:  &Apache::lonnet::cstore(\%hash);
                   7900: 
                   7901:  #retrieving the hash
                   7902:  my %history=&Apache::lonnet::restore();
                   7903: 
                   7904:  #print the hash
                   7905:  foreach my $key (sort(keys(%history))) {
                   7906:    print("\%history{$key} = $history{$key}");
                   7907:  }
                   7908: 
                   7909: Will print out:
1.191     harris41 7910: 
1.394     bowersj2 7911:  %history{1:foo} = bar
                   7912:  %history{1:keys} = foo:timestamp
                   7913:  %history{1:timestamp} = 990455579
                   7914:  %history{2:bar} = foo
                   7915:  %history{2:foo} = notbar
                   7916:  %history{2:keys} = foo:bar:timestamp
                   7917:  %history{2:timestamp} = 990455580
                   7918:  %history{bar} = foo
                   7919:  %history{foo} = notbar
                   7920:  %history{timestamp} = 990455580
                   7921:  %history{version} = 2
                   7922: 
                   7923: Note that the special hash entries C<keys>, C<version> and
                   7924: C<timestamp> were added to the hash. C<version> will be equal to the
                   7925: total number of versions of the data that have been stored. The
                   7926: C<timestamp> attribute will be the UNIX time the hash was
                   7927: stored. C<keys> is available in every historical section to list which
                   7928: keys were added or changed at a specific historical revision of a
                   7929: hash.
                   7930: 
                   7931: B<Warning>: do not store the hash that restore returns directly. This
                   7932: will cause a mess since it will restore the historical keys as if the
                   7933: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7934: 
1.394     bowersj2 7935: Calling convention:
1.191     harris41 7936: 
1.394     bowersj2 7937:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7938:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7939: 
1.394     bowersj2 7940: For more detailed information, see lonnet specific documentation.
1.191     harris41 7941: 
1.394     bowersj2 7942: =head1 RETURN MESSAGES
1.191     harris41 7943: 
1.394     bowersj2 7944: =over 4
1.191     harris41 7945: 
1.394     bowersj2 7946: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7947: 
1.394     bowersj2 7948: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7949: when the connection is brought back up
1.191     harris41 7950: 
1.394     bowersj2 7951: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7952: for later delivery
1.191     harris41 7953: 
1.394     bowersj2 7954: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7955: 
1.394     bowersj2 7956: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7957: that was requested
1.191     harris41 7958: 
1.243     albertel 7959: =back
1.191     harris41 7960: 
1.243     albertel 7961: =head1 PUBLIC SUBROUTINES
1.191     harris41 7962: 
1.243     albertel 7963: =head2 Session Environment Functions
1.191     harris41 7964: 
1.243     albertel 7965: =over 4
1.191     harris41 7966: 
1.394     bowersj2 7967: =item * 
                   7968: X<appenv()>
                   7969: B<appenv(%hash)>: the value of %hash is written to
                   7970: the user envirnoment file, and will be restored for each access this
1.620     albertel 7971: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7972: process
1.191     harris41 7973: 
                   7974: =item *
1.394     bowersj2 7975: X<delenv()>
                   7976: B<delenv($regexp)>: removes all items from the session
                   7977: environment file that matches the regular expression in $regexp. The
1.620     albertel 7978: values are also delted from the current processes %env.
1.191     harris41 7979: 
1.795     albertel 7980: =item * get_env_multiple($name) 
                   7981: 
                   7982: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7983: values may be defined and end up as an array ref.
                   7984: 
                   7985: returns an array of values
                   7986: 
1.243     albertel 7987: =back
                   7988: 
                   7989: =head2 User Information
1.191     harris41 7990: 
1.243     albertel 7991: =over 4
1.191     harris41 7992: 
                   7993: =item *
1.394     bowersj2 7994: X<queryauthenticate()>
                   7995: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7996: authentication scheme
                   7997: 
                   7998: =item *
1.394     bowersj2 7999: X<authenticate()>
                   8000: B<authenticate($uname,$upass,$udom)>: try to
                   8001: authenticate user from domain's lib servers (first use the current
                   8002: one). C<$upass> should be the users password.
1.191     harris41 8003: 
                   8004: =item *
1.394     bowersj2 8005: X<homeserver()>
                   8006: B<homeserver($uname,$udom)>: find the server which has
                   8007: the user's directory and files (there must be only one), this caches
                   8008: the answer, and also caches if there is a borken connection.
1.191     harris41 8009: 
                   8010: =item *
1.394     bowersj2 8011: X<idget()>
                   8012: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8013: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8014: username, and only 1 username per ID in a specific domain) (returns
                   8015: hash: id=>name,id=>name)
1.191     harris41 8016: 
                   8017: =item *
1.394     bowersj2 8018: X<idrget()>
                   8019: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8020: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8021: 
                   8022: =item *
1.394     bowersj2 8023: X<idput()>
                   8024: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8025: 
                   8026: =item *
1.394     bowersj2 8027: X<rolesinit()>
                   8028: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8029: 
                   8030: =item *
1.551     albertel 8031: X<getsection()>
                   8032: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8033: course $cname, return section name/number or '' for "not in course"
                   8034: and '-1' for "no section"
                   8035: 
                   8036: =item *
1.394     bowersj2 8037: X<userenvironment()>
                   8038: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8039: passed in @what from the requested user's environment, returns a hash
                   8040: 
                   8041: =back
                   8042: 
                   8043: =head2 User Roles
                   8044: 
                   8045: =over 4
                   8046: 
                   8047: =item *
                   8048: 
1.810     raeburn  8049: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8050:  F: full access
                   8051:  U,I,K: authentication modes (cxx only)
                   8052:  '': forbidden
                   8053:  1: user needs to choose course
                   8054:  2: browse allowed
1.766     albertel 8055:  A: passphrase authentication needed
1.243     albertel 8056: 
                   8057: =item *
                   8058: 
                   8059: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8060: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8061: and course level
                   8062: 
                   8063: =item *
                   8064: 
                   8065: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8066: explanation of a user role term
                   8067: 
1.832     raeburn  8068: =item *
                   8069: 
1.834     albertel 8070: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
                   8071: optional.  Returns a hash of a user's roles, with keys set to
                   8072: colon-sparated $uname,$udom,and $role, and value set to
                   8073: colon-separated start and end times for the role. If no username and
                   8074: domain are specified, will default to current user/domain. Types,
                   8075: roles, and roledoms are references to arrays, of role statuses
                   8076: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
                   8077: of the roles which can be used to restrict the list if roles
                   8078: reported. If no array ref is provided for types, will default to
                   8079: return only active roles.
                   8080: 
1.243     albertel 8081: =back
                   8082: 
                   8083: =head2 User Modification
                   8084: 
                   8085: =over 4
                   8086: 
                   8087: =item *
                   8088: 
                   8089: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8090: user for the level given by URL.  Optional start and end dates (leave empty
                   8091: string or zero for "no date")
1.191     harris41 8092: 
                   8093: =item *
                   8094: 
1.243     albertel 8095: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8096: change a users, password, possible return values are: ok,
                   8097: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8098: refused
1.191     harris41 8099: 
                   8100: =item *
                   8101: 
1.243     albertel 8102: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8103: 
                   8104: =item *
                   8105: 
1.243     albertel 8106: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8107: modify user
1.191     harris41 8108: 
                   8109: =item *
                   8110: 
1.286     matthew  8111: modifystudent
                   8112: 
                   8113: modify a students enrollment and identification information.
                   8114: The course id is resolved based on the current users environment.  
                   8115: This means the envoking user must be a course coordinator or otherwise
                   8116: associated with a course.
                   8117: 
1.297     matthew  8118: This call is essentially a wrapper for lonnet::modifyuser and
                   8119: lonnet::modify_student_enrollment
1.286     matthew  8120: 
                   8121: Inputs: 
                   8122: 
                   8123: =over 4
                   8124: 
                   8125: =item B<$udom> Students loncapa domain
                   8126: 
                   8127: =item B<$uname> Students loncapa login name
                   8128: 
                   8129: =item B<$uid> Students id/student number
                   8130: 
                   8131: =item B<$umode> Students authentication mode
                   8132: 
                   8133: =item B<$upass> Students password
                   8134: 
                   8135: =item B<$first> Students first name
                   8136: 
                   8137: =item B<$middle> Students middle name
                   8138: 
                   8139: =item B<$last> Students last name
                   8140: 
                   8141: =item B<$gene> Students generation
                   8142: 
                   8143: =item B<$usec> Students section in course
                   8144: 
                   8145: =item B<$end> Unix time of the roles expiration
                   8146: 
                   8147: =item B<$start> Unix time of the roles start date
                   8148: 
                   8149: =item B<$forceid> If defined, allow $uid to be changed
                   8150: 
                   8151: =item B<$desiredhome> server to use as home server for student
                   8152: 
                   8153: =back
1.297     matthew  8154: 
                   8155: =item *
                   8156: 
                   8157: modify_student_enrollment
                   8158: 
                   8159: Change a students enrollment status in a class.  The environment variable
                   8160: 'role.request.course' must be defined for this function to proceed.
                   8161: 
                   8162: Inputs:
                   8163: 
                   8164: =over 4
                   8165: 
                   8166: =item $udom, students domain
                   8167: 
                   8168: =item $uname, students name
                   8169: 
                   8170: =item $uid, students user id
                   8171: 
                   8172: =item $first, students first name
                   8173: 
                   8174: =item $middle
                   8175: 
                   8176: =item $last
                   8177: 
                   8178: =item $gene
                   8179: 
                   8180: =item $usec
                   8181: 
                   8182: =item $end
                   8183: 
                   8184: =item $start
                   8185: 
                   8186: =back
                   8187: 
1.191     harris41 8188: 
                   8189: =item *
                   8190: 
1.243     albertel 8191: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8192: custom role; give a custom role to a user for the level given by URL.  Specify
                   8193: name and domain of role author, and role name
1.191     harris41 8194: 
                   8195: =item *
                   8196: 
1.243     albertel 8197: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8198: 
                   8199: =item *
                   8200: 
1.243     albertel 8201: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8202: 
                   8203: =back
                   8204: 
                   8205: =head2 Course Infomation
                   8206: 
                   8207: =over 4
1.191     harris41 8208: 
                   8209: =item *
                   8210: 
1.631     albertel 8211: coursedescription($courseid) : returns a hash of information about the
                   8212: specified course id, including all environment settings for the
                   8213: course, the description of the course will be in the hash under the
                   8214: key 'description'
1.191     harris41 8215: 
                   8216: =item *
                   8217: 
1.624     albertel 8218: resdata($name,$domain,$type,@which) : request for current parameter
                   8219: setting for a specific $type, where $type is either 'course' or 'user',
                   8220: @what should be a list of parameters to ask about. This routine caches
                   8221: answers for 5 minutes.
1.243     albertel 8222: 
                   8223: =back
                   8224: 
                   8225: =head2 Course Modification
                   8226: 
                   8227: =over 4
1.191     harris41 8228: 
                   8229: =item *
                   8230: 
1.243     albertel 8231: writecoursepref($courseid,%prefs) : write preferences (environment
                   8232: database) for a course
1.191     harris41 8233: 
                   8234: =item *
                   8235: 
1.243     albertel 8236: createcourse($udom,$description,$url) : make/modify course
                   8237: 
                   8238: =back
                   8239: 
                   8240: =head2 Resource Subroutines
                   8241: 
                   8242: =over 4
1.191     harris41 8243: 
                   8244: =item *
                   8245: 
1.243     albertel 8246: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8247: 
                   8248: =item *
                   8249: 
1.243     albertel 8250: repcopy($filename) : subscribes to the requested file, and attempts to
                   8251: replicate from the owning library server, Might return
1.607     raeburn  8252: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8253: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8254: resource. Expects the local filesystem pathname
                   8255: (/home/httpd/html/res/....)
                   8256: 
                   8257: =back
                   8258: 
                   8259: =head2 Resource Information
                   8260: 
                   8261: =over 4
1.191     harris41 8262: 
                   8263: =item *
                   8264: 
1.243     albertel 8265: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8266: a vairety of different possible values, $varname should be a request
                   8267: string, and the other parameters can be used to specify who and what
                   8268: one is asking about.
                   8269: 
                   8270: Possible values for $varname are environment.lastname (or other item
                   8271: from the envirnment hash), user.name (or someother aspect about the
                   8272: user), resource.0.maxtries (or some other part and parameter of a
                   8273: resource)
1.204     albertel 8274: 
                   8275: =item *
                   8276: 
1.243     albertel 8277: directcondval($number) : get current value of a condition; reads from a state
                   8278: string
1.204     albertel 8279: 
                   8280: =item *
                   8281: 
1.243     albertel 8282: condval($condidx) : value of condition index based on state
1.204     albertel 8283: 
                   8284: =item *
                   8285: 
1.243     albertel 8286: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8287: resource's metadata, $what should be either a specific key, or either
                   8288: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8289: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8290: 
                   8291: this function automatically caches all requests
1.191     harris41 8292: 
                   8293: =item *
                   8294: 
1.243     albertel 8295: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8296: network of library servers; returns file handle of where SQL and regex results
                   8297: will be stored for query
1.191     harris41 8298: 
                   8299: =item *
                   8300: 
1.243     albertel 8301: symbread($filename) : return symbolic list entry (filename argument optional);
                   8302: returns the data handle
1.191     harris41 8303: 
                   8304: =item *
                   8305: 
1.243     albertel 8306: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8307: a possible symb for the URL in $thisfn, and if is an encryypted
                   8308: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8309: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8310: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8311: 
1.191     harris41 8312: 
                   8313: =item *
                   8314: 
1.243     albertel 8315: symbclean($symb) : removes versions numbers from a symb, returns the
                   8316: cleaned symb
1.191     harris41 8317: 
                   8318: =item *
                   8319: 
1.243     albertel 8320: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8321: course map, user must be in a course for it to work.
1.191     harris41 8322: 
                   8323: =item *
                   8324: 
1.243     albertel 8325: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8326: 
                   8327: =item *
                   8328: 
1.243     albertel 8329: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8330: a random seed, all arguments are optional, if they aren't sent it uses the
                   8331: environment to derive them. Note: if symb isn't sent and it can't get one
                   8332: from &symbread it will use the current time as its return value
1.191     harris41 8333: 
                   8334: =item *
                   8335: 
1.243     albertel 8336: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8337: unfakeable, receipt
1.191     harris41 8338: 
                   8339: =item *
                   8340: 
1.620     albertel 8341: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8342: 
                   8343: =item *
                   8344: 
1.243     albertel 8345: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8346: 
                   8347: =item *
                   8348: 
1.243     albertel 8349: 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 8350: 
                   8351: =item *
                   8352: 
1.243     albertel 8353: 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 8354: 
                   8355: =item *
                   8356: 
1.243     albertel 8357: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8358: 
                   8359: =item *
                   8360: 
1.243     albertel 8361: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8362: forcing spreadsheet to reevaluate the resource scores next time.
                   8363: 
                   8364: =back
                   8365: 
                   8366: =head2 Storing/Retreiving Data
                   8367: 
                   8368: =over 4
1.191     harris41 8369: 
                   8370: =item *
                   8371: 
1.243     albertel 8372: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8373: for this url; hashref needs to be given and should be a \%hashname; the
                   8374: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8375: be derived from the env
1.191     harris41 8376: 
                   8377: =item *
                   8378: 
1.243     albertel 8379: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8380: uses critical subroutine
1.191     harris41 8381: 
                   8382: =item *
                   8383: 
1.243     albertel 8384: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8385: all args are optional
1.191     harris41 8386: 
                   8387: =item *
                   8388: 
1.717     albertel 8389: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8390: dumps the complete (or key matching regexp) namespace into a hash
                   8391: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8392: normally &store()ed into
                   8393: 
                   8394: $range should be either an integer '100' (give me the first 100
                   8395:                                            matching records)
                   8396:               or be  two integers sperated by a - with no spaces
                   8397:                  '30-50' (give me the 30th through the 50th matching
                   8398:                           records)
                   8399: 
                   8400: 
                   8401: =item *
                   8402: 
                   8403: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8404: replaces a &store() version of data with a replacement set of data
                   8405: for a particular resource in a namespace passed in the $storehash hash 
                   8406: reference
                   8407: 
                   8408: =item *
                   8409: 
1.243     albertel 8410: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8411: works very similar to store/cstore, but all data is stored in a
                   8412: temporary location and can be reset using tmpreset, $storehash should
                   8413: be a hash reference, returns nothing on success
1.191     harris41 8414: 
                   8415: =item *
                   8416: 
1.243     albertel 8417: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8418: similar to restore, but all data is stored in a temporary location and
                   8419: can be reset using tmpreset. Returns a hash of values on success,
                   8420: error string otherwise.
1.191     harris41 8421: 
                   8422: =item *
                   8423: 
1.243     albertel 8424: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8425: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8426: 
                   8427: =item *
                   8428: 
1.243     albertel 8429: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8430: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8431: 
                   8432: =item *
                   8433: 
1.243     albertel 8434: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8435: namesp ($udom and $uname are optional)
1.191     harris41 8436: 
                   8437: =item *
                   8438: 
1.702     albertel 8439: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8440: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8441: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8442: 
1.702     albertel 8443: $range should be either an integer '100' (give me the first 100
                   8444:                                            matching records)
                   8445:               or be  two integers sperated by a - with no spaces
                   8446:                  '30-50' (give me the 30th through the 50th matching
                   8447:                           records)
1.449     matthew  8448: =item *
                   8449: 
                   8450: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8451: $store can be a scalar, an array reference, or if the amount to be 
                   8452: incremented is > 1, a hash reference.
                   8453: 
                   8454: ($udom and $uname are optional)
1.191     harris41 8455: 
                   8456: =item *
                   8457: 
1.243     albertel 8458: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8459: ($udom and $uname are optional)
1.191     harris41 8460: 
                   8461: =item *
                   8462: 
1.243     albertel 8463: cput($namespace,$storehash,$udom,$uname) : critical put
                   8464: ($udom and $uname are optional)
1.191     harris41 8465: 
                   8466: =item *
                   8467: 
1.748     albertel 8468: newput($namespace,$storehash,$udom,$uname) :
                   8469: 
                   8470: Attempts to store the items in the $storehash, but only if they don't
                   8471: currently exist, if this succeeds you can be certain that you have 
                   8472: successfully created a new key value pair in the $namespace db.
                   8473: 
                   8474: 
                   8475: Args:
                   8476:  $namespace: name of database to store values to
                   8477:  $storehash: hashref to store to the db
                   8478:  $udom: (optional) domain of user containing the db
                   8479:  $uname: (optional) name of user caontaining the db
                   8480: 
                   8481: Returns:
                   8482:  'ok' -> succeeded in storing all keys of $storehash
                   8483:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8484:                         least <key> already existed in the db (other
                   8485:                         requested keys may also already exist)
                   8486:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8487:  'con_lost' -> unable to contact request server
                   8488:  'refused' -> action was not allowed by remote machine
                   8489: 
                   8490: 
                   8491: =item *
                   8492: 
1.243     albertel 8493: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8494: reference filled in from namesp (encrypts the return communication)
                   8495: ($udom and $uname are optional)
1.191     harris41 8496: 
                   8497: =item *
                   8498: 
1.243     albertel 8499: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8500: critical subroutine
                   8501: 
1.806     raeburn  8502: =item *
                   8503: 
                   8504: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8505: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8506: 
                   8507: =item *
                   8508: 
                   8509: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8510: 
1.243     albertel 8511: =back
                   8512: 
                   8513: =head2 Network Status Functions
                   8514: 
                   8515: =over 4
1.191     harris41 8516: 
                   8517: =item *
                   8518: 
                   8519: dirlist($uri) : return directory list based on URI
                   8520: 
                   8521: =item *
                   8522: 
1.243     albertel 8523: spareserver() : find server with least workload from spare.tab
                   8524: 
                   8525: =back
                   8526: 
                   8527: =head2 Apache Request
                   8528: 
                   8529: =over 4
1.191     harris41 8530: 
                   8531: =item *
                   8532: 
1.243     albertel 8533: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8534: localhost, posts hash
                   8535: 
                   8536: =back
                   8537: 
                   8538: =head2 Data to String to Data
                   8539: 
                   8540: =over 4
1.191     harris41 8541: 
                   8542: =item *
                   8543: 
1.243     albertel 8544: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8545: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8546: 
                   8547: =item *
                   8548: 
1.243     albertel 8549: hashref2str($hashref) : convert a hashref into a string complete with
                   8550: escaping and '=' and '&' separators, supports elements that are
                   8551: arrayrefs and hashrefs
1.191     harris41 8552: 
                   8553: =item *
                   8554: 
1.243     albertel 8555: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8556: with escaping and '&' separators, supports elements that are arrayrefs
                   8557: and hashrefs
1.191     harris41 8558: 
                   8559: =item *
                   8560: 
1.243     albertel 8561: str2hash($string) : convert string to hash using unescaping and
                   8562: splitting on '=' and '&', supports elements that are arrayrefs and
                   8563: hashrefs
1.191     harris41 8564: 
                   8565: =item *
                   8566: 
1.243     albertel 8567: str2array($string) : convert string to hash using unescaping and
                   8568: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8569: 
                   8570: =back
                   8571: 
                   8572: =head2 Logging Routines
                   8573: 
                   8574: =over 4
                   8575: 
                   8576: These routines allow one to make log messages in the lonnet.log and
                   8577: lonnet.perm logfiles.
1.191     harris41 8578: 
                   8579: =item *
                   8580: 
1.243     albertel 8581: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8582: 
                   8583: =item *
                   8584: 
1.243     albertel 8585: logthis() : append message to the normal lonnet.log file, it gets
                   8586: preiodically rolled over and deleted.
1.191     harris41 8587: 
                   8588: =item *
                   8589: 
1.243     albertel 8590: logperm() : append a permanent message to lonnet.perm.log, this log
                   8591: file never gets deleted by any automated portion of the system, only
                   8592: messages of critical importance should go in here.
                   8593: 
                   8594: =back
                   8595: 
                   8596: =head2 General File Helper Routines
                   8597: 
                   8598: =over 4
1.191     harris41 8599: 
                   8600: =item *
                   8601: 
1.481     raeburn  8602: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8603: (a) files in /uploaded
                   8604:   (i) If a local copy of the file exists - 
                   8605:       compares modification date of local copy with last-modified date for 
                   8606:       definitive version stored on home server for course. If local copy is 
                   8607:       stale, requests a new version from the home server and stores it. 
                   8608:       If the original has been removed from the home server, then local copy 
                   8609:       is unlinked.
                   8610:   (ii) If local copy does not exist -
                   8611:       requests the file from the home server and stores it. 
                   8612:   
                   8613:   If $caller is 'uploadrep':  
                   8614:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8615:     for request for files originally uploaded via DOCS. 
                   8616:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8617:   
                   8618:   Otherwise:
                   8619:      This indicates a call from the content generation phase of the request.
                   8620:      -  returns the entire contents of the file or -1.
                   8621:      
                   8622: (b) files in /res
                   8623:    - returns the entire contents of a file or -1; 
                   8624:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8625: 
1.712     albertel 8626: 
                   8627: =item *
                   8628: 
                   8629: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8630:                   reference
                   8631: 
                   8632: returns either a stat() list of data about the file or an empty list
                   8633: if the file doesn't exist or couldn't find out about it (connection
                   8634: problems or user unknown)
                   8635: 
1.191     harris41 8636: =item *
                   8637: 
1.243     albertel 8638: filelocation($dir,$file) : returns file system location of a file
                   8639: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8640: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8641: and a file of ../bob will become /a/bob)
1.191     harris41 8642: 
                   8643: =item *
                   8644: 
                   8645: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8646: filelocation except for hrefs
                   8647: 
                   8648: =item *
                   8649: 
                   8650: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8651: 
1.243     albertel 8652: =back
                   8653: 
1.608     albertel 8654: =head2 Usererfile file routines (/uploaded*)
                   8655: 
                   8656: =over 4
                   8657: 
                   8658: =item *
                   8659: 
                   8660: userfileupload(): main rotine for putting a file in a user or course's
                   8661:                   filespace, arguments are,
                   8662: 
1.620     albertel 8663:  formname - required - this is the name of the element in $env where the
1.608     albertel 8664:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8665:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8666:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8667:  coursedoc - if true, store the file in the course of the active role
                   8668:              of the current user
                   8669:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8670:          if undefined, it will be placed in "unknown"
                   8671: 
                   8672:  (This routine calls clean_filename() to remove any dangerous
                   8673:  characters from the filename, and then calls finuserfileupload() to
                   8674:  complete the transaction)
                   8675: 
                   8676:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8677:  and /adm/notfound.html if unsuccessful
                   8678: 
                   8679: =item *
                   8680: 
                   8681: clean_filename(): routine for cleaing a filename up for storage in
                   8682:                  userfile space, argument is:
                   8683: 
                   8684:  filename - proposed filename
                   8685: 
                   8686: returns: the new clean filename
                   8687: 
                   8688: =item *
                   8689: 
                   8690: finishuserfileupload(): routine that creaes and sends the file to
                   8691: userspace, probably shouldn't be called directly
                   8692: 
                   8693:   docuname: username or courseid of destination for the file
                   8694:   docudom: domain of user/course of destination for the file
                   8695:   formname: same as for userfileupload()
                   8696:   fname: filename (inculding subdirectories) for the file
                   8697: 
                   8698:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8699:  and /adm/notfound.html if unsuccessful
                   8700: 
                   8701: =item *
                   8702: 
                   8703: renameuserfile(): renames an existing userfile to a new name
                   8704: 
                   8705:   Args:
                   8706:    docuname: username or courseid of destination for the file
                   8707:    docudom: domain of user/course of destination for the file
                   8708:    old: current file name (including any subdirs under userfiles)
                   8709:    new: desired file name (including any subdirs under userfiles)
                   8710: 
                   8711: =item *
                   8712: 
                   8713: mkdiruserfile(): creates a directory is a userfiles dir
                   8714: 
                   8715:   Args:
                   8716:    docuname: username or courseid of destination for the file
                   8717:    docudom: domain of user/course of destination for the file
                   8718:    dir: dir to create (including any subdirs under userfiles)
                   8719: 
                   8720: =item *
                   8721: 
                   8722: removeuserfile(): removes a file that exists in userfiles
                   8723: 
                   8724:   Args:
                   8725:    docuname: username or courseid of destination for the file
                   8726:    docudom: domain of user/course of destination for the file
                   8727:    fname: filname to delete (including any subdirs under userfiles)
                   8728: 
                   8729: =item *
                   8730: 
                   8731: removeuploadedurl(): convience function for removeuserfile()
                   8732: 
                   8733:   Args:
                   8734:    url:  a full /uploaded/... url to delete
                   8735: 
1.747     albertel 8736: =item * 
                   8737: 
                   8738: get_portfile_permissions():
                   8739:   Args:
                   8740:     domain: domain of user or course contain the portfolio files
                   8741:     user: name of user or num of course contain the portfolio files
                   8742:   Returns:
                   8743:     hashref of a dump of the proper file_permissions.db
                   8744:    
                   8745: 
                   8746: =item * 
                   8747: 
                   8748: get_access_controls():
                   8749: 
                   8750: Args:
                   8751:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8752:   group: (optional) the group you want the files associated with
                   8753:   file: (optional) the file you want access info on
                   8754: 
                   8755: Returns:
1.749     raeburn  8756:     a hash (keys are file names) of hashes containing
                   8757:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8758:         values are XML containing access control settings (see below) 
1.747     albertel 8759: 
                   8760: Internal notes:
                   8761: 
1.749     raeburn  8762:  access controls are stored in file_permissions.db as key=value pairs.
                   8763:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8764:         where scope -> public,guest,course,group,domains or users.
                   8765:               end -> UNIX time for end of access (0 -> no end date)
                   8766:               start -> UNIX time for start of access
                   8767: 
                   8768:     value -> XML description of access control
                   8769:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8770:             <start></start>
                   8771:             <end></end>
                   8772: 
                   8773:             <password></password>  for scope type = guest
                   8774: 
                   8775:             <domain></domain>     for scope type = course or group
                   8776:             <number></number>
                   8777:             <roles id="">
                   8778:              <role></role>
                   8779:              <access></access>
                   8780:              <section></section>
                   8781:              <group></group>
                   8782:             </roles>
                   8783: 
                   8784:             <dom></dom>         for scope type = domains
                   8785: 
                   8786:             <users>             for scope type = users
                   8787:              <user>
                   8788:               <uname></uname>
                   8789:               <udom></udom>
                   8790:              </user>
                   8791:             </users>
                   8792:            </scope> 
                   8793:               
                   8794:  Access data is also aggregated for each file in an additional key=value pair:
                   8795:  key -> path to file/file_name\0accesscontrol 
                   8796:  value -> reference to hash
                   8797:           hash contains key = value pairs
                   8798:           where key = uniqueID:scope_end_start
                   8799:                 value = UNIX time record was last updated
                   8800: 
                   8801:           Used to improve speed of look-ups of access controls for each file.  
                   8802:  
                   8803:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8804: 
                   8805: modify_access_controls():
                   8806: 
                   8807: Modifies access controls for a portfolio file
                   8808: Args
                   8809: 1. file name
                   8810: 2. reference to hash of required changes,
                   8811: 3. domain
                   8812: 4. username
                   8813:   where domain,username are the domain of the portfolio owner 
                   8814:   (either a user or a course) 
                   8815: 
                   8816: Returns:
                   8817: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8818: 2. result of deletions ('ok' or 'error', with error message).
                   8819: 3. reference to hash of any new or updated access controls.
                   8820: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8821:    key = integer (inbound ID)
                   8822:    value = uniqueID  
1.747     albertel 8823: 
1.608     albertel 8824: =back
                   8825: 
1.243     albertel 8826: =head2 HTTP Helper Routines
                   8827: 
                   8828: =over 4
                   8829: 
1.191     harris41 8830: =item *
                   8831: 
                   8832: escape() : unpack non-word characters into CGI-compatible hex codes
                   8833: 
                   8834: =item *
                   8835: 
                   8836: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8837: 
1.243     albertel 8838: =back
                   8839: 
                   8840: =head1 PRIVATE SUBROUTINES
                   8841: 
                   8842: =head2 Underlying communication routines (Shouldn't call)
                   8843: 
                   8844: =over 4
                   8845: 
                   8846: =item *
                   8847: 
                   8848: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8849: 
                   8850: =item *
                   8851: 
                   8852: reply() : uses subreply to send a message to remote machine, logs all failures
                   8853: 
                   8854: =item *
                   8855: 
                   8856: critical() : passes a critical message to another server; if cannot
                   8857: get through then place message in connection buffer directory and
                   8858: returns con_delayed, if incapable of saving message, returns
                   8859: con_failed
                   8860: 
                   8861: =item *
                   8862: 
                   8863: reconlonc() : tries to reconnect lonc client processes.
                   8864: 
                   8865: =back
                   8866: 
                   8867: =head2 Resource Access Logging
                   8868: 
                   8869: =over 4
                   8870: 
                   8871: =item *
                   8872: 
                   8873: flushcourselogs() : flush (save) buffer logs and access logs
                   8874: 
                   8875: =item *
                   8876: 
                   8877: courselog($what) : save message for course in hash
                   8878: 
                   8879: =item *
                   8880: 
                   8881: courseacclog($what) : save message for course using &courselog().  Perform
                   8882: special processing for specific resource types (problems, exams, quizzes, etc).
                   8883: 
1.191     harris41 8884: =item *
                   8885: 
                   8886: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8887: as a PerlChildExitHandler
1.243     albertel 8888: 
                   8889: =back
                   8890: 
                   8891: =head2 Other
                   8892: 
                   8893: =over 4
                   8894: 
                   8895: =item *
                   8896: 
                   8897: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8898: 
                   8899: =back
                   8900: 
                   8901: =cut

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