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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.847   ! albertel    4: # $Id: lonnet.pm,v 1.846 2007/03/08 01:58:41 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]);
                   6179: 	} else {
                   6180: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6181: 	}
                   6182:     }
                   6183:     # first look for a package that matches the requested part id
                   6184:     foreach my $package (@specifics) {
                   6185: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6186: 	next if ($pack_part ne $part);
                   6187: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6188: 	    return $packagetab{"$pack_type&$name&default"};
                   6189: 	}
                   6190:     }
                   6191:     # look for any possible matching non extension_ package
                   6192:     foreach my $package (@specifics) {
                   6193: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6194: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6195: 	    return $packagetab{"$pack_type&$name&default"};
                   6196: 	}
1.585     albertel 6197: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6198: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6199: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6200: 	}
                   6201:     }
1.738     albertel 6202:     # look for any posible extension_ match
                   6203:     foreach my $package (@extension) {
                   6204: 	my ($package,$pack_type)=@{$package};
                   6205: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6206: 	    return $packagetab{"$pack_type&$name&default"};
                   6207: 	}
                   6208: 	if (defined($packagetab{$package."&$name&default"})) {
                   6209: 	    return $packagetab{$package."&$name&default"};
                   6210: 	}
                   6211:     }
                   6212:     # look for a global default setting
                   6213:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6214: 	return $packagetab{"default&$name&default"};
                   6215:     }
1.395     albertel 6216:     return undef;
                   6217: }
                   6218: 
1.334     albertel 6219: sub add_prefix_and_part {
                   6220:     my ($prefix,$part)=@_;
                   6221:     my $keyroot;
                   6222:     if (defined($prefix) && $prefix !~ /^__/) {
                   6223: 	# prefix that has a part already
                   6224: 	$keyroot=$prefix;
                   6225:     } elsif (defined($prefix)) {
                   6226: 	# prefix that is missing a part
                   6227: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6228:     } else {
                   6229: 	# no prefix at all
                   6230: 	if (defined($part)) { $keyroot='_'.$part; }
                   6231:     }
                   6232:     return $keyroot;
                   6233: }
                   6234: 
1.71      www      6235: # ---------------------------------------------------------------- Get metadata
                   6236: 
1.599     albertel 6237: my %metaentry;
1.71      www      6238: sub metadata {
1.176     www      6239:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6240:     $uri=&declutter($uri);
1.288     albertel 6241:     # if it is a non metadata possible uri return quickly
1.529     albertel 6242:     if (($uri eq '') || 
                   6243: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6244: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6245:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6246: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6247: 	return undef;
1.288     albertel 6248:     }
1.73      www      6249:     my $filename=$uri;
                   6250:     $uri=~s/\.meta$//;
1.172     www      6251: #
                   6252: # Is the metadata already cached?
1.177     www      6253: # Look at timestamp of caching
1.172     www      6254: # Everything is cached by the main uri, libraries are never directly cached
                   6255: #
1.428     albertel 6256:     if (!defined($liburi)) {
1.599     albertel 6257: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6258: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6259:     }
                   6260:     {
1.172     www      6261: #
                   6262: # Is this a recursive call for a library?
                   6263: #
1.599     albertel 6264: #	if (! exists($metacache{$uri})) {
                   6265: #	    $metacache{$uri}={};
                   6266: #	}
1.171     www      6267:         if ($liburi) {
                   6268: 	    $liburi=&declutter($liburi);
                   6269:             $filename=$liburi;
1.401     bowersj2 6270:         } else {
1.599     albertel 6271: 	    &devalidate_cache_new('meta',$uri);
                   6272: 	    undef(%metaentry);
1.401     bowersj2 6273: 	}
1.140     www      6274:         my %metathesekeys=();
1.73      www      6275:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6276: 	my $metastring;
1.768     albertel 6277: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6278: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6279: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6280: 	    $metastring=&getfile($file);
1.489     albertel 6281: 	}
1.208     albertel 6282:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6283:         my $token;
1.140     www      6284:         undef %metathesekeys;
1.71      www      6285:         while ($token=$parser->get_token) {
1.339     albertel 6286: 	    if ($token->[0] eq 'S') {
                   6287: 		if (defined($token->[2]->{'package'})) {
1.172     www      6288: #
                   6289: # This is a package - get package info
                   6290: #
1.339     albertel 6291: 		    my $package=$token->[2]->{'package'};
                   6292: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6293: 		    if (defined($token->[2]->{'id'})) { 
                   6294: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6295: 		    }
1.599     albertel 6296: 		    if ($metaentry{':packages'}) {
                   6297: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6298: 		    } else {
1.599     albertel 6299: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6300: 		    }
1.736     albertel 6301: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6302: 			my $part=$keyroot;
                   6303: 			$part=~s/^\_//;
1.736     albertel 6304: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6305: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6306: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6307: 			    # ignore package.tab specified default values
                   6308:                             # here &package_tab_default() will fetch those
                   6309: 			    if ($subp eq 'default') { next; }
1.736     albertel 6310: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6311: 			    my $unikey;
                   6312: 			    if ($pack =~ /_0$/) {
                   6313: 				$unikey='parameter_0_'.$name;
                   6314: 				$part=0;
                   6315: 			    } else {
                   6316: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6317: 			    }
1.339     albertel 6318: 			    if ($subp eq 'display') {
                   6319: 				$value.=' [Part: '.$part.']';
                   6320: 			    }
1.599     albertel 6321: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6322: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6323: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6324: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6325: 			    }
1.599     albertel 6326: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6327: 				$metaentry{':'.$unikey}=
                   6328: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6329: 			    }
1.339     albertel 6330: 			}
                   6331: 		    }
                   6332: 		} else {
1.172     www      6333: #
                   6334: # This is not a package - some other kind of start tag
1.339     albertel 6335: #
                   6336: 		    my $entry=$token->[1];
                   6337: 		    my $unikey;
                   6338: 		    if ($entry eq 'import') {
                   6339: 			$unikey='';
                   6340: 		    } else {
                   6341: 			$unikey=$entry;
                   6342: 		    }
                   6343: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6344: 
                   6345: 		    if (defined($token->[2]->{'id'})) { 
                   6346: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6347: 		    }
1.175     www      6348: 
1.339     albertel 6349: 		    if ($entry eq 'import') {
1.175     www      6350: #
                   6351: # Importing a library here
1.339     albertel 6352: #
                   6353: 			if ($depthcount<20) {
                   6354: 			    my $location=$parser->get_text('/import');
                   6355: 			    my $dir=$filename;
                   6356: 			    $dir=~s|[^/]*$||;
                   6357: 			    $location=&filelocation($dir,$location);
1.736     albertel 6358: 			    my $metadata = 
                   6359: 				&metadata($uri,'keys', $location,$unikey,
                   6360: 					  $depthcount+1);
                   6361: 			    foreach my $meta (split(',',$metadata)) {
                   6362: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6363: 				$metathesekeys{$meta}=1;
1.339     albertel 6364: 			    }
                   6365: 			}
                   6366: 		    } else { 
                   6367: 			
                   6368: 			if (defined($token->[2]->{'name'})) { 
                   6369: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6370: 			}
                   6371: 			$metathesekeys{$unikey}=1;
1.736     albertel 6372: 			foreach my $param (@{$token->[3]}) {
                   6373: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6374: 				$token->[2]->{$param};
1.339     albertel 6375: 			}
                   6376: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6377: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6378: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6379: 		 # only ws inside the tag, and not in default, so use default
                   6380: 		 # as value
1.599     albertel 6381: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6382: 			} else {
1.321     albertel 6383: 		  # either something interesting inside the tag or default
                   6384:                   # uninteresting
1.599     albertel 6385: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6386: 			}
1.172     www      6387: # end of not-a-package not-a-library import
1.339     albertel 6388: 		    }
1.172     www      6389: # end of not-a-package start tag
1.339     albertel 6390: 		}
1.172     www      6391: # the next is the end of "start tag"
1.339     albertel 6392: 	    }
                   6393: 	}
1.483     albertel 6394: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6395: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6396: 	    #no specific packages #how's our extension
                   6397: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6398: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6399: 					 \%metathesekeys);
                   6400: 	}
1.599     albertel 6401: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6402: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6403: 		#no specific packages well let's get default then
                   6404: 		if ($key!~/^default&/) { next; }
1.488     albertel 6405: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6406: 					     \%metathesekeys);
                   6407: 	    }
                   6408: 	}
1.338     www      6409: # are there custom rights to evaluate
1.599     albertel 6410: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6411: 
1.338     www      6412:     #
                   6413:     # Importing a rights file here
1.339     albertel 6414:     #
                   6415: 	    unless ($depthcount) {
1.599     albertel 6416: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6417: 		my $dir=$filename;
                   6418: 		$dir=~s|[^/]*$||;
                   6419: 		$location=&filelocation($dir,$location);
1.736     albertel 6420: 		my $rights_metadata =
                   6421: 		    &metadata($uri,'keys',$location,'_rights',
                   6422: 			      $depthcount+1);
                   6423: 		foreach my $rights (split(',',$rights_metadata)) {
                   6424: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6425: 		    $metathesekeys{$rights}=1;
1.339     albertel 6426: 		}
                   6427: 	    }
                   6428: 	}
1.737     albertel 6429: 	# uniqifiy package listing
                   6430: 	my %seen;
                   6431: 	my @uniq_packages =
                   6432: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6433: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6434: 
                   6435: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6436: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6437: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6438: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6439: # this is the end of "was not already recently cached
1.71      www      6440:     }
1.599     albertel 6441:     return $metaentry{':'.$what};
1.261     albertel 6442: }
                   6443: 
1.488     albertel 6444: sub metadata_create_package_def {
1.483     albertel 6445:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6446:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6447:     if ($subp eq 'default') { next; }
                   6448:     
1.599     albertel 6449:     if (defined($metaentry{':packages'})) {
                   6450: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6451:     } else {
1.599     albertel 6452: 	$metaentry{':packages'}=$package;
1.483     albertel 6453:     }
                   6454:     my $value=$packagetab{$key};
                   6455:     my $unikey;
                   6456:     $unikey='parameter_0_'.$name;
1.599     albertel 6457:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6458:     $$metathesekeys{$unikey}=1;
1.599     albertel 6459:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6460: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6461:     }
1.599     albertel 6462:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6463: 	$metaentry{':'.$unikey}=
                   6464: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6465:     }
                   6466: }
                   6467: 
1.261     albertel 6468: sub metadata_generate_part0 {
                   6469:     my ($metadata,$metacache,$uri) = @_;
                   6470:     my %allnames;
1.737     albertel 6471:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6472: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6473: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6474: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6475: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6476: 	    $allnames{$name}=$part;
                   6477: 	  }
                   6478: 	}
                   6479:     }
                   6480:     foreach my $name (keys(%allnames)) {
                   6481:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6482:       my $key=":parameter_0_$name";
1.261     albertel 6483:       $$metacache{"$key.part"}='0';
                   6484:       $$metacache{"$key.name"}=$name;
1.428     albertel 6485:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6486: 					   $allnames{$name}.'_'.$name.
                   6487: 					   '.type'};
1.428     albertel 6488:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6489: 			     '.display'};
1.644     www      6490:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6491:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6492:       $$metacache{"$key.display"}=$olddis;
                   6493:     }
1.71      www      6494: }
                   6495: 
1.764     albertel 6496: # ------------------------------------------------------ Devalidate title cache
                   6497: 
                   6498: sub devalidate_title_cache {
                   6499:     my ($url)=@_;
                   6500:     if (!$env{'request.course.id'}) { return; }
                   6501:     my $symb=&symbread($url);
                   6502:     if (!$symb) { return; }
                   6503:     my $key=$env{'request.course.id'}."\0".$symb;
                   6504:     &devalidate_cache_new('title',$key);
                   6505: }
                   6506: 
1.301     www      6507: # ------------------------------------------------- Get the title of a resource
                   6508: 
                   6509: sub gettitle {
                   6510:     my $urlsymb=shift;
                   6511:     my $symb=&symbread($urlsymb);
1.534     albertel 6512:     if ($symb) {
1.620     albertel 6513: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6514: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6515: 	if (defined($cached)) { 
                   6516: 	    return $result;
                   6517: 	}
1.534     albertel 6518: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6519: 	my $title='';
                   6520: 	my %bighash;
1.620     albertel 6521: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6522: 		&GDBM_READER(),0640)) {
                   6523: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6524: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6525: 	    untie %bighash;
                   6526: 	}
                   6527: 	$title=~s/\&colon\;/\:/gs;
                   6528: 	if ($title) {
1.599     albertel 6529: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6530: 	}
                   6531: 	$urlsymb=$url;
                   6532:     }
                   6533:     my $title=&metadata($urlsymb,'title');
                   6534:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6535:     return $title;
1.301     www      6536: }
1.613     albertel 6537: 
1.614     albertel 6538: sub get_slot {
                   6539:     my ($which,$cnum,$cdom)=@_;
                   6540:     if (!$cnum || !$cdom) {
1.790     albertel 6541: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6542: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6543: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6544:     }
1.703     albertel 6545:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6546:     my %slotinfo;
                   6547:     if (exists($remembered{$key})) {
                   6548: 	$slotinfo{$which} = $remembered{$key};
                   6549:     } else {
                   6550: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6551: 	&Apache::lonhomework::showhash(%slotinfo);
                   6552: 	my ($tmp)=keys(%slotinfo);
                   6553: 	if ($tmp=~/^error:/) { return (); }
                   6554: 	$remembered{$key} = $slotinfo{$which};
                   6555:     }
1.616     albertel 6556:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6557: 	return %{$slotinfo{$which}};
                   6558:     }
                   6559:     return $slotinfo{$which};
1.614     albertel 6560: }
1.31      www      6561: # ------------------------------------------------- Update symbolic store links
                   6562: 
                   6563: sub symblist {
                   6564:     my ($mapname,%newhash)=@_;
1.438     www      6565:     $mapname=&deversion(&declutter($mapname));
1.31      www      6566:     my %hash;
1.620     albertel 6567:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6568:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6569:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6570: 	    foreach my $url (keys %newhash) {
                   6571: 		next if ($url eq 'last_known'
                   6572: 			 && $env{'form.no_update_last_known'});
                   6573: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6574: 						    $newhash{$url}->[1],
                   6575: 						    $newhash{$url}->[0]);
1.191     harris41 6576:             }
1.31      www      6577:             if (untie(%hash)) {
                   6578: 		return 'ok';
                   6579:             }
                   6580:         }
                   6581:     }
                   6582:     return 'error';
1.212     www      6583: }
                   6584: 
                   6585: # --------------------------------------------------------------- Verify a symb
                   6586: 
                   6587: sub symbverify {
1.510     www      6588:     my ($symb,$thisurl)=@_;
                   6589:     my $thisfn=$thisurl;
1.439     www      6590:     $thisfn=&declutter($thisfn);
1.215     www      6591: # direct jump to resource in page or to a sequence - will construct own symbs
                   6592:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6593: # check URL part
1.409     www      6594:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6595: 
1.431     www      6596:     unless ($url eq $thisfn) { return 0; }
1.213     www      6597: 
1.216     www      6598:     $symb=&symbclean($symb);
1.510     www      6599:     $thisurl=&deversion($thisurl);
1.439     www      6600:     $thisfn=&deversion($thisfn);
1.213     www      6601: 
                   6602:     my %bighash;
                   6603:     my $okay=0;
1.431     www      6604: 
1.620     albertel 6605:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6606:                             &GDBM_READER(),0640)) {
1.510     www      6607:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6608:         unless ($ids) { 
1.510     www      6609:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6610:         }
                   6611:         if ($ids) {
                   6612: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6613: 	    foreach my $id (split(/\,/,$ids)) {
                   6614: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6615:                if (
                   6616:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6617:    eq $symb) { 
1.620     albertel 6618: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6619: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6620: 		       $okay=1; 
                   6621: 		   }
                   6622: 	       }
1.216     www      6623: 	   }
                   6624:         }
1.213     www      6625: 	untie(%bighash);
                   6626:     }
                   6627:     return $okay;
1.31      www      6628: }
                   6629: 
1.210     www      6630: # --------------------------------------------------------------- Clean-up symb
                   6631: 
                   6632: sub symbclean {
                   6633:     my $symb=shift;
1.568     albertel 6634:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6635: # remove version from map
                   6636:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6637: 
1.210     www      6638: # remove version from URL
                   6639:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6640: 
1.507     www      6641: # remove wrapper
                   6642: 
1.510     www      6643:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6644:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6645:     return $symb;
1.409     www      6646: }
                   6647: 
                   6648: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6649: 
                   6650: sub encode_symb {
                   6651:     my ($map,$resid,$url)=@_;
                   6652:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6653: }
1.409     www      6654: 
                   6655: sub decode_symb {
1.568     albertel 6656:     my $symb=shift;
                   6657:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6658:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6659:     return (&fixversion($map),$resid,&fixversion($url));
                   6660: }
                   6661: 
                   6662: sub fixversion {
                   6663:     my $fn=shift;
1.609     banghart 6664:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6665:     my %bighash;
                   6666:     my $uri=&clutter($fn);
1.620     albertel 6667:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6668: # is this cached?
1.599     albertel 6669:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6670:     if (defined($cached)) { return $result; }
                   6671: # unfortunately not cached, or expired
1.620     albertel 6672:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6673: 	    &GDBM_READER(),0640)) {
                   6674:  	if ($bighash{'version_'.$uri}) {
                   6675:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6676:  	    unless (($version eq 'mostrecent') || 
                   6677: 		    ($version==&getversion($uri))) {
1.440     www      6678:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6679:  	    }
                   6680:  	}
                   6681:  	untie %bighash;
1.413     www      6682:     }
1.599     albertel 6683:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6684: }
                   6685: 
                   6686: sub deversion {
                   6687:     my $url=shift;
                   6688:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6689:     return $url;
1.210     www      6690: }
                   6691: 
1.31      www      6692: # ------------------------------------------------------ Return symb list entry
                   6693: 
                   6694: sub symbread {
1.249     www      6695:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6696:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6697:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6698: # no filename provided? try from environment
1.44      www      6699:     unless ($thisfn) {
1.620     albertel 6700:         if ($env{'request.symb'}) {
                   6701: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6702: 	}
1.620     albertel 6703: 	$thisfn=$env{'request.filename'};
1.44      www      6704:     }
1.569     albertel 6705:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6706: # is that filename actually a symb? Verify, clean, and return
                   6707:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6708: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6709: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6710: 	}
1.242     www      6711:     }
1.44      www      6712:     $thisfn=declutter($thisfn);
1.31      www      6713:     my %hash;
1.37      www      6714:     my %bighash;
                   6715:     my $syval='';
1.620     albertel 6716:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6717:         my $targetfn = $thisfn;
1.609     banghart 6718:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6719:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6720:         }
1.687     albertel 6721: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6722: 	    $targetfn=$1;
                   6723: 	}
1.620     albertel 6724:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6725:                       &GDBM_READER(),0640)) {
1.481     raeburn  6726: 	    $syval=$hash{$targetfn};
1.37      www      6727:             untie(%hash);
                   6728:         }
                   6729: # ---------------------------------------------------------- There was an entry
                   6730:         if ($syval) {
1.601     albertel 6731: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6732: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6733: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6734: 		    #return $env{$cache_str}='';
1.601     albertel 6735: 		#}    
                   6736: 		#$syval.=$1;
                   6737: 	    #}
1.37      www      6738:         } else {
                   6739: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6740:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6741:                             &GDBM_READER(),0640)) {
1.37      www      6742: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6743:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6744:               unless ($ids) { 
                   6745:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6746:               }
                   6747:               unless ($ids) {
                   6748: # alias?
                   6749: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6750:               }
1.37      www      6751:               if ($ids) {
                   6752: # ------------------------------------------------------------------- Has ID(s)
                   6753:                  my @possibilities=split(/\,/,$ids);
1.39      www      6754:                  if ($#possibilities==0) {
                   6755: # ----------------------------------------------- There is only one possibility
1.37      www      6756: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6757: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6758: 						    $resid,$thisfn);
1.249     www      6759:                  } elsif (!$donotrecurse) {
1.39      www      6760: # ------------------------------------------ There is more than one possibility
                   6761:                      my $realpossible=0;
1.800     albertel 6762:                      foreach my $id (@possibilities) {
                   6763: 			 my $file=$bighash{'src_'.$id};
1.39      www      6764:                          if (&allowed('bre',$file)) {
1.800     albertel 6765:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6766:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6767: 				$realpossible++;
1.626     albertel 6768:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6769: 						    $resid,$thisfn);
1.39      www      6770:                             }
                   6771: 			 }
1.191     harris41 6772:                      }
1.39      www      6773: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6774:                  } else {
                   6775:                      $syval='';
1.37      www      6776:                  }
                   6777: 	      }
                   6778:               untie(%bighash)
1.481     raeburn  6779:            }
1.31      www      6780:         }
1.62      www      6781:         if ($syval) {
1.620     albertel 6782: 	    return $env{$cache_str}=$syval;
1.62      www      6783:         }
1.31      www      6784:     }
1.44      www      6785:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6786:     return $env{$cache_str}='';
1.31      www      6787: }
                   6788: 
                   6789: # ---------------------------------------------------------- Return random seed
                   6790: 
1.32      www      6791: sub numval {
                   6792:     my $txt=shift;
                   6793:     $txt=~tr/A-J/0-9/;
                   6794:     $txt=~tr/a-j/0-9/;
                   6795:     $txt=~tr/K-T/0-9/;
                   6796:     $txt=~tr/k-t/0-9/;
                   6797:     $txt=~tr/U-Z/0-5/;
                   6798:     $txt=~tr/u-z/0-5/;
                   6799:     $txt=~s/\D//g;
1.564     albertel 6800:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6801:     return int($txt);
1.368     albertel 6802: }
                   6803: 
1.484     albertel 6804: sub numval2 {
                   6805:     my $txt=shift;
                   6806:     $txt=~tr/A-J/0-9/;
                   6807:     $txt=~tr/a-j/0-9/;
                   6808:     $txt=~tr/K-T/0-9/;
                   6809:     $txt=~tr/k-t/0-9/;
                   6810:     $txt=~tr/U-Z/0-5/;
                   6811:     $txt=~tr/u-z/0-5/;
                   6812:     $txt=~s/\D//g;
                   6813:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6814:     my $total;
                   6815:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6816:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6817:     return int($total);
                   6818: }
                   6819: 
1.575     albertel 6820: sub numval3 {
                   6821:     use integer;
                   6822:     my $txt=shift;
                   6823:     $txt=~tr/A-J/0-9/;
                   6824:     $txt=~tr/a-j/0-9/;
                   6825:     $txt=~tr/K-T/0-9/;
                   6826:     $txt=~tr/k-t/0-9/;
                   6827:     $txt=~tr/U-Z/0-5/;
                   6828:     $txt=~tr/u-z/0-5/;
                   6829:     $txt=~s/\D//g;
                   6830:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6831:     my $total;
                   6832:     foreach my $val (@txts) { $total+=$val; }
                   6833:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6834:     return $total;
                   6835: }
                   6836: 
1.675     albertel 6837: sub digest {
                   6838:     my ($data)=@_;
                   6839:     my $digest=&Digest::MD5::md5($data);
                   6840:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6841:     my ($e,$f);
                   6842:     {
                   6843:         use integer;
                   6844:         $e=($a+$b);
                   6845:         $f=($c+$d);
                   6846:         if ($_64bit) {
                   6847:             $e=(($e<<32)>>32);
                   6848:             $f=(($f<<32)>>32);
                   6849:         }
                   6850:     }
                   6851:     if (wantarray) {
                   6852: 	return ($e,$f);
                   6853:     } else {
                   6854: 	my $g;
                   6855: 	{
                   6856: 	    use integer;
                   6857: 	    $g=($e+$f);
                   6858: 	    if ($_64bit) {
                   6859: 		$g=(($g<<32)>>32);
                   6860: 	    }
                   6861: 	}
                   6862: 	return $g;
                   6863:     }
                   6864: }
                   6865: 
1.368     albertel 6866: sub latest_rnd_algorithm_id {
1.675     albertel 6867:     return '64bit5';
1.366     albertel 6868: }
1.32      www      6869: 
1.503     albertel 6870: sub get_rand_alg {
                   6871:     my ($courseid)=@_;
1.790     albertel 6872:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6873:     if ($courseid) {
1.620     albertel 6874: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6875:     }
                   6876:     return &latest_rnd_algorithm_id();
                   6877: }
                   6878: 
1.562     albertel 6879: sub validCODE {
                   6880:     my ($CODE)=@_;
                   6881:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6882:     return 0;
                   6883: }
                   6884: 
1.491     albertel 6885: sub getCODE {
1.620     albertel 6886:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6887:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6888: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6889: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6890: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6891:     }
                   6892:     return undef;
                   6893: }
                   6894: 
1.31      www      6895: sub rndseed {
1.155     albertel 6896:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6897: 
1.790     albertel 6898:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6899:     if (!$symb) {
1.366     albertel 6900: 	unless ($symb=$wsymb) { return time; }
                   6901:     }
                   6902:     if (!$courseid) { $courseid=$wcourseid; }
                   6903:     if (!$domain) { $domain=$wdomain; }
                   6904:     if (!$username) { $username=$wusername }
1.503     albertel 6905:     my $which=&get_rand_alg();
1.803     albertel 6906: 
1.491     albertel 6907:     if (defined(&getCODE())) {
1.675     albertel 6908: 	if ($which eq '64bit5') {
                   6909: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6910: 	} elsif ($which eq '64bit4') {
1.575     albertel 6911: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6912: 	} else {
                   6913: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6914: 	}
1.675     albertel 6915:     } elsif ($which eq '64bit5') {
                   6916: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6917:     } elsif ($which eq '64bit4') {
                   6918: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6919:     } elsif ($which eq '64bit3') {
                   6920: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6921:     } elsif ($which eq '64bit2') {
                   6922: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6923:     } elsif ($which eq '64bit') {
                   6924: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6925:     }
                   6926:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6927: }
                   6928: 
                   6929: sub rndseed_32bit {
                   6930:     my ($symb,$courseid,$domain,$username)=@_;
                   6931:     {
                   6932: 	use integer;
                   6933: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6934: 	my $symbseed=numval($symb) << 22;
                   6935: 	my $namechck=unpack("%32C*",$username) << 17;
                   6936: 	my $nameseed=numval($username) << 12;
                   6937: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6938: 	my $courseseed=unpack("%32C*",$courseid);
                   6939: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6940: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6941: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6942: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6943: 	return $num;
                   6944:     }
                   6945: }
                   6946: 
                   6947: sub rndseed_64bit {
                   6948:     my ($symb,$courseid,$domain,$username)=@_;
                   6949:     {
                   6950: 	use integer;
                   6951: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6952: 	my $symbseed=numval($symb) << 10;
                   6953: 	my $namechck=unpack("%32S*",$username);
                   6954: 	
                   6955: 	my $nameseed=numval($username) << 21;
                   6956: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6957: 	my $courseseed=unpack("%32S*",$courseid);
                   6958: 	
                   6959: 	my $num1=$symbchck+$symbseed+$namechck;
                   6960: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6961: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6962: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6963: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6964: 	return "$num1,$num2";
1.155     albertel 6965:     }
1.366     albertel 6966: }
                   6967: 
1.443     albertel 6968: sub rndseed_64bit2 {
                   6969:     my ($symb,$courseid,$domain,$username)=@_;
                   6970:     {
                   6971: 	use integer;
                   6972: 	# strings need to be an even # of cahracters long, it it is odd the
                   6973:         # last characters gets thrown away
                   6974: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6975: 	my $symbseed=numval($symb) << 10;
                   6976: 	my $namechck=unpack("%32S*",$username.' ');
                   6977: 	
                   6978: 	my $nameseed=numval($username) << 21;
1.501     albertel 6979: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6980: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6981: 	
                   6982: 	my $num1=$symbchck+$symbseed+$namechck;
                   6983: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6984: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6985: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6986: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6987: 	return "$num1,$num2";
                   6988:     }
                   6989: }
                   6990: 
                   6991: sub rndseed_64bit3 {
                   6992:     my ($symb,$courseid,$domain,$username)=@_;
                   6993:     {
                   6994: 	use integer;
                   6995: 	# strings need to be an even # of cahracters long, it it is odd the
                   6996:         # last characters gets thrown away
                   6997: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6998: 	my $symbseed=numval2($symb) << 10;
                   6999: 	my $namechck=unpack("%32S*",$username.' ');
                   7000: 	
                   7001: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7002: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7003: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7004: 	
                   7005: 	my $num1=$symbchck+$symbseed+$namechck;
                   7006: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7007: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7008: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7009: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7010: 	
1.503     albertel 7011: 	return "$num1:$num2";
1.443     albertel 7012:     }
                   7013: }
                   7014: 
1.575     albertel 7015: sub rndseed_64bit4 {
                   7016:     my ($symb,$courseid,$domain,$username)=@_;
                   7017:     {
                   7018: 	use integer;
                   7019: 	# strings need to be an even # of cahracters long, it it is odd the
                   7020:         # last characters gets thrown away
                   7021: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7022: 	my $symbseed=numval3($symb) << 10;
                   7023: 	my $namechck=unpack("%32S*",$username.' ');
                   7024: 	
                   7025: 	my $nameseed=numval3($username) << 21;
                   7026: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7027: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7028: 	
                   7029: 	my $num1=$symbchck+$symbseed+$namechck;
                   7030: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7031: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7032: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7033: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7034: 	
                   7035: 	return "$num1:$num2";
                   7036:     }
                   7037: }
                   7038: 
1.675     albertel 7039: sub rndseed_64bit5 {
                   7040:     my ($symb,$courseid,$domain,$username)=@_;
                   7041:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7042:     return "$num1:$num2";
                   7043: }
                   7044: 
1.366     albertel 7045: sub rndseed_CODE_64bit {
                   7046:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7047:     {
1.366     albertel 7048: 	use integer;
1.443     albertel 7049: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7050: 	my $symbseed=numval2($symb);
1.491     albertel 7051: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7052: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7053: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7054: 	my $num1=$symbseed+$CODEchck;
                   7055: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7056: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7057: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7058: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7059: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7060: 	return "$num1:$num2";
1.366     albertel 7061:     }
                   7062: }
                   7063: 
1.575     albertel 7064: sub rndseed_CODE_64bit4 {
                   7065:     my ($symb,$courseid,$domain,$username)=@_;
                   7066:     {
                   7067: 	use integer;
                   7068: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7069: 	my $symbseed=numval3($symb);
                   7070: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7071: 	my $CODEseed=numval3(&getCODE());
                   7072: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7073: 	my $num1=$symbseed+$CODEchck;
                   7074: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7075: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7076: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7077: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7078: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7079: 	return "$num1:$num2";
                   7080:     }
                   7081: }
                   7082: 
1.675     albertel 7083: sub rndseed_CODE_64bit5 {
                   7084:     my ($symb,$courseid,$domain,$username)=@_;
                   7085:     my $code = &getCODE();
                   7086:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7087:     return "$num1:$num2";
                   7088: }
                   7089: 
1.366     albertel 7090: sub setup_random_from_rndseed {
                   7091:     my ($rndseed)=@_;
1.503     albertel 7092:     if ($rndseed =~/([,:])/) {
                   7093: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7094: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7095:     } else {
                   7096: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7097:     }
1.36      albertel 7098: }
                   7099: 
1.474     albertel 7100: sub latest_receipt_algorithm_id {
1.835     albertel 7101:     return 'receipt3';
1.474     albertel 7102: }
                   7103: 
1.480     www      7104: sub recunique {
                   7105:     my $fucourseid=shift;
                   7106:     my $unique;
1.835     albertel 7107:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7108: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7109: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7110:     } else {
                   7111: 	$unique=$perlvar{'lonReceipt'};
                   7112:     }
                   7113:     return unpack("%32C*",$unique);
                   7114: }
                   7115: 
                   7116: sub recprefix {
                   7117:     my $fucourseid=shift;
                   7118:     my $prefix;
1.835     albertel 7119:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7120: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7121: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7122:     } else {
                   7123: 	$prefix=$perlvar{'lonHostID'};
                   7124:     }
                   7125:     return unpack("%32C*",$prefix);
                   7126: }
                   7127: 
1.76      www      7128: sub ireceipt {
1.474     albertel 7129:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7130: 
                   7131:     my $return =&recprefix($fucourseid).'-';
                   7132: 
                   7133:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7134: 	$env{'request.state'} eq 'construct') {
                   7135: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7136: 	return $return;
                   7137:     }
                   7138: 
1.76      www      7139:     my $cuname=unpack("%32C*",$funame);
                   7140:     my $cudom=unpack("%32C*",$fudom);
                   7141:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7142:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7143:     my $cunique=&recunique($fucourseid);
1.474     albertel 7144:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7145:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7146: 
1.790     albertel 7147: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7148: 			       
                   7149: 	$return.= ($cunique%$cuname+
                   7150: 		   $cunique%$cudom+
                   7151: 		   $cusymb%$cuname+
                   7152: 		   $cusymb%$cudom+
                   7153: 		   $cucourseid%$cuname+
                   7154: 		   $cucourseid%$cudom+
                   7155: 		   $cpart%$cuname+
                   7156: 		   $cpart%$cudom);
                   7157:     } else {
                   7158: 	$return.= ($cunique%$cuname+
                   7159: 		   $cunique%$cudom+
                   7160: 		   $cusymb%$cuname+
                   7161: 		   $cusymb%$cudom+
                   7162: 		   $cucourseid%$cuname+
                   7163: 		   $cucourseid%$cudom);
                   7164:     }
                   7165:     return $return;
1.76      www      7166: }
                   7167: 
                   7168: sub receipt {
1.474     albertel 7169:     my ($part)=@_;
1.790     albertel 7170:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7171:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7172: }
1.260     ng       7173: 
1.790     albertel 7174: sub whichuser {
                   7175:     my ($passedsymb)=@_;
                   7176:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7177:     if (defined($env{'form.grade_symb'})) {
                   7178: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7179: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7180: 	if (!$allowed &&
                   7181: 	    exists($env{'request.course.sec'}) &&
                   7182: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7183: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7184: 			      '/'.$env{'request.course.sec'});
                   7185: 	}
                   7186: 	if ($allowed) {
                   7187: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7188: 	    $courseid=$tmp_courseid;
                   7189: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7190: 	    ($name)=&get_env_multiple('form.grade_username');
                   7191: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7192: 	}
                   7193:     }
                   7194:     if (!$passedsymb) {
                   7195: 	$symb=&symbread();
                   7196:     } else {
                   7197: 	$symb=$passedsymb;
                   7198:     }
                   7199:     $courseid=$env{'request.course.id'};
                   7200:     $domain=$env{'user.domain'};
                   7201:     $name=$env{'user.name'};
                   7202:     if ($name eq 'public' && $domain eq 'public') {
                   7203: 	if (!defined($env{'form.username'})) {
                   7204: 	    $env{'form.username'}.=time.rand(10000000);
                   7205: 	}
                   7206: 	$name.=$env{'form.username'};
                   7207:     }
                   7208:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7209: 
                   7210: }
                   7211: 
1.36      albertel 7212: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7213: # returns either the contents of the file or 
                   7214: # -1 if the file doesn't exist
1.481     raeburn  7215: #
                   7216: # if the target is a file that was uploaded via DOCS, 
                   7217: # a check will be made to see if a current copy exists on the local server,
                   7218: # if it does this will be served, otherwise a copy will be retrieved from
                   7219: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7220: # the local server.   
1.472     albertel 7221: 
1.36      albertel 7222: sub getfile {
1.538     albertel 7223:     my ($file) = @_;
1.609     banghart 7224:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7225:     &repcopy($file);
                   7226:     return &readfile($file);
                   7227: }
                   7228: 
                   7229: sub repcopy_userfile {
                   7230:     my ($file)=@_;
1.609     banghart 7231:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7232:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7233:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7234: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7235:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7236:     if (-e "$file") {
1.828     www      7237: # we already have a local copy, check it out
1.538     albertel 7238: 	my @fileinfo = stat($file);
1.828     www      7239: 	my $rtncode;
                   7240: 	my $info;
1.538     albertel 7241: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7242: 	if ($lwpresp ne 'ok') {
1.828     www      7243: # there is no such file anymore, even though we had a local copy
1.482     albertel 7244: 	    if ($rtncode eq '404') {
1.538     albertel 7245: 		unlink($file);
1.482     albertel 7246: 	    }
                   7247: 	    return -1;
                   7248: 	}
                   7249: 	if ($info < $fileinfo[9]) {
1.828     www      7250: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7251: 	    return 'ok';
1.828     www      7252: 	} else {
                   7253: # the file is outdated, get rid of it
                   7254: 	    unlink($file);
1.482     albertel 7255: 	}
1.828     www      7256:     }
                   7257: # one way or the other, at this point, we don't have the file
                   7258: # construct the correct path for the file
                   7259:     my @parts = ($cdom,$cnum); 
                   7260:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7261: 	push @parts, split(/\//,$1);
                   7262:     }
                   7263:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7264:     foreach my $part (@parts) {
                   7265: 	$path .= '/'.$part;
                   7266: 	if (!-e $path) {
                   7267: 	    mkdir($path,0770);
1.482     albertel 7268: 	}
                   7269:     }
1.828     www      7270: # now the path exists for sure
                   7271: # get a user agent
                   7272:     my $ua=new LWP::UserAgent;
                   7273:     my $transferfile=$file.'.in.transfer';
                   7274: # FIXME: this should flock
                   7275:     if (-e $transferfile) { return 'ok'; }
                   7276:     my $request;
                   7277:     $uri=~s/^\///;
1.838     albertel 7278:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7279:     my $response=$ua->request($request,$transferfile);
                   7280: # did it work?
                   7281:     if ($response->is_error()) {
                   7282: 	unlink($transferfile);
                   7283: 	&logthis("Userfile repcopy failed for $uri");
                   7284: 	return -1;
                   7285:     }
                   7286: # worked, rename the transfer file
                   7287:     rename($transferfile,$file);
1.607     raeburn  7288:     return 'ok';
1.481     raeburn  7289: }
                   7290: 
1.517     albertel 7291: sub tokenwrapper {
                   7292:     my $uri=shift;
1.552     albertel 7293:     $uri=~s|^http\://([^/]+)||;
                   7294:     $uri=~s|^/||;
1.620     albertel 7295:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7296:     my $token=$1;
1.552     albertel 7297:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7298:     if ($udom && $uname && $file) {
                   7299: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7300:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7301:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7302:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7303:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7304:     } else {
                   7305:         return '/adm/notfound.html';
                   7306:     }
                   7307: }
                   7308: 
1.828     www      7309: # call with reqtype HEAD: get last modification time
                   7310: # call with reqtype GET: get the file contents
                   7311: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7312: #
1.481     raeburn  7313: sub getuploaded {
                   7314:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7315:     $uri=~s/^\///;
1.838     albertel 7316:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7317:     my $ua=new LWP::UserAgent;
                   7318:     my $request=new HTTP::Request($reqtype,$uri);
                   7319:     my $response=$ua->request($request);
                   7320:     $$rtncode = $response->code;
1.482     albertel 7321:     if (! $response->is_success()) {
                   7322: 	return 'failed';
                   7323:     }      
                   7324:     if ($reqtype eq 'HEAD') {
1.486     www      7325: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7326:     } elsif ($reqtype eq 'GET') {
                   7327: 	$$info = $response->content;
1.472     albertel 7328:     }
1.482     albertel 7329:     return 'ok';
1.36      albertel 7330: }
                   7331: 
1.481     raeburn  7332: sub readfile {
                   7333:     my $file = shift;
                   7334:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7335:     my $fh;
                   7336:     open($fh,"<$file");
                   7337:     my $a='';
1.800     albertel 7338:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7339:     return $a;
                   7340: }
                   7341: 
1.36      albertel 7342: sub filelocation {
1.590     banghart 7343:     my ($dir,$file) = @_;
                   7344:     my $location;
                   7345:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7346: 
                   7347:     if ($file =~ m-^/adm/-) {
                   7348: 	$file=~s-^/adm/wrapper/-/-;
                   7349: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7350:     }
1.590     banghart 7351:     if ($file=~m:^/~:) { # is a contruction space reference
                   7352:         $location = $file;
                   7353:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7354:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7355: 	# is a correct contruction space reference
                   7356:         $location = $file;
1.609     banghart 7357:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7358:         my ($udom,$uname,$filename)=
1.811     albertel 7359:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7360:         my $home=&homeserver($uname,$udom);
                   7361:         my $is_me=0;
                   7362:         my @ids=&current_machine_ids();
                   7363:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7364:         if ($is_me) {
1.740     www      7365:   	    $location=&propath($udom,$uname).
1.590     banghart 7366:   	      '/userfiles/'.$filename;
                   7367:         } else {
                   7368:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7369:   	      $udom.'/'.$uname.'/'.$filename;
                   7370:         }
                   7371:     } else {
                   7372:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7373:         $file=~s:^/res/:/:;
                   7374:         if ( !( $file =~ m:^/:) ) {
                   7375:             $location = $dir. '/'.$file;
                   7376:         } else {
                   7377:             $location = '/home/httpd/html/res'.$file;
                   7378:         }
1.59      albertel 7379:     }
1.590     banghart 7380:     $location=~s://+:/:g; # remove duplicate /
                   7381:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7382:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7383:     return $location;
1.46      www      7384: }
1.36      albertel 7385: 
1.46      www      7386: sub hreflocation {
                   7387:     my ($dir,$file)=@_;
1.460     albertel 7388:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7389: 	$file=filelocation($dir,$file);
1.700     albertel 7390:     } elsif ($file=~m-^/adm/-) {
                   7391: 	$file=~s-^/adm/wrapper/-/-;
                   7392: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7393:     }
                   7394:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7395: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7396:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7397: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7398:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7399: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7400: 	    -/uploaded/$1/$2/-x;
1.46      www      7401:     }
1.462     albertel 7402:     return $file;
1.465     albertel 7403: }
                   7404: 
                   7405: sub current_machine_domains {
1.838     albertel 7406:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7407:     my @domains;
1.838     albertel 7408:     my %hostname = &all_hostnames();
1.465     albertel 7409:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7410: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7411: 	if ($hostname eq $name) {
1.844     albertel 7412: 	    push(@domains,&host_domain($id));
1.465     albertel 7413: 	}
                   7414:     }
                   7415:     return @domains;
                   7416: }
                   7417: 
                   7418: sub current_machine_ids {
1.838     albertel 7419:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7420:     my @ids;
1.838     albertel 7421:     my %hostname = &all_hostnames();
1.465     albertel 7422:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7423: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7424: 	if ($hostname eq $name) {
                   7425: 	    push(@ids,$id);
                   7426: 	}
                   7427:     }
                   7428:     return @ids;
1.31      www      7429: }
                   7430: 
1.824     raeburn  7431: sub additional_machine_domains {
                   7432:     my @domains;
                   7433:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7434:     while( my $line = <$fh>) {
                   7435:         $line =~ s/\s//g;
                   7436:         push(@domains,$line);
                   7437:     }
                   7438:     return @domains;
                   7439: }
                   7440: 
                   7441: sub default_login_domain {
                   7442:     my $domain = $perlvar{'lonDefDomain'};
                   7443:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7444:     foreach my $posdom (&current_machine_domains(),
                   7445:                         &additional_machine_domains()) {
                   7446:         if (lc($posdom) eq lc($testdomain)) {
                   7447:             $domain=$posdom;
                   7448:             last;
                   7449:         }
                   7450:     }
                   7451:     return $domain;
                   7452: }
                   7453: 
1.31      www      7454: # ------------------------------------------------------------- Declutters URLs
                   7455: 
                   7456: sub declutter {
                   7457:     my $thisfn=shift;
1.569     albertel 7458:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7459:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7460:     $thisfn=~s/^\///;
1.697     albertel 7461:     $thisfn=~s|^adm/wrapper/||;
                   7462:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7463:     $thisfn=~s/^res\///;
1.235     www      7464:     $thisfn=~s/\?.+$//;
1.268     www      7465:     return $thisfn;
                   7466: }
                   7467: 
                   7468: # ------------------------------------------------------------- Clutter up URLs
                   7469: 
                   7470: sub clutter {
                   7471:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7472:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7473:        $thisfn='/res'.$thisfn; 
                   7474:     }
1.694     albertel 7475:     if ($thisfn !~m|/adm|) {
1.695     albertel 7476: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7477: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7478: 	} else {
                   7479: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7480: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7481: 	    if ($embstyle eq 'ssi'
                   7482: 		|| ($embstyle eq 'hdn')
                   7483: 		|| ($embstyle eq 'rat')
                   7484: 		|| ($embstyle eq 'prv')
                   7485: 		|| ($embstyle eq 'ign')) {
                   7486: 		#do nothing with these
                   7487: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7488: 		|| ($embstyle eq 'emb')
                   7489: 		|| ($embstyle eq 'wrp')) {
                   7490: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7491: 	    } elsif ($embstyle eq 'unk'
                   7492: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7493: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7494: 	    } else {
1.718     www      7495: #		&logthis("Got a blank emb style");
1.695     albertel 7496: 	    }
1.694     albertel 7497: 	}
                   7498:     }
1.31      www      7499:     return $thisfn;
1.12      www      7500: }
                   7501: 
1.787     albertel 7502: sub clutter_with_no_wrapper {
                   7503:     my $uri = &clutter(shift);
                   7504:     if ($uri =~ m-^/adm/-) {
                   7505: 	$uri =~ s-^/adm/wrapper/-/-;
                   7506: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7507:     }
                   7508:     return $uri;
                   7509: }
                   7510: 
1.557     albertel 7511: sub freeze_escape {
                   7512:     my ($value)=@_;
                   7513:     if (ref($value)) {
                   7514: 	$value=&nfreeze($value);
                   7515: 	return '__FROZEN__'.&escape($value);
                   7516:     }
                   7517:     return &escape($value);
                   7518: }
                   7519: 
1.11      www      7520: 
1.557     albertel 7521: sub thaw_unescape {
                   7522:     my ($value)=@_;
                   7523:     if ($value =~ /^__FROZEN__/) {
                   7524: 	substr($value,0,10,undef);
                   7525: 	$value=&unescape($value);
                   7526: 	return &thaw($value);
                   7527:     }
                   7528:     return &unescape($value);
                   7529: }
                   7530: 
1.436     albertel 7531: sub correct_line_ends {
                   7532:     my ($result)=@_;
                   7533:     $$result =~s/\r\n/\n/mg;
                   7534:     $$result =~s/\r/\n/mg;
1.415     albertel 7535: }
1.1       albertel 7536: # ================================================================ Main Program
                   7537: 
1.184     www      7538: sub goodbye {
1.204     albertel 7539:    &logthis("Starting Shut down");
1.443     albertel 7540: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7541:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7542: #converted
1.599     albertel 7543: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7544:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7545: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7546: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7547: #1.1 only
1.599     albertel 7548: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7549: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7550: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7551: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7552:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7553:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7554:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7555:    &flushcourselogs();
                   7556:    &logthis("Shutting down");
                   7557: }
                   7558: 
1.179     www      7559: BEGIN {
1.228     harris41 7560: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7561:     unless ($readit) {
1.217     harris41 7562: {
1.781     raeburn  7563:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7564:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7565: }
1.1       albertel 7566: 
1.327     albertel 7567: # ------------------------------------------------------------ Read domain file
                   7568: {
1.846     albertel 7569:     my %domain;
                   7570: 
1.448     albertel 7571:     my $fh;
                   7572:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7573: 	while (my $line = <$fh>) {
1.846     albertel 7574: 	    next if ($line =~ /^(\#|\s*$ )/);
1.403     www      7575: 
1.846     albertel 7576: 	    chomp($line);
                   7577: 	    my ($name,@elements) =  split(/:/,$line,9);
                   7578: 	    my %this_domain;
                   7579: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7580: 			       'lang_def', 'city', 'longi', 'lati',
                   7581: 			       'primary') {
                   7582: 		$this_domain{$field} = shift(@elements);
                   7583: 	    }
                   7584: 	    $domain{$name} = \%this_domain;
1.327     albertel 7585: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7586: 	}
1.327     albertel 7587:     }
1.448     albertel 7588:     close ($fh);
1.846     albertel 7589: 
                   7590:     sub domain {
                   7591: 	my ($name,$what) = @_;
                   7592: 	return if ( !exists($domain{$name}) );
                   7593: 
                   7594: 	if (!$what) {
                   7595: 	    return $domain{$name}{'description'};
                   7596: 	}
                   7597: 	return $domain{$name}{$what};
                   7598:     }
1.327     albertel 7599: }
                   7600: 
                   7601: 
1.1       albertel 7602: # ------------------------------------------------------------- Read hosts file
                   7603: {
1.838     albertel 7604:     my %hostname;
1.844     albertel 7605:     my %hostdom;
1.845     albertel 7606:     my %libserv;
1.448     albertel 7607:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7608: 
                   7609:     while (my $configline=<$config>) {
1.303     matthew  7610:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7611:        chomp($configline);
1.595     albertel 7612:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7613:        $name=~s/\s//g;
1.595     albertel 7614:        if ($id && $domain && $role && $name) {
1.252     albertel 7615: 	 $hostname{$id}=$name;
                   7616: 	 $hostdom{$id}=$domain;
                   7617: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7618:        }
1.1       albertel 7619:     }
1.448     albertel 7620:     close($config);
1.619     albertel 7621:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7622:     #&get_iphost();
1.838     albertel 7623: 
                   7624:     sub hostname {
                   7625: 	my ($lonid) = @_;
                   7626: 	return $hostname{$lonid};
                   7627:     }
1.845     albertel 7628: 
1.838     albertel 7629:     sub all_hostnames {
                   7630: 	return %hostname;
                   7631:     }
1.845     albertel 7632: 
                   7633:     sub is_library {
                   7634: 	return exists($libserv{$_[0]});
                   7635:     }
                   7636: 
                   7637:     sub all_library {
                   7638: 	return %libserv;
                   7639:     }
                   7640: 
1.841     albertel 7641:     sub get_servers {
                   7642: 	my ($domain,$type) = @_;
                   7643: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7644: 	                                          : %hostname;
                   7645: 	my %result;
1.842     albertel 7646: 	if (ref($domain) eq 'ARRAY') {
                   7647: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7648: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7649: 		    $result{$host} = $hostname;
                   7650: 		}
                   7651: 	    }
                   7652: 	} else {
                   7653: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7654: 		if ($hostdom{$host} eq $domain) {
                   7655: 		    $result{$host} = $hostname;
                   7656: 		}
1.841     albertel 7657: 	    }
                   7658: 	}
                   7659: 	return %result;
                   7660:     }
1.845     albertel 7661: 
1.844     albertel 7662:     sub host_domain {
                   7663: 	my ($lonid) = @_;
                   7664: 	return $hostdom{$lonid};
                   7665:     }
                   7666: 
1.841     albertel 7667:     sub all_domains {
                   7668: 	my %seen;
                   7669: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7670: 	return @uniq;
                   7671:     }
1.1       albertel 7672: }
                   7673: 
1.847   ! albertel 7674: { 
        !          7675:     my %iphost;
        !          7676:     sub get_hosts_from_ip {
        !          7677: 	my ($ip) = @_;
        !          7678: 	my %iphosts = &get_iphost();
        !          7679: 	if (ref($iphosts{$ip})) {
        !          7680: 	    return @{$iphosts{$ip}};
        !          7681: 	}
        !          7682: 	return;
1.839     albertel 7683:     }
1.847   ! albertel 7684:     
        !          7685:     sub get_iphost {
        !          7686: 	if (%iphost) { return %iphost; }
        !          7687: 	my %name_to_ip;
        !          7688: 	my %hostname = &all_hostnames();
        !          7689: 	foreach my $id (keys(%hostname)) {
        !          7690: 	    my $name=$hostname{$id};
        !          7691: 	    my $ip;
        !          7692: 	    if (!exists($name_to_ip{$name})) {
        !          7693: 		$ip = gethostbyname($name);
        !          7694: 		if (!$ip || length($ip) ne 4) {
        !          7695: 		    &logthis("Skipping host $id name $name no IP found");
        !          7696: 		    next;
        !          7697: 		}
        !          7698: 		$ip=inet_ntoa($ip);
        !          7699: 		$name_to_ip{$name} = $ip;
        !          7700: 	    } else {
        !          7701: 		$ip = $name_to_ip{$name};
1.653     albertel 7702: 	    }
1.847   ! albertel 7703: 	    push(@{$iphost{$ip}},$id);
1.598     albertel 7704: 	}
1.847   ! albertel 7705: 	return %iphost;
1.598     albertel 7706:     }
                   7707: }
                   7708: 
1.1       albertel 7709: # ------------------------------------------------------ Read spare server file
                   7710: {
1.448     albertel 7711:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7712: 
                   7713:     while (my $configline=<$config>) {
                   7714:        chomp($configline);
1.284     matthew  7715:        if ($configline) {
1.784     albertel 7716: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7717: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7718: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7719:        }
                   7720:     }
1.448     albertel 7721:     close($config);
1.1       albertel 7722: }
1.11      www      7723: # ------------------------------------------------------------ Read permissions
                   7724: {
1.448     albertel 7725:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7726: 
                   7727:     while (my $configline=<$config>) {
1.448     albertel 7728: 	chomp($configline);
                   7729: 	if ($configline) {
                   7730: 	    my ($role,$perm)=split(/ /,$configline);
                   7731: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7732: 	}
1.11      www      7733:     }
1.448     albertel 7734:     close($config);
1.11      www      7735: }
                   7736: 
                   7737: # -------------------------------------------- Read plain texts for permissions
                   7738: {
1.448     albertel 7739:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7740: 
                   7741:     while (my $configline=<$config>) {
1.448     albertel 7742: 	chomp($configline);
                   7743: 	if ($configline) {
1.742     raeburn  7744: 	    my ($short,@plain)=split(/:/,$configline);
                   7745:             %{$prp{$short}} = ();
                   7746: 	    if (@plain > 0) {
                   7747:                 $prp{$short}{'std'} = $plain[0];
                   7748:                 for (my $i=1; $i<@plain; $i++) {
                   7749:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7750:                 }
                   7751:             }
1.448     albertel 7752: 	}
1.135     www      7753:     }
1.448     albertel 7754:     close($config);
1.135     www      7755: }
                   7756: 
                   7757: # ---------------------------------------------------------- Read package table
                   7758: {
1.448     albertel 7759:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7760: 
                   7761:     while (my $configline=<$config>) {
1.483     albertel 7762: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7763: 	chomp($configline);
                   7764: 	my ($short,$plain)=split(/:/,$configline);
                   7765: 	my ($pack,$name)=split(/\&/,$short);
                   7766: 	if ($plain ne '') {
                   7767: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7768: 	    $packagetab{$short}=$plain; 
                   7769: 	}
1.11      www      7770:     }
1.448     albertel 7771:     close($config);
1.329     matthew  7772: }
                   7773: 
                   7774: # ------------- set up temporary directory
                   7775: {
                   7776:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7777: 
1.11      www      7778: }
                   7779: 
1.794     albertel 7780: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7781: 				'compress_threshold'=> 20_000,
                   7782:  			        });
1.185     www      7783: 
1.281     www      7784: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7785: $dumpcount=0;
1.22      www      7786: 
1.163     harris41 7787: &logtouch();
1.672     albertel 7788: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7789: $readit=1;
1.564     albertel 7790:     {
                   7791: 	use integer;
                   7792: 	my $test=(2**32)+1;
1.568     albertel 7793: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7794: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7795:     }
1.195     www      7796: }
1.1       albertel 7797: }
1.179     www      7798: 
1.1       albertel 7799: 1;
1.191     harris41 7800: __END__
                   7801: 
1.243     albertel 7802: =pod
                   7803: 
1.191     harris41 7804: =head1 NAME
                   7805: 
1.243     albertel 7806: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7807: 
                   7808: =head1 SYNOPSIS
                   7809: 
1.243     albertel 7810: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7811: 
                   7812:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7813: 
1.243     albertel 7814: Common parameters:
                   7815: 
                   7816: =over 4
                   7817: 
                   7818: =item *
                   7819: 
                   7820: $uname : an internal username (if $cname expecting a course Id specifically)
                   7821: 
                   7822: =item *
                   7823: 
                   7824: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7825: 
                   7826: =item *
                   7827: 
                   7828: $symb : a resource instance identifier
                   7829: 
                   7830: =item *
                   7831: 
                   7832: $namespace : the name of a .db file that contains the data needed or
                   7833: being set.
                   7834: 
                   7835: =back
                   7836: 
1.394     bowersj2 7837: =head1 OVERVIEW
1.191     harris41 7838: 
1.394     bowersj2 7839: lonnet provides subroutines which interact with the
                   7840: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7841: about classes, users, and resources.
1.243     albertel 7842: 
                   7843: For many of these objects you can also use this to store data about
                   7844: them or modify them in various ways.
1.191     harris41 7845: 
1.394     bowersj2 7846: =head2 Symbs
1.191     harris41 7847: 
1.394     bowersj2 7848: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7849: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7850: map, the resource number of the resource in the map, and the URL of
                   7851: the resource itself. The latter is somewhat redundant, but might help
                   7852: if maps change.
                   7853: 
                   7854: An example is
                   7855: 
                   7856:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7857: 
                   7858: The respective map entry is
                   7859: 
                   7860:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7861:   title="Problem 2">
                   7862:  </resource>
                   7863: 
                   7864: Symbs are used by the random number generator, as well as to store and
                   7865: restore data specific to a certain instance of for example a problem.
                   7866: 
                   7867: =head2 Storing And Retrieving Data
                   7868: 
                   7869: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7870: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7871: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7872: is is the non-critical message twin of cstore. These functions are for
                   7873: handlers to store a perl hash to a user's permanent data space in an
                   7874: easy manner, and to retrieve it again on another call. It is expected
                   7875: that a handler would use this once at the beginning to retrieve data,
                   7876: and then again once at the end to send only the new data back.
                   7877: 
                   7878: The data is stored in the user's data directory on the user's
                   7879: homeserver under the ID of the course.
                   7880: 
                   7881: The hash that is returned by restore will have all of the previous
                   7882: value for all of the elements of the hash.
                   7883: 
                   7884: Example:
                   7885: 
                   7886:  #creating a hash
                   7887:  my %hash;
                   7888:  $hash{'foo'}='bar';
                   7889: 
                   7890:  #storing it
                   7891:  &Apache::lonnet::cstore(\%hash);
                   7892: 
                   7893:  #changing a value
                   7894:  $hash{'foo'}='notbar';
                   7895: 
                   7896:  #adding a new value
                   7897:  $hash{'bar'}='foo';
                   7898:  &Apache::lonnet::cstore(\%hash);
                   7899: 
                   7900:  #retrieving the hash
                   7901:  my %history=&Apache::lonnet::restore();
                   7902: 
                   7903:  #print the hash
                   7904:  foreach my $key (sort(keys(%history))) {
                   7905:    print("\%history{$key} = $history{$key}");
                   7906:  }
                   7907: 
                   7908: Will print out:
1.191     harris41 7909: 
1.394     bowersj2 7910:  %history{1:foo} = bar
                   7911:  %history{1:keys} = foo:timestamp
                   7912:  %history{1:timestamp} = 990455579
                   7913:  %history{2:bar} = foo
                   7914:  %history{2:foo} = notbar
                   7915:  %history{2:keys} = foo:bar:timestamp
                   7916:  %history{2:timestamp} = 990455580
                   7917:  %history{bar} = foo
                   7918:  %history{foo} = notbar
                   7919:  %history{timestamp} = 990455580
                   7920:  %history{version} = 2
                   7921: 
                   7922: Note that the special hash entries C<keys>, C<version> and
                   7923: C<timestamp> were added to the hash. C<version> will be equal to the
                   7924: total number of versions of the data that have been stored. The
                   7925: C<timestamp> attribute will be the UNIX time the hash was
                   7926: stored. C<keys> is available in every historical section to list which
                   7927: keys were added or changed at a specific historical revision of a
                   7928: hash.
                   7929: 
                   7930: B<Warning>: do not store the hash that restore returns directly. This
                   7931: will cause a mess since it will restore the historical keys as if the
                   7932: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7933: 
1.394     bowersj2 7934: Calling convention:
1.191     harris41 7935: 
1.394     bowersj2 7936:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7937:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7938: 
1.394     bowersj2 7939: For more detailed information, see lonnet specific documentation.
1.191     harris41 7940: 
1.394     bowersj2 7941: =head1 RETURN MESSAGES
1.191     harris41 7942: 
1.394     bowersj2 7943: =over 4
1.191     harris41 7944: 
1.394     bowersj2 7945: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7946: 
1.394     bowersj2 7947: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7948: when the connection is brought back up
1.191     harris41 7949: 
1.394     bowersj2 7950: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7951: for later delivery
1.191     harris41 7952: 
1.394     bowersj2 7953: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7954: 
1.394     bowersj2 7955: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7956: that was requested
1.191     harris41 7957: 
1.243     albertel 7958: =back
1.191     harris41 7959: 
1.243     albertel 7960: =head1 PUBLIC SUBROUTINES
1.191     harris41 7961: 
1.243     albertel 7962: =head2 Session Environment Functions
1.191     harris41 7963: 
1.243     albertel 7964: =over 4
1.191     harris41 7965: 
1.394     bowersj2 7966: =item * 
                   7967: X<appenv()>
                   7968: B<appenv(%hash)>: the value of %hash is written to
                   7969: the user envirnoment file, and will be restored for each access this
1.620     albertel 7970: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7971: process
1.191     harris41 7972: 
                   7973: =item *
1.394     bowersj2 7974: X<delenv()>
                   7975: B<delenv($regexp)>: removes all items from the session
                   7976: environment file that matches the regular expression in $regexp. The
1.620     albertel 7977: values are also delted from the current processes %env.
1.191     harris41 7978: 
1.795     albertel 7979: =item * get_env_multiple($name) 
                   7980: 
                   7981: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7982: values may be defined and end up as an array ref.
                   7983: 
                   7984: returns an array of values
                   7985: 
1.243     albertel 7986: =back
                   7987: 
                   7988: =head2 User Information
1.191     harris41 7989: 
1.243     albertel 7990: =over 4
1.191     harris41 7991: 
                   7992: =item *
1.394     bowersj2 7993: X<queryauthenticate()>
                   7994: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7995: authentication scheme
                   7996: 
                   7997: =item *
1.394     bowersj2 7998: X<authenticate()>
                   7999: B<authenticate($uname,$upass,$udom)>: try to
                   8000: authenticate user from domain's lib servers (first use the current
                   8001: one). C<$upass> should be the users password.
1.191     harris41 8002: 
                   8003: =item *
1.394     bowersj2 8004: X<homeserver()>
                   8005: B<homeserver($uname,$udom)>: find the server which has
                   8006: the user's directory and files (there must be only one), this caches
                   8007: the answer, and also caches if there is a borken connection.
1.191     harris41 8008: 
                   8009: =item *
1.394     bowersj2 8010: X<idget()>
                   8011: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8012: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8013: username, and only 1 username per ID in a specific domain) (returns
                   8014: hash: id=>name,id=>name)
1.191     harris41 8015: 
                   8016: =item *
1.394     bowersj2 8017: X<idrget()>
                   8018: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8019: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8020: 
                   8021: =item *
1.394     bowersj2 8022: X<idput()>
                   8023: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8024: 
                   8025: =item *
1.394     bowersj2 8026: X<rolesinit()>
                   8027: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8028: 
                   8029: =item *
1.551     albertel 8030: X<getsection()>
                   8031: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8032: course $cname, return section name/number or '' for "not in course"
                   8033: and '-1' for "no section"
                   8034: 
                   8035: =item *
1.394     bowersj2 8036: X<userenvironment()>
                   8037: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8038: passed in @what from the requested user's environment, returns a hash
                   8039: 
                   8040: =back
                   8041: 
                   8042: =head2 User Roles
                   8043: 
                   8044: =over 4
                   8045: 
                   8046: =item *
                   8047: 
1.810     raeburn  8048: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8049:  F: full access
                   8050:  U,I,K: authentication modes (cxx only)
                   8051:  '': forbidden
                   8052:  1: user needs to choose course
                   8053:  2: browse allowed
1.766     albertel 8054:  A: passphrase authentication needed
1.243     albertel 8055: 
                   8056: =item *
                   8057: 
                   8058: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8059: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8060: and course level
                   8061: 
                   8062: =item *
                   8063: 
                   8064: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8065: explanation of a user role term
                   8066: 
1.832     raeburn  8067: =item *
                   8068: 
1.834     albertel 8069: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
                   8070: optional.  Returns a hash of a user's roles, with keys set to
                   8071: colon-sparated $uname,$udom,and $role, and value set to
                   8072: colon-separated start and end times for the role. If no username and
                   8073: domain are specified, will default to current user/domain. Types,
                   8074: roles, and roledoms are references to arrays, of role statuses
                   8075: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
                   8076: of the roles which can be used to restrict the list if roles
                   8077: reported. If no array ref is provided for types, will default to
                   8078: return only active roles.
                   8079: 
1.243     albertel 8080: =back
                   8081: 
                   8082: =head2 User Modification
                   8083: 
                   8084: =over 4
                   8085: 
                   8086: =item *
                   8087: 
                   8088: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8089: user for the level given by URL.  Optional start and end dates (leave empty
                   8090: string or zero for "no date")
1.191     harris41 8091: 
                   8092: =item *
                   8093: 
1.243     albertel 8094: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8095: change a users, password, possible return values are: ok,
                   8096: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8097: refused
1.191     harris41 8098: 
                   8099: =item *
                   8100: 
1.243     albertel 8101: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8102: 
                   8103: =item *
                   8104: 
1.243     albertel 8105: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8106: modify user
1.191     harris41 8107: 
                   8108: =item *
                   8109: 
1.286     matthew  8110: modifystudent
                   8111: 
                   8112: modify a students enrollment and identification information.
                   8113: The course id is resolved based on the current users environment.  
                   8114: This means the envoking user must be a course coordinator or otherwise
                   8115: associated with a course.
                   8116: 
1.297     matthew  8117: This call is essentially a wrapper for lonnet::modifyuser and
                   8118: lonnet::modify_student_enrollment
1.286     matthew  8119: 
                   8120: Inputs: 
                   8121: 
                   8122: =over 4
                   8123: 
                   8124: =item B<$udom> Students loncapa domain
                   8125: 
                   8126: =item B<$uname> Students loncapa login name
                   8127: 
                   8128: =item B<$uid> Students id/student number
                   8129: 
                   8130: =item B<$umode> Students authentication mode
                   8131: 
                   8132: =item B<$upass> Students password
                   8133: 
                   8134: =item B<$first> Students first name
                   8135: 
                   8136: =item B<$middle> Students middle name
                   8137: 
                   8138: =item B<$last> Students last name
                   8139: 
                   8140: =item B<$gene> Students generation
                   8141: 
                   8142: =item B<$usec> Students section in course
                   8143: 
                   8144: =item B<$end> Unix time of the roles expiration
                   8145: 
                   8146: =item B<$start> Unix time of the roles start date
                   8147: 
                   8148: =item B<$forceid> If defined, allow $uid to be changed
                   8149: 
                   8150: =item B<$desiredhome> server to use as home server for student
                   8151: 
                   8152: =back
1.297     matthew  8153: 
                   8154: =item *
                   8155: 
                   8156: modify_student_enrollment
                   8157: 
                   8158: Change a students enrollment status in a class.  The environment variable
                   8159: 'role.request.course' must be defined for this function to proceed.
                   8160: 
                   8161: Inputs:
                   8162: 
                   8163: =over 4
                   8164: 
                   8165: =item $udom, students domain
                   8166: 
                   8167: =item $uname, students name
                   8168: 
                   8169: =item $uid, students user id
                   8170: 
                   8171: =item $first, students first name
                   8172: 
                   8173: =item $middle
                   8174: 
                   8175: =item $last
                   8176: 
                   8177: =item $gene
                   8178: 
                   8179: =item $usec
                   8180: 
                   8181: =item $end
                   8182: 
                   8183: =item $start
                   8184: 
                   8185: =back
                   8186: 
1.191     harris41 8187: 
                   8188: =item *
                   8189: 
1.243     albertel 8190: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8191: custom role; give a custom role to a user for the level given by URL.  Specify
                   8192: name and domain of role author, and role name
1.191     harris41 8193: 
                   8194: =item *
                   8195: 
1.243     albertel 8196: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8197: 
                   8198: =item *
                   8199: 
1.243     albertel 8200: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8201: 
                   8202: =back
                   8203: 
                   8204: =head2 Course Infomation
                   8205: 
                   8206: =over 4
1.191     harris41 8207: 
                   8208: =item *
                   8209: 
1.631     albertel 8210: coursedescription($courseid) : returns a hash of information about the
                   8211: specified course id, including all environment settings for the
                   8212: course, the description of the course will be in the hash under the
                   8213: key 'description'
1.191     harris41 8214: 
                   8215: =item *
                   8216: 
1.624     albertel 8217: resdata($name,$domain,$type,@which) : request for current parameter
                   8218: setting for a specific $type, where $type is either 'course' or 'user',
                   8219: @what should be a list of parameters to ask about. This routine caches
                   8220: answers for 5 minutes.
1.243     albertel 8221: 
                   8222: =back
                   8223: 
                   8224: =head2 Course Modification
                   8225: 
                   8226: =over 4
1.191     harris41 8227: 
                   8228: =item *
                   8229: 
1.243     albertel 8230: writecoursepref($courseid,%prefs) : write preferences (environment
                   8231: database) for a course
1.191     harris41 8232: 
                   8233: =item *
                   8234: 
1.243     albertel 8235: createcourse($udom,$description,$url) : make/modify course
                   8236: 
                   8237: =back
                   8238: 
                   8239: =head2 Resource Subroutines
                   8240: 
                   8241: =over 4
1.191     harris41 8242: 
                   8243: =item *
                   8244: 
1.243     albertel 8245: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8246: 
                   8247: =item *
                   8248: 
1.243     albertel 8249: repcopy($filename) : subscribes to the requested file, and attempts to
                   8250: replicate from the owning library server, Might return
1.607     raeburn  8251: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8252: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8253: resource. Expects the local filesystem pathname
                   8254: (/home/httpd/html/res/....)
                   8255: 
                   8256: =back
                   8257: 
                   8258: =head2 Resource Information
                   8259: 
                   8260: =over 4
1.191     harris41 8261: 
                   8262: =item *
                   8263: 
1.243     albertel 8264: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8265: a vairety of different possible values, $varname should be a request
                   8266: string, and the other parameters can be used to specify who and what
                   8267: one is asking about.
                   8268: 
                   8269: Possible values for $varname are environment.lastname (or other item
                   8270: from the envirnment hash), user.name (or someother aspect about the
                   8271: user), resource.0.maxtries (or some other part and parameter of a
                   8272: resource)
1.204     albertel 8273: 
                   8274: =item *
                   8275: 
1.243     albertel 8276: directcondval($number) : get current value of a condition; reads from a state
                   8277: string
1.204     albertel 8278: 
                   8279: =item *
                   8280: 
1.243     albertel 8281: condval($condidx) : value of condition index based on state
1.204     albertel 8282: 
                   8283: =item *
                   8284: 
1.243     albertel 8285: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8286: resource's metadata, $what should be either a specific key, or either
                   8287: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8288: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8289: 
                   8290: this function automatically caches all requests
1.191     harris41 8291: 
                   8292: =item *
                   8293: 
1.243     albertel 8294: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8295: network of library servers; returns file handle of where SQL and regex results
                   8296: will be stored for query
1.191     harris41 8297: 
                   8298: =item *
                   8299: 
1.243     albertel 8300: symbread($filename) : return symbolic list entry (filename argument optional);
                   8301: returns the data handle
1.191     harris41 8302: 
                   8303: =item *
                   8304: 
1.243     albertel 8305: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8306: a possible symb for the URL in $thisfn, and if is an encryypted
                   8307: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8308: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8309: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8310: 
1.191     harris41 8311: 
                   8312: =item *
                   8313: 
1.243     albertel 8314: symbclean($symb) : removes versions numbers from a symb, returns the
                   8315: cleaned symb
1.191     harris41 8316: 
                   8317: =item *
                   8318: 
1.243     albertel 8319: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8320: course map, user must be in a course for it to work.
1.191     harris41 8321: 
                   8322: =item *
                   8323: 
1.243     albertel 8324: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8325: 
                   8326: =item *
                   8327: 
1.243     albertel 8328: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8329: a random seed, all arguments are optional, if they aren't sent it uses the
                   8330: environment to derive them. Note: if symb isn't sent and it can't get one
                   8331: from &symbread it will use the current time as its return value
1.191     harris41 8332: 
                   8333: =item *
                   8334: 
1.243     albertel 8335: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8336: unfakeable, receipt
1.191     harris41 8337: 
                   8338: =item *
                   8339: 
1.620     albertel 8340: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8341: 
                   8342: =item *
                   8343: 
1.243     albertel 8344: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8345: 
                   8346: =item *
                   8347: 
1.243     albertel 8348: 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 8349: 
                   8350: =item *
                   8351: 
1.243     albertel 8352: 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 8353: 
                   8354: =item *
                   8355: 
1.243     albertel 8356: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8357: 
                   8358: =item *
                   8359: 
1.243     albertel 8360: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8361: forcing spreadsheet to reevaluate the resource scores next time.
                   8362: 
                   8363: =back
                   8364: 
                   8365: =head2 Storing/Retreiving Data
                   8366: 
                   8367: =over 4
1.191     harris41 8368: 
                   8369: =item *
                   8370: 
1.243     albertel 8371: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8372: for this url; hashref needs to be given and should be a \%hashname; the
                   8373: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8374: be derived from the env
1.191     harris41 8375: 
                   8376: =item *
                   8377: 
1.243     albertel 8378: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8379: uses critical subroutine
1.191     harris41 8380: 
                   8381: =item *
                   8382: 
1.243     albertel 8383: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8384: all args are optional
1.191     harris41 8385: 
                   8386: =item *
                   8387: 
1.717     albertel 8388: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8389: dumps the complete (or key matching regexp) namespace into a hash
                   8390: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8391: normally &store()ed into
                   8392: 
                   8393: $range should be either an integer '100' (give me the first 100
                   8394:                                            matching records)
                   8395:               or be  two integers sperated by a - with no spaces
                   8396:                  '30-50' (give me the 30th through the 50th matching
                   8397:                           records)
                   8398: 
                   8399: 
                   8400: =item *
                   8401: 
                   8402: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8403: replaces a &store() version of data with a replacement set of data
                   8404: for a particular resource in a namespace passed in the $storehash hash 
                   8405: reference
                   8406: 
                   8407: =item *
                   8408: 
1.243     albertel 8409: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8410: works very similar to store/cstore, but all data is stored in a
                   8411: temporary location and can be reset using tmpreset, $storehash should
                   8412: be a hash reference, returns nothing on success
1.191     harris41 8413: 
                   8414: =item *
                   8415: 
1.243     albertel 8416: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8417: similar to restore, but all data is stored in a temporary location and
                   8418: can be reset using tmpreset. Returns a hash of values on success,
                   8419: error string otherwise.
1.191     harris41 8420: 
                   8421: =item *
                   8422: 
1.243     albertel 8423: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8424: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8425: 
                   8426: =item *
                   8427: 
1.243     albertel 8428: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8429: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8430: 
                   8431: =item *
                   8432: 
1.243     albertel 8433: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8434: namesp ($udom and $uname are optional)
1.191     harris41 8435: 
                   8436: =item *
                   8437: 
1.702     albertel 8438: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8439: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8440: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8441: 
1.702     albertel 8442: $range should be either an integer '100' (give me the first 100
                   8443:                                            matching records)
                   8444:               or be  two integers sperated by a - with no spaces
                   8445:                  '30-50' (give me the 30th through the 50th matching
                   8446:                           records)
1.449     matthew  8447: =item *
                   8448: 
                   8449: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8450: $store can be a scalar, an array reference, or if the amount to be 
                   8451: incremented is > 1, a hash reference.
                   8452: 
                   8453: ($udom and $uname are optional)
1.191     harris41 8454: 
                   8455: =item *
                   8456: 
1.243     albertel 8457: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8458: ($udom and $uname are optional)
1.191     harris41 8459: 
                   8460: =item *
                   8461: 
1.243     albertel 8462: cput($namespace,$storehash,$udom,$uname) : critical put
                   8463: ($udom and $uname are optional)
1.191     harris41 8464: 
                   8465: =item *
                   8466: 
1.748     albertel 8467: newput($namespace,$storehash,$udom,$uname) :
                   8468: 
                   8469: Attempts to store the items in the $storehash, but only if they don't
                   8470: currently exist, if this succeeds you can be certain that you have 
                   8471: successfully created a new key value pair in the $namespace db.
                   8472: 
                   8473: 
                   8474: Args:
                   8475:  $namespace: name of database to store values to
                   8476:  $storehash: hashref to store to the db
                   8477:  $udom: (optional) domain of user containing the db
                   8478:  $uname: (optional) name of user caontaining the db
                   8479: 
                   8480: Returns:
                   8481:  'ok' -> succeeded in storing all keys of $storehash
                   8482:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8483:                         least <key> already existed in the db (other
                   8484:                         requested keys may also already exist)
                   8485:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8486:  'con_lost' -> unable to contact request server
                   8487:  'refused' -> action was not allowed by remote machine
                   8488: 
                   8489: 
                   8490: =item *
                   8491: 
1.243     albertel 8492: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8493: reference filled in from namesp (encrypts the return communication)
                   8494: ($udom and $uname are optional)
1.191     harris41 8495: 
                   8496: =item *
                   8497: 
1.243     albertel 8498: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8499: critical subroutine
                   8500: 
1.806     raeburn  8501: =item *
                   8502: 
                   8503: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8504: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8505: 
                   8506: =item *
                   8507: 
                   8508: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8509: 
1.243     albertel 8510: =back
                   8511: 
                   8512: =head2 Network Status Functions
                   8513: 
                   8514: =over 4
1.191     harris41 8515: 
                   8516: =item *
                   8517: 
                   8518: dirlist($uri) : return directory list based on URI
                   8519: 
                   8520: =item *
                   8521: 
1.243     albertel 8522: spareserver() : find server with least workload from spare.tab
                   8523: 
                   8524: =back
                   8525: 
                   8526: =head2 Apache Request
                   8527: 
                   8528: =over 4
1.191     harris41 8529: 
                   8530: =item *
                   8531: 
1.243     albertel 8532: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8533: localhost, posts hash
                   8534: 
                   8535: =back
                   8536: 
                   8537: =head2 Data to String to Data
                   8538: 
                   8539: =over 4
1.191     harris41 8540: 
                   8541: =item *
                   8542: 
1.243     albertel 8543: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8544: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8545: 
                   8546: =item *
                   8547: 
1.243     albertel 8548: hashref2str($hashref) : convert a hashref into a string complete with
                   8549: escaping and '=' and '&' separators, supports elements that are
                   8550: arrayrefs and hashrefs
1.191     harris41 8551: 
                   8552: =item *
                   8553: 
1.243     albertel 8554: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8555: with escaping and '&' separators, supports elements that are arrayrefs
                   8556: and hashrefs
1.191     harris41 8557: 
                   8558: =item *
                   8559: 
1.243     albertel 8560: str2hash($string) : convert string to hash using unescaping and
                   8561: splitting on '=' and '&', supports elements that are arrayrefs and
                   8562: hashrefs
1.191     harris41 8563: 
                   8564: =item *
                   8565: 
1.243     albertel 8566: str2array($string) : convert string to hash using unescaping and
                   8567: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8568: 
                   8569: =back
                   8570: 
                   8571: =head2 Logging Routines
                   8572: 
                   8573: =over 4
                   8574: 
                   8575: These routines allow one to make log messages in the lonnet.log and
                   8576: lonnet.perm logfiles.
1.191     harris41 8577: 
                   8578: =item *
                   8579: 
1.243     albertel 8580: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8581: 
                   8582: =item *
                   8583: 
1.243     albertel 8584: logthis() : append message to the normal lonnet.log file, it gets
                   8585: preiodically rolled over and deleted.
1.191     harris41 8586: 
                   8587: =item *
                   8588: 
1.243     albertel 8589: logperm() : append a permanent message to lonnet.perm.log, this log
                   8590: file never gets deleted by any automated portion of the system, only
                   8591: messages of critical importance should go in here.
                   8592: 
                   8593: =back
                   8594: 
                   8595: =head2 General File Helper Routines
                   8596: 
                   8597: =over 4
1.191     harris41 8598: 
                   8599: =item *
                   8600: 
1.481     raeburn  8601: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8602: (a) files in /uploaded
                   8603:   (i) If a local copy of the file exists - 
                   8604:       compares modification date of local copy with last-modified date for 
                   8605:       definitive version stored on home server for course. If local copy is 
                   8606:       stale, requests a new version from the home server and stores it. 
                   8607:       If the original has been removed from the home server, then local copy 
                   8608:       is unlinked.
                   8609:   (ii) If local copy does not exist -
                   8610:       requests the file from the home server and stores it. 
                   8611:   
                   8612:   If $caller is 'uploadrep':  
                   8613:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8614:     for request for files originally uploaded via DOCS. 
                   8615:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8616:   
                   8617:   Otherwise:
                   8618:      This indicates a call from the content generation phase of the request.
                   8619:      -  returns the entire contents of the file or -1.
                   8620:      
                   8621: (b) files in /res
                   8622:    - returns the entire contents of a file or -1; 
                   8623:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8624: 
1.712     albertel 8625: 
                   8626: =item *
                   8627: 
                   8628: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8629:                   reference
                   8630: 
                   8631: returns either a stat() list of data about the file or an empty list
                   8632: if the file doesn't exist or couldn't find out about it (connection
                   8633: problems or user unknown)
                   8634: 
1.191     harris41 8635: =item *
                   8636: 
1.243     albertel 8637: filelocation($dir,$file) : returns file system location of a file
                   8638: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8639: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8640: and a file of ../bob will become /a/bob)
1.191     harris41 8641: 
                   8642: =item *
                   8643: 
                   8644: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8645: filelocation except for hrefs
                   8646: 
                   8647: =item *
                   8648: 
                   8649: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8650: 
1.243     albertel 8651: =back
                   8652: 
1.608     albertel 8653: =head2 Usererfile file routines (/uploaded*)
                   8654: 
                   8655: =over 4
                   8656: 
                   8657: =item *
                   8658: 
                   8659: userfileupload(): main rotine for putting a file in a user or course's
                   8660:                   filespace, arguments are,
                   8661: 
1.620     albertel 8662:  formname - required - this is the name of the element in $env where the
1.608     albertel 8663:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8664:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8665:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8666:  coursedoc - if true, store the file in the course of the active role
                   8667:              of the current user
                   8668:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8669:          if undefined, it will be placed in "unknown"
                   8670: 
                   8671:  (This routine calls clean_filename() to remove any dangerous
                   8672:  characters from the filename, and then calls finuserfileupload() to
                   8673:  complete the transaction)
                   8674: 
                   8675:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8676:  and /adm/notfound.html if unsuccessful
                   8677: 
                   8678: =item *
                   8679: 
                   8680: clean_filename(): routine for cleaing a filename up for storage in
                   8681:                  userfile space, argument is:
                   8682: 
                   8683:  filename - proposed filename
                   8684: 
                   8685: returns: the new clean filename
                   8686: 
                   8687: =item *
                   8688: 
                   8689: finishuserfileupload(): routine that creaes and sends the file to
                   8690: userspace, probably shouldn't be called directly
                   8691: 
                   8692:   docuname: username or courseid of destination for the file
                   8693:   docudom: domain of user/course of destination for the file
                   8694:   formname: same as for userfileupload()
                   8695:   fname: filename (inculding subdirectories) for the file
                   8696: 
                   8697:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8698:  and /adm/notfound.html if unsuccessful
                   8699: 
                   8700: =item *
                   8701: 
                   8702: renameuserfile(): renames an existing userfile to a new name
                   8703: 
                   8704:   Args:
                   8705:    docuname: username or courseid of destination for the file
                   8706:    docudom: domain of user/course of destination for the file
                   8707:    old: current file name (including any subdirs under userfiles)
                   8708:    new: desired file name (including any subdirs under userfiles)
                   8709: 
                   8710: =item *
                   8711: 
                   8712: mkdiruserfile(): creates a directory is a userfiles dir
                   8713: 
                   8714:   Args:
                   8715:    docuname: username or courseid of destination for the file
                   8716:    docudom: domain of user/course of destination for the file
                   8717:    dir: dir to create (including any subdirs under userfiles)
                   8718: 
                   8719: =item *
                   8720: 
                   8721: removeuserfile(): removes a file that exists in userfiles
                   8722: 
                   8723:   Args:
                   8724:    docuname: username or courseid of destination for the file
                   8725:    docudom: domain of user/course of destination for the file
                   8726:    fname: filname to delete (including any subdirs under userfiles)
                   8727: 
                   8728: =item *
                   8729: 
                   8730: removeuploadedurl(): convience function for removeuserfile()
                   8731: 
                   8732:   Args:
                   8733:    url:  a full /uploaded/... url to delete
                   8734: 
1.747     albertel 8735: =item * 
                   8736: 
                   8737: get_portfile_permissions():
                   8738:   Args:
                   8739:     domain: domain of user or course contain the portfolio files
                   8740:     user: name of user or num of course contain the portfolio files
                   8741:   Returns:
                   8742:     hashref of a dump of the proper file_permissions.db
                   8743:    
                   8744: 
                   8745: =item * 
                   8746: 
                   8747: get_access_controls():
                   8748: 
                   8749: Args:
                   8750:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8751:   group: (optional) the group you want the files associated with
                   8752:   file: (optional) the file you want access info on
                   8753: 
                   8754: Returns:
1.749     raeburn  8755:     a hash (keys are file names) of hashes containing
                   8756:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8757:         values are XML containing access control settings (see below) 
1.747     albertel 8758: 
                   8759: Internal notes:
                   8760: 
1.749     raeburn  8761:  access controls are stored in file_permissions.db as key=value pairs.
                   8762:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8763:         where scope -> public,guest,course,group,domains or users.
                   8764:               end -> UNIX time for end of access (0 -> no end date)
                   8765:               start -> UNIX time for start of access
                   8766: 
                   8767:     value -> XML description of access control
                   8768:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8769:             <start></start>
                   8770:             <end></end>
                   8771: 
                   8772:             <password></password>  for scope type = guest
                   8773: 
                   8774:             <domain></domain>     for scope type = course or group
                   8775:             <number></number>
                   8776:             <roles id="">
                   8777:              <role></role>
                   8778:              <access></access>
                   8779:              <section></section>
                   8780:              <group></group>
                   8781:             </roles>
                   8782: 
                   8783:             <dom></dom>         for scope type = domains
                   8784: 
                   8785:             <users>             for scope type = users
                   8786:              <user>
                   8787:               <uname></uname>
                   8788:               <udom></udom>
                   8789:              </user>
                   8790:             </users>
                   8791:            </scope> 
                   8792:               
                   8793:  Access data is also aggregated for each file in an additional key=value pair:
                   8794:  key -> path to file/file_name\0accesscontrol 
                   8795:  value -> reference to hash
                   8796:           hash contains key = value pairs
                   8797:           where key = uniqueID:scope_end_start
                   8798:                 value = UNIX time record was last updated
                   8799: 
                   8800:           Used to improve speed of look-ups of access controls for each file.  
                   8801:  
                   8802:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8803: 
                   8804: modify_access_controls():
                   8805: 
                   8806: Modifies access controls for a portfolio file
                   8807: Args
                   8808: 1. file name
                   8809: 2. reference to hash of required changes,
                   8810: 3. domain
                   8811: 4. username
                   8812:   where domain,username are the domain of the portfolio owner 
                   8813:   (either a user or a course) 
                   8814: 
                   8815: Returns:
                   8816: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8817: 2. result of deletions ('ok' or 'error', with error message).
                   8818: 3. reference to hash of any new or updated access controls.
                   8819: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8820:    key = integer (inbound ID)
                   8821:    value = uniqueID  
1.747     albertel 8822: 
1.608     albertel 8823: =back
                   8824: 
1.243     albertel 8825: =head2 HTTP Helper Routines
                   8826: 
                   8827: =over 4
                   8828: 
1.191     harris41 8829: =item *
                   8830: 
                   8831: escape() : unpack non-word characters into CGI-compatible hex codes
                   8832: 
                   8833: =item *
                   8834: 
                   8835: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8836: 
1.243     albertel 8837: =back
                   8838: 
                   8839: =head1 PRIVATE SUBROUTINES
                   8840: 
                   8841: =head2 Underlying communication routines (Shouldn't call)
                   8842: 
                   8843: =over 4
                   8844: 
                   8845: =item *
                   8846: 
                   8847: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8848: 
                   8849: =item *
                   8850: 
                   8851: reply() : uses subreply to send a message to remote machine, logs all failures
                   8852: 
                   8853: =item *
                   8854: 
                   8855: critical() : passes a critical message to another server; if cannot
                   8856: get through then place message in connection buffer directory and
                   8857: returns con_delayed, if incapable of saving message, returns
                   8858: con_failed
                   8859: 
                   8860: =item *
                   8861: 
                   8862: reconlonc() : tries to reconnect lonc client processes.
                   8863: 
                   8864: =back
                   8865: 
                   8866: =head2 Resource Access Logging
                   8867: 
                   8868: =over 4
                   8869: 
                   8870: =item *
                   8871: 
                   8872: flushcourselogs() : flush (save) buffer logs and access logs
                   8873: 
                   8874: =item *
                   8875: 
                   8876: courselog($what) : save message for course in hash
                   8877: 
                   8878: =item *
                   8879: 
                   8880: courseacclog($what) : save message for course using &courselog().  Perform
                   8881: special processing for specific resource types (problems, exams, quizzes, etc).
                   8882: 
1.191     harris41 8883: =item *
                   8884: 
                   8885: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8886: as a PerlChildExitHandler
1.243     albertel 8887: 
                   8888: =back
                   8889: 
                   8890: =head2 Other
                   8891: 
                   8892: =over 4
                   8893: 
                   8894: =item *
                   8895: 
                   8896: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8897: 
                   8898: =back
                   8899: 
                   8900: =cut

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