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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.840   ! albertel    4: # $Id: lonnet.pm,v 1.839 2007/03/02 23:43:24 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.838     albertel   38: qw(%perlvar %badServerCache %iphost %spareid %hostdom 
1.599     albertel   39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.807     albertel   56: use LONCAPA qw(:DEFAULT :match);
1.740     www        57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.838     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.838     albertel  192:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
1.836     www       204:     &logthis("Trying to reconnect lonc");
1.1       albertel  205:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  206:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  207: 	my $loncpid=<$fh>;
                    208:         chomp($loncpid);
                    209:         if (kill 0 => $loncpid) {
                    210: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    211:             kill USR1 => $loncpid;
                    212:             sleep 1;
1.836     www       213:          } else {
1.12      www       214: 	    &logthis(
1.672     albertel  215:                "<font color=\"blue\">WARNING:".
1.12      www       216:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  217:         }
                    218:     } else {
1.836     www       219: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  220:     }
                    221: }
                    222: 
                    223: # ------------------------------------------------------ Critical communication
1.12      www       224: 
1.1       albertel  225: sub critical {
                    226:     my ($cmd,$server)=@_;
1.838     albertel  227:     unless (&hostname($server)) {
1.672     albertel  228:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       229:                " Critical message to unknown server ($server)</font>");
                    230:         return 'no_such_host';
                    231:     }
1.1       albertel  232:     my $answer=reply($cmd,$server);
                    233:     if ($answer eq 'con_lost') {
                    234: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  235: 	my $answer=reply($cmd,$server);
1.1       albertel  236:         if ($answer eq 'con_lost') {
                    237:             my $now=time;
                    238:             my $middlename=$cmd;
1.5       www       239:             $middlename=substr($middlename,0,16);
1.1       albertel  240:             $middlename=~s/\W//g;
                    241:             my $dfilename=
1.305     www       242:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    243:             $dumpcount++;
1.1       albertel  244:             {
1.448     albertel  245: 		my $dfh;
                    246: 		if (open($dfh,">$dfilename")) {
                    247: 		    print $dfh "$cmd\n"; 
                    248: 		    close($dfh);
                    249: 		}
1.1       albertel  250:             }
                    251:             sleep 2;
                    252:             my $wcmd='';
                    253:             {
1.448     albertel  254: 		my $dfh;
                    255: 		if (open($dfh,"<$dfilename")) {
                    256: 		    $wcmd=<$dfh>; 
                    257: 		    close($dfh);
                    258: 		}
1.1       albertel  259:             }
                    260:             chomp($wcmd);
1.7       www       261:             if ($wcmd eq $cmd) {
1.672     albertel  262: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       263:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  264:                 &logperm("D:$server:$cmd");
                    265: 	        return 'con_delayed';
                    266:             } else {
1.672     albertel  267:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       268:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  269:                 &logperm("F:$server:$cmd");
                    270:                 return 'con_failed';
                    271:             }
                    272:         }
                    273:     }
                    274:     return $answer;
1.405     albertel  275: }
                    276: 
1.755     albertel  277: # ------------------------------------------- check if return value is an error
                    278: 
                    279: sub error {
                    280:     my ($result) = @_;
1.756     albertel  281:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  282: 	if ($2 == 2) { return undef; }
                    283: 	return $1;
                    284:     }
                    285:     return undef;
                    286: }
                    287: 
1.783     albertel  288: sub convert_and_load_session_env {
                    289:     my ($lonidsdir,$handle)=@_;
                    290:     my @profile;
                    291:     {
                    292: 	open(my $idf,"$lonidsdir/$handle.id");
                    293: 	flock($idf,LOCK_SH);
                    294: 	@profile=<$idf>;
                    295: 	close($idf);
                    296:     }
                    297:     my %temp_env;
                    298:     foreach my $line (@profile) {
1.786     albertel  299: 	if ($line !~ m/=/) {
                    300: 	    return 0;
                    301: 	}
1.783     albertel  302: 	chomp($line);
                    303: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    304: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    305:     }
                    306:     unlink("$lonidsdir/$handle.id");
                    307:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    308: 	    0640)) {
                    309: 	%disk_env = %temp_env;
                    310: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    311: 	untie(%disk_env);
                    312:     }
1.786     albertel  313:     return 1;
1.783     albertel  314: }
                    315: 
1.374     www       316: # ------------------------------------------- Transfer profile into environment
1.780     albertel  317: my $env_loaded;
                    318: sub transfer_profile_to_env {
1.788     albertel  319:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    320:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       321: 
1.720     albertel  322:     if (!defined($lonidsdir)) {
                    323: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    324:     }
                    325:     if (!defined($handle)) {
                    326:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    327:     }
                    328: 
1.786     albertel  329:     my $convert;
                    330:     {
                    331:     	open(my $idf,"$lonidsdir/$handle.id");
                    332: 	flock($idf,LOCK_SH);
                    333: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    334: 		&GDBM_READER(),0640)) {
                    335: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    336: 	    untie(%disk_env);
                    337: 	} else {
                    338: 	    $convert = 1;
                    339: 	}
                    340:     }
                    341:     if ($convert) {
                    342: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    343: 	    &logthis("Failed to load session, or convert session.");
                    344: 	}
1.374     www       345:     }
1.783     albertel  346: 
1.786     albertel  347:     my %remove;
1.783     albertel  348:     while ( my $envname = each(%env) ) {
1.433     matthew   349:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    350:             if ($time < time-300) {
1.783     albertel  351:                 $remove{$key}++;
1.433     matthew   352:             }
                    353:         }
                    354:     }
1.783     albertel  355: 
1.619     albertel  356:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  357:     $env_loaded=1;
1.783     albertel  358:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   359:         &delenv($expired_key);
1.374     www       360:     }
1.1       albertel  361: }
                    362: 
1.830     albertel  363: sub timed_flock {
                    364:     my ($file,$lock_type) = @_;
                    365:     my $failed=0;
                    366:     eval {
                    367: 	local $SIG{__DIE__}='DEFAULT';
                    368: 	local $SIG{ALRM}=sub {
                    369: 	    $failed=1;
                    370: 	    die("failed lock");
                    371: 	};
                    372: 	alarm(13);
                    373: 	flock($file,$lock_type);
                    374: 	alarm(0);
                    375:     };
                    376:     if ($failed) {
                    377: 	return undef;
                    378:     } else {
                    379: 	return 1;
                    380:     }
                    381: }
                    382: 
1.5       www       383: # ---------------------------------------------------------- Append Environment
                    384: 
                    385: sub appenv {
1.6       www       386:     my %newenv=@_;
1.692     albertel  387:     foreach my $key (keys(%newenv)) {
                    388: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  389:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  390:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       391:                 .'</font>');
1.692     albertel  392: 	    delete($newenv{$key});
1.35      www       393:         } else {
1.692     albertel  394:             $env{$key}=$newenv{$key};
1.35      www       395:         }
1.191     harris41  396:     }
1.830     albertel  397:     open(my $env_file,$env{'user.environment'});
                    398:     if (&timed_flock($env_file,LOCK_EX)
                    399: 	&&
                    400: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    401: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  402: 	while (my ($key,$value) = each(%newenv)) {
                    403: 	    $disk_env{$key} = $value;
1.448     albertel  404: 	}
1.783     albertel  405: 	untie(%disk_env);
1.56      www       406:     }
                    407:     return 'ok';
                    408: }
                    409: # ----------------------------------------------------- Delete from Environment
                    410: 
                    411: sub delenv {
                    412:     my $delthis=shift;
                    413:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  414:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       415:                 "Attempt to delete from environment ".$delthis);
                    416:         return 'error';
                    417:     }
1.830     albertel  418:     open(my $env_file,$env{'user.environment'});
                    419:     if (&timed_flock($env_file,LOCK_EX)
                    420: 	&&
                    421: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    422: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  423: 	foreach my $key (keys(%disk_env)) {
                    424: 	    if ($key=~/^$delthis/) { 
1.619     albertel  425:                 delete($env{$key});
1.783     albertel  426:                 delete($disk_env{$key});
1.473     matthew   427:             }
1.448     albertel  428: 	}
1.783     albertel  429: 	untie(%disk_env);
1.5       www       430:     }
                    431:     return 'ok';
1.369     albertel  432: }
                    433: 
1.790     albertel  434: sub get_env_multiple {
                    435:     my ($name) = @_;
                    436:     my @values;
                    437:     if (defined($env{$name})) {
                    438:         # exists is it an array
                    439:         if (ref($env{$name})) {
                    440:             @values=@{ $env{$name} };
                    441:         } else {
                    442:             $values[0]=$env{$name};
                    443:         }
                    444:     }
                    445:     return(@values);
                    446: }
                    447: 
1.369     albertel  448: # ------------------------------------------ Find out current server userload
                    449: # there is a copy in lond
                    450: sub userload {
                    451:     my $numusers=0;
                    452:     {
                    453: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    454: 	my $filename;
                    455: 	my $curtime=time;
                    456: 	while ($filename=readdir(LONIDS)) {
                    457: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  458: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  459: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  460: 	}
                    461: 	closedir(LONIDS);
                    462:     }
                    463:     my $userloadpercent=0;
                    464:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    465:     if ($maxuserload) {
1.371     albertel  466: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  467:     }
1.372     albertel  468:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  469:     return $userloadpercent;
1.283     www       470: }
                    471: 
                    472: # ------------------------------------------ Fight off request when overloaded
                    473: 
                    474: sub overloaderror {
                    475:     my ($r,$checkserver)=@_;
                    476:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    477:     my $loadavg;
                    478:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  479:        open(my $loadfile,'/proc/loadavg');
1.283     www       480:        $loadavg=<$loadfile>;
                    481:        $loadavg =~ s/\s.*//g;
1.285     matthew   482:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  483:        close($loadfile);
1.283     www       484:     } else {
                    485:        $loadavg=&reply('load',$checkserver);
                    486:     }
1.285     matthew   487:     my $overload=$loadavg-100;
1.283     www       488:     if ($overload>0) {
1.285     matthew   489: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       490:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       491:         return 413;
1.283     www       492:     }    
                    493:     return '';
1.5       www       494: }
1.1       albertel  495: 
                    496: # ------------------------------ Find server with least workload from spare.tab
1.11      www       497: 
1.1       albertel  498: sub spareserver {
1.670     albertel  499:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  500:     my $spare_server;
1.370     albertel  501:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  502:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    503:                                                      :  $userloadpercent;
                    504:     
                    505:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    506: 	($spare_server, $lowest_load) =
                    507: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    508:     }
                    509: 
                    510:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    511: 
                    512:     if (!$found_server) {
                    513: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    514: 	    ($spare_server, $lowest_load) =
                    515: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    516: 	}
                    517:     }
                    518: 
                    519:     if (!$want_server_name) {
1.838     albertel  520: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  521:     }
                    522:     return $spare_server;
                    523: }
                    524: 
                    525: sub compare_server_load {
                    526:     my ($try_server, $spare_server, $lowest_load) = @_;
                    527: 
                    528:     my $loadans     = &reply('load',    $try_server);
                    529:     my $userloadans = &reply('userload',$try_server);
                    530: 
                    531:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    532: 	next; #didn't get a number from the server
                    533:     }
                    534: 
                    535:     my $load;
                    536:     if ($loadans =~ /\d/) {
                    537: 	if ($userloadans =~ /\d/) {
                    538: 	    #both are numbers, pick the bigger one
                    539: 	    $load = ($loadans > $userloadans) ? $loadans 
                    540: 		                              : $userloadans;
1.411     albertel  541: 	} else {
1.784     albertel  542: 	    $load = $loadans;
1.411     albertel  543: 	}
1.784     albertel  544:     } else {
                    545: 	$load = $userloadans;
                    546:     }
                    547: 
                    548:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    549: 	$spare_server = $try_server;
                    550: 	$lowest_load  = $load;
1.370     albertel  551:     }
1.784     albertel  552:     return ($spare_server,$lowest_load);
1.202     matthew   553: }
                    554: # --------------------------------------------- Try to change a user's password
                    555: 
                    556: sub changepass {
1.799     raeburn   557:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   558:     $currentpass = &escape($currentpass);
                    559:     $newpass     = &escape($newpass);
1.799     raeburn   560:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   561: 		       $server);
                    562:     if (! $answer) {
                    563: 	&logthis("No reply on password change request to $server ".
                    564: 		 "by $uname in domain $udom.");
                    565:     } elsif ($answer =~ "^ok") {
                    566:         &logthis("$uname in $udom successfully changed their password ".
                    567: 		 "on $server.");
                    568:     } elsif ($answer =~ "^pwchange_failure") {
                    569: 	&logthis("$uname in $udom was unable to change their password ".
                    570: 		 "on $server.  The action was blocked by either lcpasswd ".
                    571: 		 "or pwchange");
                    572:     } elsif ($answer =~ "^non_authorized") {
                    573:         &logthis("$uname in $udom did not get their password correct when ".
                    574: 		 "attempting to change it on $server.");
                    575:     } elsif ($answer =~ "^auth_mode_error") {
                    576:         &logthis("$uname in $udom attempted to change their password despite ".
                    577: 		 "not being locally or internally authenticated on $server.");
                    578:     } elsif ($answer =~ "^unknown_user") {
                    579:         &logthis("$uname in $udom attempted to change their password ".
                    580: 		 "on $server but were unable to because $server is not ".
                    581: 		 "their home server.");
                    582:     } elsif ($answer =~ "^refused") {
                    583: 	&logthis("$server refused to change $uname in $udom password because ".
                    584: 		 "it was sent an unencrypted request to change the password.");
                    585:     }
                    586:     return $answer;
1.1       albertel  587: }
                    588: 
1.169     harris41  589: # ----------------------- Try to determine user's current authentication scheme
                    590: 
                    591: sub queryauthenticate {
                    592:     my ($uname,$udom)=@_;
1.456     albertel  593:     my $uhome=&homeserver($uname,$udom);
                    594:     if (!$uhome) {
                    595: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    596: 	return 'no_host';
                    597:     }
                    598:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    599:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    600: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  601:     }
1.456     albertel  602:     return $answer;
1.169     harris41  603: }
                    604: 
1.1       albertel  605: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       606: 
1.1       albertel  607: sub authenticate {
                    608:     my ($uname,$upass,$udom)=@_;
1.807     albertel  609:     $upass=&escape($upass);
                    610:     $uname= &LONCAPA::clean_username($uname);
1.836     www       611:     my $uhome=&homeserver($uname,$udom,1);
                    612:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    613: # Maybe the machine was offline and only re-appeared again recently?
                    614:         &reconlonc();
                    615: # One more
                    616: 	my $uhome=&homeserver($uname,$udom,1);
                    617: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    618: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    619: 	}
1.471     albertel  620: 	return 'no_host';
1.1       albertel  621:     }
1.471     albertel  622:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    623:     if ($answer eq 'authorized') {
                    624: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    625: 	return $uhome; 
                    626:     }
                    627:     if ($answer eq 'non_authorized') {
                    628: 	&logthis("User $uname at $udom rejected by $uhome");
                    629: 	return 'no_host'; 
1.9       www       630:     }
1.471     albertel  631:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  632:     return 'no_host';
                    633: }
                    634: 
                    635: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       636: 
1.599     albertel  637: my %homecache;
1.1       albertel  638: sub homeserver {
1.230     stredwic  639:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  640:     my $index="$uname:$udom";
1.426     albertel  641: 
1.599     albertel  642:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  643:     my $tryserver;
                    644:     foreach $tryserver (keys %libserv) {
1.230     stredwic  645:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  646: 		 exists($badServerCache{$tryserver}));
1.1       albertel  647: 	if ($hostdom{$tryserver} eq $udom) {
                    648:            my $answer=reply("home:$udom:$uname",$tryserver);
1.836     www       649:            if ($answer eq 'found') {
                    650:                delete($badServerCache{$tryserver}); 
1.599     albertel  651: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  652:            } elsif ($answer eq 'no_host') {
                    653: 	       $badServerCache{$tryserver}=1;
1.221     matthew   654:            }
1.1       albertel  655:        }
                    656:     }    
                    657:     return 'no_host';
1.70      www       658: }
                    659: 
                    660: # ------------------------------------- Find the usernames behind a list of IDs
                    661: 
                    662: sub idget {
                    663:     my ($udom,@ids)=@_;
                    664:     my %returnhash=();
                    665:     
                    666:     my $tryserver;
                    667:     foreach $tryserver (keys %libserv) {
                    668:        if ($hostdom{$tryserver} eq $udom) {
                    669: 	  my $idlist=join('&',@ids);
                    670:           $idlist=~tr/A-Z/a-z/; 
                    671: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    672:           my @answer=();
1.76      www       673:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       674: 	      @answer=split(/\&/,$reply);
                    675:           }                    ;
                    676:           my $i;
                    677:           for ($i=0;$i<=$#ids;$i++) {
                    678:               if ($answer[$i]) {
                    679: 		  $returnhash{$ids[$i]}=$answer[$i];
                    680:               } 
                    681:           }
                    682:        }
                    683:     }    
                    684:     return %returnhash;
                    685: }
                    686: 
                    687: # ------------------------------------- Find the IDs behind a list of usernames
                    688: 
                    689: sub idrget {
                    690:     my ($udom,@unames)=@_;
                    691:     my %returnhash=();
1.800     albertel  692:     foreach my $uname (@unames) {
                    693:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  694:     }
1.70      www       695:     return %returnhash;
                    696: }
                    697: 
                    698: # ------------------------------- Store away a list of names and associated IDs
                    699: 
                    700: sub idput {
                    701:     my ($udom,%ids)=@_;
                    702:     my %servers=();
1.800     albertel  703:     foreach my $uname (keys(%ids)) {
                    704: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    705:         my $uhom=&homeserver($uname,$udom);
1.70      www       706:         if ($uhom ne 'no_host') {
1.800     albertel  707:             my $id=&escape($ids{$uname});
1.70      www       708:             $id=~tr/A-Z/a-z/;
1.800     albertel  709:             my $esc_unam=&escape($uname);
1.70      www       710: 	    if ($servers{$uhom}) {
1.800     albertel  711: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       712:             } else {
1.800     albertel  713:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       714:             }
                    715:         }
1.191     harris41  716:     }
1.800     albertel  717:     foreach my $server (keys(%servers)) {
                    718:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  719:     }
1.344     www       720: }
                    721: 
1.806     raeburn   722: # ------------------------------------------- get items from domain db files   
                    723: 
                    724: sub get_dom {
                    725:     my ($namespace,$storearr,$udom)=@_;
                    726:     my $items='';
                    727:     foreach my $item (@$storearr) {
                    728:         $items.=&escape($item).'&';
                    729:     }
                    730:     $items=~s/\&$//;
                    731:     if (!$udom) { $udom=$env{'user.domain'}; }
                    732:     if (exists($domain_primary{$udom})) {
                    733:         my $uhome=$domain_primary{$udom};
                    734:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    735:         my @pairs=split(/\&/,$rep);
                    736:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    737:             return @pairs;
                    738:         }
                    739:         my %returnhash=();
                    740:         my $i=0;
                    741:         foreach my $item (@$storearr) {
                    742:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    743:             $i++;
                    744:         }
                    745:         return %returnhash;
                    746:     } else {
                    747:         &logthis("get_dom failed - no primary domain server for $udom");
                    748:     }
                    749: }
                    750: 
                    751: # -------------------------------------------- put items in domain db files 
                    752: 
                    753: sub put_dom {
                    754:     my ($namespace,$storehash,$udom)=@_;
                    755:     if (!$udom) { $udom=$env{'user.domain'}; }
                    756:     if (exists($domain_primary{$udom})) {
                    757:         my $uhome=$domain_primary{$udom};
                    758:         my $items='';
                    759:         foreach my $item (keys(%$storehash)) {
                    760:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    761:         }
                    762:         $items=~s/\&$//;
                    763:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    764:     } else {
                    765:         &logthis("put_dom failed - no primary domain server for $udom");
                    766:     }
                    767: }
                    768: 
1.837     raeburn   769: sub retrieve_inst_usertypes {
                    770:     my ($udom) = @_;
                    771:     my (%returnhash,@order);
                    772:     if (exists($domain_primary{$udom})) {
                    773:         my $uhome=$domain_primary{$udom};
                    774:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    775:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    776:         my @pairs=split(/\&/,$hashitems);
                    777:         foreach my $item (@pairs) {
                    778:             my ($key,$value)=split(/=/,$item,2);
                    779:             $key = &unescape($key);
                    780:             next if ($key =~ /^error: 2 /);
                    781:             $returnhash{$key}=&thaw_unescape($value);
                    782:         }
                    783:         my @esc_order = split(/\&/,$orderitems);
                    784:         foreach my $item (@esc_order) {
                    785:             push(@order,&unescape($item));
                    786:         }
                    787:     } else {
                    788:         &logthis("get_dom failed - no primary domain server for $udom");
                    789:     }
                    790:     return (\%returnhash,\@order);
                    791: }
                    792: 
1.344     www       793: # --------------------------------------------------- Assign a key to a student
                    794: 
                    795: sub assign_access_key {
1.364     www       796: #
                    797: # a valid key looks like uname:udom#comments
                    798: # comments are being appended
                    799: #
1.498     www       800:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    801:     $kdom=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       803:     $knum=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       805:     $cdom=
1.620     albertel  806:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       807:     $cnum=
1.620     albertel  808:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    809:     $udom=$env{'user.name'} unless (defined($udom));
                    810:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       811:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       812:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  813:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       814:                                                   # assigned to this person
                    815:                                                   # - this should not happen,
1.345     www       816:                                                   # unless something went wrong
                    817:                                                   # the first time around
                    818: # ready to assign
1.364     www       819:         $logentry=$1.'; '.$logentry;
1.496     www       820:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       821:                                                  $kdom,$knum) eq 'ok') {
1.345     www       822: # key now belongs to user
1.346     www       823: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       824:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    825:                 &appenv('environment.'.$envkey => $ckey);
                    826:                 return 'ok';
                    827:             } else {
                    828:                 return 
                    829:   'error: Count not permanently assign key, will need to be re-entered later.';
                    830: 	    }
                    831:         } else {
                    832:             return 'error: Could not assign key, try again later.';
                    833:         }
1.364     www       834:     } elsif (!$existing{$ckey}) {
1.345     www       835: # the key does not exist
                    836: 	return 'error: The key does not exist';
                    837:     } else {
                    838: # the key is somebody else's
                    839: 	return 'error: The key is already in use';
                    840:     }
1.344     www       841: }
                    842: 
1.364     www       843: # ------------------------------------------ put an additional comment on a key
                    844: 
                    845: sub comment_access_key {
                    846: #
                    847: # a valid key looks like uname:udom#comments
                    848: # comments are being appended
                    849: #
                    850:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    851:     $cdom=
1.620     albertel  852:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       853:     $cnum=
1.620     albertel  854:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       855:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    856:     if ($existing{$ckey}) {
                    857:         $existing{$ckey}.='; '.$logentry;
                    858: # ready to assign
1.367     www       859:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       860:                                                  $cdom,$cnum) eq 'ok') {
                    861: 	    return 'ok';
                    862:         } else {
                    863: 	    return 'error: Count not store comment.';
                    864:         }
                    865:     } else {
                    866: # the key does not exist
                    867: 	return 'error: The key does not exist';
                    868:     }
                    869: }
                    870: 
1.344     www       871: # ------------------------------------------------------ Generate a set of keys
                    872: 
                    873: sub generate_access_keys {
1.364     www       874:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       875:     $cdom=
1.620     albertel  876:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       877:     $cnum=
1.620     albertel  878:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       879:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       880:     unless (($cdom) && ($cnum)) { return 0; }
                    881:     if ($number>10000) { return 0; }
                    882:     sleep(2); # make sure don't get same seed twice
                    883:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    884:     my $total=0;
                    885:     for (my $i=1;$i<=$number;$i++) {
                    886:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    887:                   sprintf("%lx",int(100000*rand)).'-'.
                    888:                   sprintf("%lx",int(100000*rand));
                    889:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    890:        $newkey=~s/0/h/g; # and also 0 and O
                    891:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    892:        if ($existing{$newkey}) {
                    893:            $i--;
                    894:        } else {
1.364     www       895: 	  if (&put('accesskeys',
                    896:               { $newkey => '# generated '.localtime().
1.620     albertel  897:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       898:                            '; '.$logentry },
                    899: 		   $cdom,$cnum) eq 'ok') {
1.344     www       900:               $total++;
                    901: 	  }
                    902:        }
                    903:     }
1.620     albertel  904:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       905:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    906:     return $total;
                    907: }
                    908: 
                    909: # ------------------------------------------------------- Validate an accesskey
                    910: 
                    911: sub validate_access_key {
                    912:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    913:     $cdom=
1.620     albertel  914:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       915:     $cnum=
1.620     albertel  916:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    917:     $udom=$env{'user.domain'} unless (defined($udom));
                    918:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       919:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  920:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       921: }
                    922: 
                    923: # ------------------------------------- Find the section of student in a course
1.652     albertel  924: sub devalidate_getsection_cache {
                    925:     my ($udom,$unam,$courseid)=@_;
                    926:     my $hashid="$udom:$unam:$courseid";
                    927:     &devalidate_cache_new('getsection',$hashid);
                    928: }
1.298     matthew   929: 
1.815     albertel  930: sub courseid_to_courseurl {
                    931:     my ($courseid) = @_;
                    932:     #already url style courseid
                    933:     return $courseid if ($courseid =~ m{^/});
                    934: 
                    935:     if (exists($env{'course.'.$courseid.'.num'})) {
                    936: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    937: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    938: 	return "/$cdom/$cnum";
                    939:     }
                    940: 
                    941:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    942:     if (exists($courseinfo{'num'})) {
                    943: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    944:     }
                    945: 
                    946:     return undef;
                    947: }
                    948: 
1.298     matthew   949: sub getsection {
                    950:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  951:     my $cachetime=1800;
1.551     albertel  952: 
                    953:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  954:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  955:     if (defined($cached)) { return $result; }
                    956: 
1.298     matthew   957:     my %Pending; 
                    958:     my %Expired;
                    959:     #
                    960:     # Each role can either have not started yet (pending), be active, 
                    961:     #    or have expired.
                    962:     #
                    963:     # If there is an active role, we are done.
                    964:     #
                    965:     # If there is more than one role which has not started yet, 
                    966:     #     choose the one which will start sooner
                    967:     # If there is one role which has not started yet, return it.
                    968:     #
                    969:     # If there is more than one expired role, choose the one which ended last.
                    970:     # If there is a role which has expired, return it.
                    971:     #
1.815     albertel  972:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   973:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    974:     foreach my $key (keys(%roleshash)) {
1.479     albertel  975:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   976:         my $section=$1;
                    977:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   978:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   979:         my $now=time;
1.548     albertel  980:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   981:             $Expired{$end}=$section;
                    982:             next;
                    983:         }
1.548     albertel  984:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   985:             $Pending{$start}=$section;
                    986:             next;
                    987:         }
1.599     albertel  988:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   989:     }
                    990:     #
                    991:     # Presumedly there will be few matching roles from the above
                    992:     # loop and the sorting time will be negligible.
                    993:     if (scalar(keys(%Pending))) {
                    994:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  995:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   996:     } 
                    997:     if (scalar(keys(%Expired))) {
                    998:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    999:         my $time = pop(@sorted);
1.599     albertel 1000:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1001:     }
1.599     albertel 1002:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1003: }
1.70      www      1004: 
1.599     albertel 1005: sub save_cache {
                   1006:     &purge_remembered();
1.722     albertel 1007:     #&Apache::loncommon::validate_page();
1.620     albertel 1008:     undef(%env);
1.780     albertel 1009:     undef($env_loaded);
1.599     albertel 1010: }
1.452     albertel 1011: 
1.599     albertel 1012: my $to_remember=-1;
                   1013: my %remembered;
                   1014: my %accessed;
                   1015: my $kicks=0;
                   1016: my $hits=0;
                   1017: sub devalidate_cache_new {
                   1018:     my ($name,$id,$debug) = @_;
                   1019:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                   1020:     $id=&escape($name.':'.$id);
                   1021:     $memcache->delete($id);
                   1022:     delete($remembered{$id});
                   1023:     delete($accessed{$id});
                   1024: }
                   1025: 
                   1026: sub is_cached_new {
                   1027:     my ($name,$id,$debug) = @_;
                   1028:     $id=&escape($name.':'.$id);
                   1029:     if (exists($remembered{$id})) {
                   1030: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1031: 	$accessed{$id}=[&gettimeofday()];
                   1032: 	$hits++;
                   1033: 	return ($remembered{$id},1);
                   1034:     }
                   1035:     my $value = $memcache->get($id);
                   1036:     if (!(defined($value))) {
                   1037: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1038: 	return (undef,undef);
1.416     albertel 1039:     }
1.599     albertel 1040:     if ($value eq '__undef__') {
                   1041: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1042: 	$value=undef;
                   1043:     }
                   1044:     &make_room($id,$value,$debug);
                   1045:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1046:     return ($value,1);
                   1047: }
                   1048: 
                   1049: sub do_cache_new {
                   1050:     my ($name,$id,$value,$time,$debug) = @_;
                   1051:     $id=&escape($name.':'.$id);
                   1052:     my $setvalue=$value;
                   1053:     if (!defined($setvalue)) {
                   1054: 	$setvalue='__undef__';
                   1055:     }
1.623     albertel 1056:     if (!defined($time) ) {
                   1057: 	$time=600;
                   1058:     }
1.599     albertel 1059:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1060:     $memcache->set($id,$setvalue,$time);
                   1061:     # need to make a copy of $value
                   1062:     #&make_room($id,$value,$debug);
1.599     albertel 1063:     return $value;
                   1064: }
                   1065: 
                   1066: sub make_room {
                   1067:     my ($id,$value,$debug)=@_;
                   1068:     $remembered{$id}=$value;
                   1069:     if ($to_remember<0) { return; }
                   1070:     $accessed{$id}=[&gettimeofday()];
                   1071:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1072:     my $to_kick;
                   1073:     my $max_time=0;
                   1074:     foreach my $other (keys(%accessed)) {
                   1075: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1076: 	    $to_kick=$other;
                   1077: 	    $max_time=&tv_interval($accessed{$other});
                   1078: 	}
                   1079:     }
                   1080:     delete($remembered{$to_kick});
                   1081:     delete($accessed{$to_kick});
                   1082:     $kicks++;
                   1083:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1084:     return;
                   1085: }
                   1086: 
1.599     albertel 1087: sub purge_remembered {
1.604     albertel 1088:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1089:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1090:     undef(%remembered);
                   1091:     undef(%accessed);
1.428     albertel 1092: }
1.70      www      1093: # ------------------------------------- Read an entry from a user's environment
                   1094: 
                   1095: sub userenvironment {
                   1096:     my ($udom,$unam,@what)=@_;
                   1097:     my %returnhash=();
                   1098:     my @answer=split(/\&/,
                   1099:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1100:                       &homeserver($unam,$udom)));
                   1101:     my $i;
                   1102:     for ($i=0;$i<=$#what;$i++) {
                   1103: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1104:     }
                   1105:     return %returnhash;
1.1       albertel 1106: }
                   1107: 
1.617     albertel 1108: # ---------------------------------------------------------- Get a studentphoto
                   1109: sub studentphoto {
                   1110:     my ($udom,$unam,$ext) = @_;
                   1111:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1112:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1113:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1114:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1115:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1116:             } else {
                   1117:                 my ($result,$perm_reqd)=
1.707     albertel 1118: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1119:                 if ($result eq 'ok') {
                   1120:                     if (!($perm_reqd eq 'yes')) {
                   1121:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1122:                     }
                   1123:                 }
                   1124:             }
                   1125:         }
                   1126:     } else {
                   1127:         my ($result,$perm_reqd) = 
1.707     albertel 1128: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1129:         if ($result eq 'ok') {
                   1130:             if (!($perm_reqd eq 'yes')) {
                   1131:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1132:             }
                   1133:         }
                   1134:     }
                   1135:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1136: }
                   1137: 
                   1138: sub retrievestudentphoto {
                   1139:     my ($udom,$unam,$ext,$type) = @_;
                   1140:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1141:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1142:     if ($ret eq 'ok') {
                   1143:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1144:         if ($type eq 'thumbnail') {
                   1145:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1146:         }
                   1147:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1148:         return $tokenurl;
                   1149:     } else {
                   1150:         if ($type eq 'thumbnail') {
                   1151:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1152:         } else { 
                   1153:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1154:         }
1.617     albertel 1155:     }
                   1156: }
                   1157: 
1.263     www      1158: # -------------------------------------------------------------------- New chat
                   1159: 
                   1160: sub chatsend {
1.724     raeburn  1161:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1162:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1163:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1164:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1165:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1166: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1167: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1168: }
                   1169: 
                   1170: # ------------------------------------------ Find current version of a resource
                   1171: 
                   1172: sub getversion {
                   1173:     my $fname=&clutter(shift);
                   1174:     unless ($fname=~/^\/res\//) { return -1; }
                   1175:     return &currentversion(&filelocation('',$fname));
                   1176: }
                   1177: 
                   1178: sub currentversion {
                   1179:     my $fname=shift;
1.599     albertel 1180:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1181:     if (defined($cached)) { return $result; }
1.292     www      1182:     my $author=$fname;
                   1183:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1184:     my ($udom,$uname)=split(/\//,$author);
                   1185:     my $home=homeserver($uname,$udom);
                   1186:     if ($home eq 'no_host') { 
                   1187:         return -1; 
                   1188:     }
                   1189:     my $answer=reply("currentversion:$fname",$home);
                   1190:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1191: 	return -1;
                   1192:     }
1.599     albertel 1193:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1194: }
                   1195: 
1.1       albertel 1196: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1197: 
1.1       albertel 1198: sub subscribe {
                   1199:     my $fname=shift;
1.761     raeburn  1200:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1201:     $fname=~s/[\n\r]//g;
1.1       albertel 1202:     my $author=$fname;
                   1203:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1204:     my ($udom,$uname)=split(/\//,$author);
                   1205:     my $home=homeserver($uname,$udom);
1.335     albertel 1206:     if ($home eq 'no_host') {
                   1207:         return 'not_found';
1.1       albertel 1208:     }
                   1209:     my $answer=reply("sub:$fname",$home);
1.64      www      1210:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1211: 	$answer.=' by '.$home;
                   1212:     }
1.1       albertel 1213:     return $answer;
                   1214: }
                   1215:     
1.8       www      1216: # -------------------------------------------------------------- Replicate file
                   1217: 
                   1218: sub repcopy {
                   1219:     my $filename=shift;
1.23      www      1220:     $filename=~s/\/+/\//g;
1.607     raeburn  1221:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1222:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1223:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1224: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1225: 	return &repcopy_userfile($filename);
                   1226:     }
1.532     albertel 1227:     $filename=~s/[\n\r]//g;
1.8       www      1228:     my $transname="$filename.in.transfer";
1.828     www      1229: # FIXME: this should flock
1.607     raeburn  1230:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1231:     my $remoteurl=subscribe($filename);
1.64      www      1232:     if ($remoteurl =~ /^con_lost by/) {
                   1233: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1234:            return 'unavailable';
1.8       www      1235:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1236: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1237: 	   return 'not_found';
1.64      www      1238:     } elsif ($remoteurl =~ /^rejected by/) {
                   1239: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1240:            return 'forbidden';
1.20      www      1241:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1242:            return 'ok';
1.8       www      1243:     } else {
1.290     www      1244:         my $author=$filename;
                   1245:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1246:         my ($udom,$uname)=split(/\//,$author);
                   1247:         my $home=homeserver($uname,$udom);
                   1248:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1249:            my @parts=split(/\//,$filename);
                   1250:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1251:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1252:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1253: 	       return 'bad_request';
1.8       www      1254:            }
                   1255:            my $count;
                   1256:            for ($count=5;$count<$#parts;$count++) {
                   1257:                $path.="/$parts[$count]";
                   1258:                if ((-e $path)!=1) {
                   1259: 		   mkdir($path,0777);
                   1260:                }
                   1261:            }
                   1262:            my $ua=new LWP::UserAgent;
                   1263:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1264:            my $response=$ua->request($request,$transname);
                   1265:            if ($response->is_error()) {
                   1266: 	       unlink($transname);
                   1267:                my $message=$response->status_line;
1.672     albertel 1268:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1269:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1270:                return 'unavailable';
1.8       www      1271:            } else {
1.16      www      1272: 	       if ($remoteurl!~/\.meta$/) {
                   1273:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1274:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1275:                   if ($mresponse->is_error()) {
                   1276: 		      unlink($filename.'.meta');
                   1277:                       &logthis(
1.672     albertel 1278:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1279:                   }
                   1280: 	       }
1.8       www      1281:                rename($transname,$filename);
1.607     raeburn  1282:                return 'ok';
1.8       www      1283:            }
1.290     www      1284:        }
1.8       www      1285:     }
1.330     www      1286: }
                   1287: 
                   1288: # ------------------------------------------------ Get server side include body
                   1289: sub ssi_body {
1.381     albertel 1290:     my ($filelink,%form)=@_;
1.606     matthew  1291:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1292:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1293:     }
1.330     www      1294:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1295:                                      &ssi($filelink,%form));
1.778     albertel 1296:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1297:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1298:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1299:     return $output;
1.8       www      1300: }
                   1301: 
1.15      www      1302: # --------------------------------------------------------- Server Side Include
                   1303: 
1.782     albertel 1304: sub absolute_url {
                   1305:     my ($host_name) = @_;
                   1306:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1307:     if ($host_name eq '') {
                   1308: 	$host_name = $ENV{'SERVER_NAME'};
                   1309:     }
                   1310:     return $protocol.$host_name;
                   1311: }
                   1312: 
1.15      www      1313: sub ssi {
                   1314: 
1.23      www      1315:     my ($fn,%form)=@_;
1.15      www      1316: 
                   1317:     my $ua=new LWP::UserAgent;
1.23      www      1318:     
                   1319:     my $request;
1.711     albertel 1320: 
                   1321:     $form{'no_update_last_known'}=1;
                   1322: 
1.23      www      1323:     if (%form) {
1.782     albertel 1324:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1325:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1326:     } else {
1.782     albertel 1327:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1328:     }
                   1329: 
1.15      www      1330:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1331:     my $response=$ua->request($request);
                   1332: 
1.324     www      1333:     return $response->content;
                   1334: }
                   1335: 
                   1336: sub externalssi {
                   1337:     my ($url)=@_;
                   1338:     my $ua=new LWP::UserAgent;
                   1339:     my $request=new HTTP::Request('GET',$url);
                   1340:     my $response=$ua->request($request);
1.15      www      1341:     return $response->content;
                   1342: }
1.254     www      1343: 
1.492     albertel 1344: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1345: 
                   1346: sub allowuploaded {
                   1347:     my ($srcurl,$url)=@_;
                   1348:     $url=&clutter(&declutter($url));
                   1349:     my $dir=$url;
                   1350:     $dir=~s/\/[^\/]+$//;
                   1351:     my %httpref=();
                   1352:     my $httpurl=&hreflocation('',$url);
                   1353:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1354:     &Apache::lonnet::appenv(%httpref);
1.254     www      1355: }
1.477     raeburn  1356: 
1.478     albertel 1357: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1358: # input: action, courseID, current domain, intended
1.637     raeburn  1359: #        path to file, source of file, instruction to parse file for objects,
                   1360: #        ref to hash for embedded objects,
                   1361: #        ref to hash for codebase of java objects.
                   1362: #
1.485     raeburn  1363: # output: url to file (if action was uploaddoc), 
                   1364: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1365: #
1.478     albertel 1366: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1367: # course.
1.477     raeburn  1368: #
1.478     albertel 1369: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1370: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1371: #          course's home server.
1.477     raeburn  1372: #
1.478     albertel 1373: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1374: #          be copied from $source (current location) to 
                   1375: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1376: #         and will then be copied to
                   1377: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1378: #         course's home server.
1.485     raeburn  1379: #
1.481     raeburn  1380: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1381: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1382: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1383: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1384: #         in course's home server.
1.637     raeburn  1385: #
1.477     raeburn  1386: 
                   1387: sub process_coursefile {
1.638     albertel 1388:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1389:     my $fetchresult;
1.638     albertel 1390:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1391:     if ($action eq 'propagate') {
1.638     albertel 1392:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1393: 			     $home);
1.481     raeburn  1394:     } else {
1.477     raeburn  1395:         my $fpath = '';
                   1396:         my $fname = $file;
1.478     albertel 1397:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1398:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1399:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1400:         if ($action eq 'copy') {
                   1401:             if ($source eq '') {
                   1402:                 $fetchresult = 'no source file';
                   1403:                 return $fetchresult;
                   1404:             } else {
                   1405:                 my $destination = $filepath.'/'.$fname;
                   1406:                 rename($source,$destination);
                   1407:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1408:                                  $home);
1.481     raeburn  1409:             }
                   1410:         } elsif ($action eq 'uploaddoc') {
                   1411:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1412:             print $fh $env{'form.'.$source};
1.481     raeburn  1413:             close($fh);
1.637     raeburn  1414:             if ($parser eq 'parse') {
                   1415:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1416:                 unless ($parse_result eq 'ok') {
                   1417:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1418:                 }
                   1419:             }
1.477     raeburn  1420:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1421:                                  $home);
1.481     raeburn  1422:             if ($fetchresult eq 'ok') {
                   1423:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1424:             } else {
                   1425:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1426:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1427:                 return '/adm/notfound.html';
                   1428:             }
1.477     raeburn  1429:         }
                   1430:     }
1.485     raeburn  1431:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1432:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1433:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1434:     }
                   1435:     return $fetchresult;
                   1436: }
                   1437: 
1.637     raeburn  1438: sub build_filepath {
                   1439:     my ($fpath) = @_;
                   1440:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1441:     unless ($fpath eq '') {
                   1442:         my @parts=split('/',$fpath);
                   1443:         foreach my $part (@parts) {
                   1444:             $filepath.= '/'.$part;
                   1445:             if ((-e $filepath)!=1) {
                   1446:                 mkdir($filepath,0777);
                   1447:             }
                   1448:         }
                   1449:     }
                   1450:     return $filepath;
                   1451: }
                   1452: 
                   1453: sub store_edited_file {
1.638     albertel 1454:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1455:     my $file = $primary_url;
                   1456:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1457:     my $fpath = '';
                   1458:     my $fname = $file;
                   1459:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1460:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1461:     my $filepath = &build_filepath($fpath);
                   1462:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1463:     print $fh $content;
                   1464:     close($fh);
1.638     albertel 1465:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1466:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1467: 			  $home);
1.637     raeburn  1468:     if ($$fetchresult eq 'ok') {
                   1469:         return '/uploaded/'.$fpath.'/'.$fname;
                   1470:     } else {
1.638     albertel 1471:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1472: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1473:         return '/adm/notfound.html';
                   1474:     }
                   1475: }
                   1476: 
1.531     albertel 1477: sub clean_filename {
1.831     albertel 1478:     my ($fname,$args)=@_;
1.315     www      1479: # Replace Windows backslashes by forward slashes
1.257     www      1480:     $fname=~s/\\/\//g;
1.831     albertel 1481:     if (!$args->{'keep_path'}) {
                   1482:         # Get rid of everything but the actual filename
                   1483: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1484:     }
1.315     www      1485: # Replace spaces by underscores
                   1486:     $fname=~s/\s+/\_/g;
                   1487: # Replace all other weird characters by nothing
1.831     albertel 1488:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1489: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1490: # numbers
                   1491:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1492:     return $fname;
                   1493: }
                   1494: 
1.608     albertel 1495: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1496: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1497: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1498: #        $coursedoc - if true up to the current course
                   1499: #                     if false
                   1500: #        $subdir - directory in userfile to store the file into
                   1501: #        $parser, $allfiles, $codebase - unknown
                   1502: #
                   1503: # output: url of file in userspace, or error: <message> 
                   1504: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1505: 
                   1506: 
1.531     albertel 1507: sub userfileupload {
1.719     banghart 1508:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1509:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1510:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1511:     $fname=&clean_filename($fname);
1.315     www      1512: # See if there is anything left
1.257     www      1513:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1514:     chop($env{'form.'.$formname});
1.523     raeburn  1515:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1516:         my $now = time;
                   1517:         my $filepath = 'tmp/helprequests/'.$now;
                   1518:         my @parts=split(/\//,$filepath);
                   1519:         my $fullpath = $perlvar{'lonDaemons'};
                   1520:         for (my $i=0;$i<@parts;$i++) {
                   1521:             $fullpath .= '/'.$parts[$i];
                   1522:             if ((-e $fullpath)!=1) {
                   1523:                 mkdir($fullpath,0777);
                   1524:             }
                   1525:         }
                   1526:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1527:         print $fh $env{'form.'.$formname};
1.523     raeburn  1528:         close($fh);
1.741     raeburn  1529:         return $fullpath.'/'.$fname;
                   1530:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1531:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1532:                        '_'.$env{'user.domain'}.'/pending';
                   1533:         my @parts=split(/\//,$filepath);
                   1534:         my $fullpath = $perlvar{'lonDaemons'};
                   1535:         for (my $i=0;$i<@parts;$i++) {
                   1536:             $fullpath .= '/'.$parts[$i];
                   1537:             if ((-e $fullpath)!=1) {
                   1538:                 mkdir($fullpath,0777);
                   1539:             }
                   1540:         }
                   1541:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1542:         print $fh $env{'form.'.$formname};
                   1543:         close($fh);
                   1544:         return $fullpath.'/'.$fname;
1.523     raeburn  1545:     }
1.719     banghart 1546:     
1.258     www      1547: # Create the directory if not present
1.493     albertel 1548:     $fname="$subdir/$fname";
1.259     www      1549:     if ($coursedoc) {
1.638     albertel 1550: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1551: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1552:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1553:             return &finishuserfileupload($docuname,$docudom,
                   1554: 					 $formname,$fname,$parser,$allfiles,
                   1555: 					 $codebase);
1.481     raeburn  1556:         } else {
1.620     albertel 1557:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1558:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1559: 				       $fname,$formname,$parser,
                   1560: 				       $allfiles,$codebase);
1.481     raeburn  1561:         }
1.719     banghart 1562:     } elsif (defined($destuname)) {
                   1563:         my $docuname=$destuname;
                   1564:         my $docudom=$destudom;
                   1565: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1566: 				     $fname,$parser,$allfiles,$codebase);
                   1567:         
1.259     www      1568:     } else {
1.638     albertel 1569:         my $docuname=$env{'user.name'};
                   1570:         my $docudom=$env{'user.domain'};
1.714     raeburn  1571:         if (exists($env{'form.group'})) {
                   1572:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1573:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1574:         }
1.638     albertel 1575: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1576: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1577:     }
1.271     www      1578: }
                   1579: 
                   1580: sub finishuserfileupload {
1.638     albertel 1581:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1582:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1583:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1584:     my ($fnamepath,$file);
                   1585:     $file=$fname;
                   1586:     if ($fname=~m|/|) {
                   1587:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1588: 	$path.=$fnamepath.'/';
                   1589:     }
1.259     www      1590:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1591:     my $count;
                   1592:     for ($count=4;$count<=$#parts;$count++) {
                   1593:         $filepath.="/$parts[$count]";
                   1594:         if ((-e $filepath)!=1) {
                   1595: 	    mkdir($filepath,0777);
                   1596:         }
                   1597:     }
                   1598: # Save the file
                   1599:     {
1.701     albertel 1600: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1601: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1602: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1603: 	    return '/adm/notfound.html';
                   1604: 	}
                   1605: 	if (!print FH ($env{'form.'.$formname})) {
                   1606: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1607: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1608: 	    return '/adm/notfound.html';
                   1609: 	}
1.570     albertel 1610: 	close(FH);
1.258     www      1611:     }
1.637     raeburn  1612:     if ($parser eq 'parse') {
1.638     albertel 1613:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1614: 						   $codebase);
1.637     raeburn  1615:         unless ($parse_result eq 'ok') {
1.638     albertel 1616:             &logthis('Failed to parse '.$filepath.$file.
                   1617: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1618:         }
                   1619:     }
1.259     www      1620: # Notify homeserver to grep it
                   1621: #
1.638     albertel 1622:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1623:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1624:     if ($fetchresult eq 'ok') {
1.259     www      1625: #
1.258     www      1626: # Return the URL to it
1.494     albertel 1627:         return '/uploaded/'.$path.$file;
1.263     www      1628:     } else {
1.494     albertel 1629:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1630: 		 ': '.$fetchresult);
1.263     www      1631:         return '/adm/notfound.html';
                   1632:     }    
1.493     albertel 1633: }
                   1634: 
1.637     raeburn  1635: sub extract_embedded_items {
1.648     raeburn  1636:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1637:     my @state = ();
                   1638:     my %javafiles = (
                   1639:                       codebase => '',
                   1640:                       code => '',
                   1641:                       archive => ''
                   1642:                     );
                   1643:     my %mediafiles = (
                   1644:                       src => '',
                   1645:                       movie => '',
                   1646:                      );
1.648     raeburn  1647:     my $p;
                   1648:     if ($content) {
                   1649:         $p = HTML::LCParser->new($content);
                   1650:     } else {
                   1651:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1652:     }
1.641     albertel 1653:     while (my $t=$p->get_token()) {
1.640     albertel 1654: 	if ($t->[0] eq 'S') {
                   1655: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1656: 	    push (@state, $tagname);
1.648     raeburn  1657:             if (lc($tagname) eq 'allow') {
                   1658:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1659:             }
1.640     albertel 1660: 	    if (lc($tagname) eq 'img') {
                   1661: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1662: 	    }
1.645     raeburn  1663:             if (lc($tagname) eq 'script') {
                   1664:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1665:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1666:                 } else {
                   1667:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1668:                 }
                   1669:             }
                   1670:             if (lc($tagname) eq 'link') {
                   1671:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1672:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1673:                 }
                   1674:             }
1.640     albertel 1675: 	    if (lc($tagname) eq 'object' ||
                   1676: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1677: 		foreach my $item (keys(%javafiles)) {
                   1678: 		    $javafiles{$item} = '';
                   1679: 		}
                   1680: 	    }
                   1681: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1682: 		my $name = lc($attr->{'name'});
                   1683: 		foreach my $item (keys(%javafiles)) {
                   1684: 		    if ($name eq $item) {
                   1685: 			$javafiles{$item} = $attr->{'value'};
                   1686: 			last;
                   1687: 		    }
                   1688: 		}
                   1689: 		foreach my $item (keys(%mediafiles)) {
                   1690: 		    if ($name eq $item) {
                   1691: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1692: 			last;
                   1693: 		    }
                   1694: 		}
                   1695: 	    }
                   1696: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1697: 		foreach my $item (keys(%javafiles)) {
                   1698: 		    if ($attr->{$item}) {
                   1699: 			$javafiles{$item} = $attr->{$item};
                   1700: 			last;
                   1701: 		    }
                   1702: 		}
                   1703: 		foreach my $item (keys(%mediafiles)) {
                   1704: 		    if ($attr->{$item}) {
                   1705: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1706: 			last;
                   1707: 		    }
                   1708: 		}
                   1709: 	    }
                   1710: 	} elsif ($t->[0] eq 'E') {
                   1711: 	    my ($tagname) = ($t->[1]);
                   1712: 	    if ($javafiles{'codebase'} ne '') {
                   1713: 		$javafiles{'codebase'} .= '/';
                   1714: 	    }  
                   1715: 	    if (lc($tagname) eq 'applet' ||
                   1716: 		lc($tagname) eq 'object' ||
                   1717: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1718: 		) {
                   1719: 		foreach my $item (keys(%javafiles)) {
                   1720: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1721: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1722: 			&add_filetype($allfiles,$file,$item);
                   1723: 		    }
                   1724: 		}
                   1725: 	    } 
                   1726: 	    pop @state;
                   1727: 	}
                   1728:     }
1.637     raeburn  1729:     return 'ok';
                   1730: }
                   1731: 
1.639     albertel 1732: sub add_filetype {
                   1733:     my ($allfiles,$file,$type)=@_;
                   1734:     if (exists($allfiles->{$file})) {
                   1735: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1736: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1737: 	}
                   1738:     } else {
                   1739: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1740:     }
                   1741: }
                   1742: 
1.493     albertel 1743: sub removeuploadedurl {
                   1744:     my ($url)=@_;
                   1745:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1746:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1747: }
                   1748: 
                   1749: sub removeuserfile {
                   1750:     my ($docuname,$docudom,$fname)=@_;
                   1751:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1752:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1753:     if ($result eq 'ok') {
                   1754:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1755:             my $metafile = $fname.'.meta';
                   1756:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1757: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1758:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1759:             my $sqlresult = 
1.823     albertel 1760:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1761:                                         'portfolio_metadata',$group,
                   1762:                                         'delete');
1.798     raeburn  1763:         }
                   1764:     }
                   1765:     return $result;
1.257     www      1766: }
1.15      www      1767: 
1.530     albertel 1768: sub mkdiruserfile {
                   1769:     my ($docuname,$docudom,$dir)=@_;
                   1770:     my $home=&homeserver($docuname,$docudom);
                   1771:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1772: }
                   1773: 
1.531     albertel 1774: sub renameuserfile {
                   1775:     my ($docuname,$docudom,$old,$new)=@_;
                   1776:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1777:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1778:                         &escape("$old").':'.&escape("$new"),$home);
                   1779:     if ($result eq 'ok') {
                   1780:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1781:             my $oldmeta = $old.'.meta';
                   1782:             my $newmeta = $new.'.meta';
                   1783:             my $metaresult = 
                   1784:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1785: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1786:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1787:             my $sqlresult = 
1.823     albertel 1788:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1789:                                         'portfolio_metadata',$group,
                   1790:                                         'delete');
1.798     raeburn  1791:         }
                   1792:     }
                   1793:     return $result;
1.531     albertel 1794: }
                   1795: 
1.14      www      1796: # ------------------------------------------------------------------------- Log
                   1797: 
                   1798: sub log {
                   1799:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1800:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1801: }
                   1802: 
                   1803: # ------------------------------------------------------------------ Course Log
1.352     www      1804: #
                   1805: # This routine flushes several buffers of non-mission-critical nature
                   1806: #
1.157     www      1807: 
                   1808: sub flushcourselogs {
1.352     www      1809:     &logthis('Flushing log buffers');
                   1810: #
                   1811: # course logs
                   1812: # This is a log of all transactions in a course, which can be used
                   1813: # for data mining purposes
                   1814: #
                   1815: # It also collects the courseid database, which lists last transaction
                   1816: # times and course titles for all courseids
                   1817: #
                   1818:     my %courseidbuffer=();
1.800     albertel 1819:     foreach my $crsid (keys %courselogs) {
1.352     www      1820:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1821: 		          &escape($courselogs{$crsid}),
                   1822: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1823: 	    delete $courselogs{$crsid};
                   1824:         } else {
                   1825:             &logthis('Failed to flush log buffer for '.$crsid);
                   1826:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1827:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1828:                         " exceeded maximum size, deleting.</font>");
                   1829:                delete $courselogs{$crsid};
                   1830:             }
1.352     www      1831:         }
                   1832:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1833:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1834: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1835:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1836:         } else {
                   1837:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1838: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1839:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1840:         }
1.191     harris41 1841:     }
1.352     www      1842: #
                   1843: # Write course id database (reverse lookup) to homeserver of courses 
                   1844: # Is used in pickcourse
                   1845: #
1.840   ! albertel 1846:     foreach my $crs_home (keys(%courseidbuffer)) {
        !          1847:         &courseidput($hostdom{$crs_home},$courseidbuffer{$crs_home},
        !          1848: 		     $crs_home);
1.352     www      1849:     }
                   1850: #
                   1851: # File accesses
                   1852: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1853: #
1.449     matthew  1854:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1855:         if ($entry =~ /___count$/) {
                   1856:             my ($dom,$name);
1.807     albertel 1857:             ($dom,$name,undef)=
1.811     albertel 1858: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1859:             if (! defined($dom) || $dom eq '' || 
                   1860:                 ! defined($name) || $name eq '') {
1.620     albertel 1861:                 my $cid = $env{'request.course.id'};
                   1862:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1863:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1864:             }
1.450     matthew  1865:             my $value = $accesshash{$entry};
                   1866:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1867:             my %temphash=($url => $value);
1.449     matthew  1868:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1869:             if ($result eq 'ok') {
                   1870:                 delete $accesshash{$entry};
                   1871:             } elsif ($result eq 'unknown_cmd') {
                   1872:                 # Target server has old code running on it.
1.450     matthew  1873:                 my %temphash=($entry => $value);
1.449     matthew  1874:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1875:                     delete $accesshash{$entry};
                   1876:                 }
                   1877:             }
                   1878:         } else {
1.811     albertel 1879:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1880:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1881:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1882:                 delete $accesshash{$entry};
                   1883:             }
1.185     www      1884:         }
1.191     harris41 1885:     }
1.352     www      1886: #
                   1887: # Roles
                   1888: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1889: #
1.800     albertel 1890:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1891:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1892: 	    split(/\:/,$entry);
                   1893:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1894:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1895:                 $rudom,$runame) eq 'ok') {
                   1896: 	    delete $userrolehash{$entry};
                   1897:         }
                   1898:     }
1.662     raeburn  1899: #
                   1900: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1901: #
                   1902:     my %domrolebuffer = ();
                   1903:     foreach my $entry (keys %domainrolehash) {
                   1904:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1905:         if ($domrolebuffer{$rudom}) {
                   1906:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1907:                       '='.&escape($domainrolehash{$entry});
                   1908:         } else {
                   1909:             $domrolebuffer{$rudom}.=&escape($entry).
                   1910:                       '='.&escape($domainrolehash{$entry});
                   1911:         }
                   1912:         delete $domainrolehash{$entry};
                   1913:     }
                   1914:     foreach my $dom (keys(%domrolebuffer)) {
                   1915:         foreach my $tryserver (keys %libserv) {
                   1916:             if ($hostdom{$tryserver} eq $dom) {
                   1917:                 unless (&reply('domroleput:'.$dom.':'.
                   1918:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1919:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1920:                 }
                   1921:             }
                   1922:         }
                   1923:     }
1.186     www      1924:     $dumpcount++;
1.157     www      1925: }
                   1926: 
                   1927: sub courselog {
                   1928:     my $what=shift;
1.158     www      1929:     $what=time.':'.$what;
1.620     albertel 1930:     unless ($env{'request.course.id'}) { return ''; }
                   1931:     $coursedombuf{$env{'request.course.id'}}=
                   1932:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1933:     $coursenumbuf{$env{'request.course.id'}}=
                   1934:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1935:     $coursehombuf{$env{'request.course.id'}}=
                   1936:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1937:     $coursedescrbuf{$env{'request.course.id'}}=
                   1938:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1939:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1940:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1941:     $courseownerbuf{$env{'request.course.id'}}=
                   1942:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1943:     $coursetypebuf{$env{'request.course.id'}}=
                   1944:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1945:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1946: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1947:     } else {
1.620     albertel 1948: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1949:     }
1.620     albertel 1950:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1951: 	&flushcourselogs();
                   1952:     }
1.158     www      1953: }
                   1954: 
                   1955: sub courseacclog {
                   1956:     my $fnsymb=shift;
1.620     albertel 1957:     unless ($env{'request.course.id'}) { return ''; }
                   1958:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1959:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1960:         $what.=':POST';
1.583     matthew  1961:         # FIXME: Probably ought to escape things....
1.800     albertel 1962: 	foreach my $key (keys(%env)) {
                   1963:             if ($key=~/^form\.(.*)/) {
                   1964: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1965:             }
1.191     harris41 1966:         }
1.583     matthew  1967:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1968:         # FIXME: We should not be depending on a form parameter that someone
                   1969:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1970:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1971:             $what.= ':POST';
                   1972:             # FIXME: Probably ought to escape things....
                   1973:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1974:                                  'crsdiscuss') {
1.620     albertel 1975:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1976:             }
                   1977:         }
1.158     www      1978:     }
                   1979:     &courselog($what);
1.149     www      1980: }
                   1981: 
1.185     www      1982: sub countacc {
                   1983:     my $url=&declutter(shift);
1.458     matthew  1984:     return if (! defined($url) || $url eq '');
1.620     albertel 1985:     unless ($env{'request.course.id'}) { return ''; }
                   1986:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1987:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1988:     $accesshash{$key}++;
1.185     www      1989: }
1.349     www      1990: 
1.361     www      1991: sub linklog {
                   1992:     my ($from,$to)=@_;
                   1993:     $from=&declutter($from);
                   1994:     $to=&declutter($to);
                   1995:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1996:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1997: }
                   1998:   
1.349     www      1999: sub userrolelog {
                   2000:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2001:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2002:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2003:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2004:         ($trole=~/^ta/)) {
1.350     www      2005:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2006:        $userrolehash
                   2007:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2008:                     =$tend.':'.$tstart;
1.662     raeburn  2009:     }
                   2010:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2011:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2012:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2013:         ($trole=~/^sc/)) {
                   2014:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2015:        $domainrolehash
                   2016:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2017:                     = $tend.':'.$tstart;
                   2018:     }
1.351     www      2019: }
                   2020: 
                   2021: sub get_course_adv_roles {
                   2022:     my $cid=shift;
1.620     albertel 2023:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2024:     my %coursehash=&coursedescription($cid);
1.470     www      2025:     my %nothide=();
1.800     albertel 2026:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2027: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2028:     }
1.351     www      2029:     my %returnhash=();
                   2030:     my %dumphash=
                   2031:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2032:     my $now=time;
1.800     albertel 2033:     foreach my $entry (keys %dumphash) {
                   2034: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2035:         if (($tstart) && ($tstart<0)) { next; }
                   2036:         if (($tend) && ($tend<$now)) { next; }
                   2037:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2038:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2039: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2040: 	if ((&privileged($username,$domain)) && 
                   2041: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2042: 	if ($role eq 'cr') { next; }
1.351     www      2043:         my $key=&plaintext($role);
                   2044:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2045:         if ($returnhash{$key}) {
                   2046: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2047:         } else {
                   2048:             $returnhash{$key}=$username.':'.$domain;
                   2049:         }
1.400     www      2050:      }
                   2051:     return %returnhash;
                   2052: }
                   2053: 
                   2054: sub get_my_roles {
1.832     raeburn  2055:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
1.620     albertel 2056:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2057:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2058:     my %dumphash=
                   2059:             &dump('nohist_userroles',$udom,$uname);
                   2060:     my %returnhash=();
                   2061:     my $now=time;
1.800     albertel 2062:     foreach my $entry (keys(%dumphash)) {
                   2063: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2064:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2065:         my $status = 'active';
                   2066:         if (($tend) && ($tend<$now)) {
                   2067:             $status = 'previous';
                   2068:         } 
                   2069:         if (($tstart) && ($now<$tstart)) {
                   2070:             $status = 'future';
                   2071:         }
                   2072:         if (ref($types) eq 'ARRAY') {
                   2073:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2074:                 next;
                   2075:             } 
                   2076:         } else {
                   2077:             if ($status ne 'active') {
                   2078:                 next;
                   2079:             }
                   2080:         }
1.800     albertel 2081:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.832     raeburn  2082:         if (ref($roledoms) eq 'ARRAY') {
                   2083:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2084:                 next;
                   2085:             }
                   2086:         }
                   2087:         if (ref($roles) eq 'ARRAY') {
                   2088:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2089:                 next;
                   2090:             }
                   2091:         } 
1.400     www      2092: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2093:     }
1.373     www      2094:     return %returnhash;
1.399     www      2095: }
                   2096: 
                   2097: # ----------------------------------------------------- Frontpage Announcements
                   2098: #
                   2099: #
                   2100: 
                   2101: sub postannounce {
                   2102:     my ($server,$text)=@_;
                   2103:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2104:     unless ($text=~/\w/) { $text=''; }
                   2105:     return &reply('setannounce:'.&escape($text),$server);
                   2106: }
                   2107: 
                   2108: sub getannounce {
1.448     albertel 2109: 
                   2110:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2111: 	my $announcement='';
1.800     albertel 2112: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2113: 	close($fh);
1.399     www      2114: 	if ($announcement=~/\w/) { 
                   2115: 	    return 
                   2116:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2117:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2118: 	} else {
                   2119: 	    return '';
                   2120: 	}
                   2121:     } else {
                   2122: 	return '';
                   2123:     }
1.351     www      2124: }
1.353     www      2125: 
                   2126: # ---------------------------------------------------------- Course ID routines
                   2127: # Deal with domain's nohist_courseid.db files
                   2128: #
                   2129: 
                   2130: sub courseidput {
                   2131:     my ($domain,$what,$coursehome)=@_;
                   2132:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2133: }
                   2134: 
                   2135: sub courseiddump {
1.791     raeburn  2136:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2137:     my %returnhash=();
1.355     www      2138:     unless ($domfilter) { $domfilter=''; }
1.353     www      2139:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2140:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2141: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2142: 	        foreach my $line (
1.506     raeburn  2143:                  split(/\&/,&reply('courseiddump:'.$hostdom{$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=();
                   2171:     if (exists($domain_primary{$dom})) {
                   2172:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2173:                                                          &escape($enddate).':';
                   2174: 	my @esc_senders=map { &escape($_)} @$senders;
                   2175: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2176: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2177:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2178:             if (($key) && ($value)) {
                   2179:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2180:             }
                   2181:         }
                   2182:     }
                   2183:     return %returnhash;
                   2184: }
1.662     raeburn  2185: # ---------------------------------------------------------- Domain roles
                   2186: 
                   2187: sub get_domain_roles {
                   2188:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2189:     if (undef($startdate) || $startdate eq '') {
                   2190:         $startdate = '.';
                   2191:     }
                   2192:     if (undef($enddate) || $enddate eq '') {
                   2193:         $enddate = '.';
                   2194:     }
                   2195:     my $rolelist = join(':',@{$roles});
                   2196:     my %personnel = ();
                   2197:     foreach my $tryserver (keys(%libserv)) {
                   2198:         if ($hostdom{$tryserver} eq $dom) {
                   2199:             %{$personnel{$tryserver}}=();
1.800     albertel 2200:             foreach my $line (
1.662     raeburn  2201:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2202:                    &escape($startdate).':'.&escape($enddate).':'.
                   2203:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2204:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2205:                 if (($key) && ($value)) {
                   2206:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2207:                 }
                   2208:             }
                   2209:         }
                   2210:     }
                   2211:     return %personnel;
                   2212: }
1.658     raeburn  2213: 
1.149     www      2214: # ----------------------------------------------------------- Check out an item
                   2215: 
1.504     albertel 2216: sub get_first_access {
                   2217:     my ($type,$argsymb)=@_;
1.790     albertel 2218:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2219:     if ($argsymb) { $symb=$argsymb; }
                   2220:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2221:     if ($type eq 'map') {
                   2222: 	$res=&symbread($map);
                   2223:     } else {
                   2224: 	$res=$symb;
                   2225:     }
                   2226:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2227:     return $times{"$courseid\0$res"};
1.504     albertel 2228: }
                   2229: 
                   2230: sub set_first_access {
                   2231:     my ($type)=@_;
1.790     albertel 2232:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2233:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2234:     if ($type eq 'map') {
                   2235: 	$res=&symbread($map);
                   2236:     } else {
                   2237: 	$res=$symb;
                   2238:     }
                   2239:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2240:     if (!$firstaccess) {
1.588     albertel 2241: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2242:     }
                   2243:     return 'already_set';
1.504     albertel 2244: }
                   2245: 
1.149     www      2246: sub checkout {
                   2247:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2248:     my $now=time;
                   2249:     my $lonhost=$perlvar{'lonHostID'};
                   2250:     my $infostr=&escape(
1.234     www      2251:                  'CHECKOUTTOKEN&'.
1.149     www      2252:                  $tuname.'&'.
                   2253:                  $tudom.'&'.
                   2254:                  $tcrsid.'&'.
                   2255:                  $symb.'&'.
                   2256: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2257:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2258:     if ($token=~/^error\:/) { 
1.672     albertel 2259:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2260:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2261:                  "</font>");
                   2262:         return ''; 
                   2263:     }
                   2264: 
1.149     www      2265:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2266:     $token=~tr/a-z/A-Z/;
                   2267: 
1.153     www      2268:     my %infohash=('resource.0.outtoken' => $token,
                   2269:                   'resource.0.checkouttime' => $now,
                   2270:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2271: 
                   2272:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2273:        return '';
1.151     www      2274:     } else {
1.672     albertel 2275:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2276:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2277:                  "</font>");
1.149     www      2278:     }    
                   2279: 
                   2280:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2281:                          &escape('Checkout '.$infostr.' - '.
                   2282:                                                  $token)) ne 'ok') {
                   2283: 	return '';
1.151     www      2284:     } else {
1.672     albertel 2285:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2286:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2287:                  "</font>");
1.149     www      2288:     }
1.151     www      2289:     return $token;
1.149     www      2290: }
                   2291: 
                   2292: # ------------------------------------------------------------ Check in an item
                   2293: 
                   2294: sub checkin {
                   2295:     my $token=shift;
1.150     www      2296:     my $now=time;
                   2297:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2298:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2299:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2300:     $dtoken=~s/\W/\_/g;
1.234     www      2301:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2302:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2303: 
1.154     www      2304:     unless (($tuname) && ($tudom)) {
                   2305:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2306:         return '';
                   2307:     }
                   2308:     
                   2309:     unless (&allowed('mgr',$tcrsid)) {
                   2310:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2311:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2312:         return '';
                   2313:     }
                   2314: 
1.153     www      2315:     my %infohash=('resource.0.intoken' => $token,
                   2316:                   'resource.0.checkintime' => $now,
                   2317:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2318: 
                   2319:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2320:        return '';
                   2321:     }    
                   2322: 
                   2323:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2324:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2325: 	return '';
                   2326:     }
                   2327: 
                   2328:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2329: }
                   2330: 
                   2331: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2332: 
                   2333: sub expirespread {
                   2334:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2335:     my $cid=$env{'request.course.id'}; 
1.110     www      2336:     if ($cid) {
                   2337:        my $now=time;
                   2338:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2339:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2340:                             $env{'course.'.$cid.'.num'}.
1.110     www      2341: 	        	    ':nohist_expirationdates:'.
                   2342:                             &escape($key).'='.$now,
1.620     albertel 2343:                             $env{'course.'.$cid.'.home'})
1.110     www      2344:     }
                   2345:     return 'ok';
1.14      www      2346: }
                   2347: 
1.109     www      2348: # ----------------------------------------------------- Devalidate Spreadsheets
                   2349: 
                   2350: sub devalidate {
1.325     www      2351:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2352:     my $cid=$env{'request.course.id'}; 
1.109     www      2353:     if ($cid) {
1.391     matthew  2354:         # delete the stored spreadsheets for
                   2355:         # - the student level sheet of this user in course's homespace
                   2356:         # - the assessment level sheet for this resource 
                   2357:         #   for this user in user's homespace
1.553     albertel 2358: 	# - current conditional state info
1.325     www      2359: 	my $key=$uname.':'.$udom.':';
1.109     www      2360:         my $status=
1.299     matthew  2361: 	    &del('nohist_calculatedsheets',
1.391     matthew  2362: 		 [$key.'studentcalc:'],
1.620     albertel 2363: 		 $env{'course.'.$cid.'.domain'},
                   2364: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2365: 		.' '.
                   2366: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2367: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2368:         unless ($status eq 'ok ok') {
                   2369:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2370:                     $uname.' at '.$udom.' for '.
1.109     www      2371: 		    $symb.': '.$status);
1.133     albertel 2372:         }
1.553     albertel 2373: 	&delenv('user.state.'.$cid);
1.109     www      2374:     }
                   2375: }
                   2376: 
1.265     albertel 2377: sub get_scalar {
                   2378:     my ($string,$end) = @_;
                   2379:     my $value;
                   2380:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2381: 	$value = $1;
                   2382:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2383: 	$value = $1;
                   2384:     }
                   2385:     return &unescape($value);
                   2386: }
                   2387: 
                   2388: sub array2str {
                   2389:   my (@array) = @_;
                   2390:   my $result=&arrayref2str(\@array);
                   2391:   $result=~s/^__ARRAY_REF__//;
                   2392:   $result=~s/__END_ARRAY_REF__$//;
                   2393:   return $result;
                   2394: }
                   2395: 
1.204     albertel 2396: sub arrayref2str {
                   2397:   my ($arrayref) = @_;
1.265     albertel 2398:   my $result='__ARRAY_REF__';
1.204     albertel 2399:   foreach my $elem (@$arrayref) {
1.265     albertel 2400:     if(ref($elem) eq 'ARRAY') {
                   2401:       $result.=&arrayref2str($elem).'&';
                   2402:     } elsif(ref($elem) eq 'HASH') {
                   2403:       $result.=&hashref2str($elem).'&';
                   2404:     } elsif(ref($elem)) {
                   2405:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2406:     } else {
                   2407:       $result.=&escape($elem).'&';
                   2408:     }
                   2409:   }
                   2410:   $result=~s/\&$//;
1.265     albertel 2411:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2412:   return $result;
                   2413: }
                   2414: 
1.168     albertel 2415: sub hash2str {
1.204     albertel 2416:   my (%hash) = @_;
                   2417:   my $result=&hashref2str(\%hash);
1.265     albertel 2418:   $result=~s/^__HASH_REF__//;
                   2419:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2420:   return $result;
                   2421: }
                   2422: 
                   2423: sub hashref2str {
                   2424:   my ($hashref)=@_;
1.265     albertel 2425:   my $result='__HASH_REF__';
1.800     albertel 2426:   foreach my $key (sort(keys(%$hashref))) {
                   2427:     if (ref($key) eq 'ARRAY') {
                   2428:       $result.=&arrayref2str($key).'=';
                   2429:     } elsif (ref($key) eq 'HASH') {
                   2430:       $result.=&hashref2str($key).'=';
                   2431:     } elsif (ref($key)) {
1.265     albertel 2432:       $result.='=';
1.800     albertel 2433:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2434:     } else {
1.800     albertel 2435: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2436:     }
                   2437: 
1.800     albertel 2438:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2439:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2440:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2441:       $result.=&hashref2str($hashref->{$key}).'&';
                   2442:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2443:        $result.='&';
1.800     albertel 2444:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2445:     } else {
1.800     albertel 2446:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2447:     }
                   2448:   }
1.168     albertel 2449:   $result=~s/\&$//;
1.265     albertel 2450:   $result .= '__END_HASH_REF__';
1.168     albertel 2451:   return $result;
                   2452: }
                   2453: 
                   2454: sub str2hash {
1.265     albertel 2455:     my ($string)=@_;
                   2456:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2457:     return %$hash;
                   2458: }
                   2459: 
                   2460: sub str2hashref {
1.168     albertel 2461:   my ($string) = @_;
1.265     albertel 2462: 
                   2463:   my %hash;
                   2464: 
                   2465:   if($string !~ /^__HASH_REF__/) {
                   2466:       if (! ($string eq '' || !defined($string))) {
                   2467: 	  $hash{'error'}='Not hash reference';
                   2468:       }
                   2469:       return (\%hash, $string);
                   2470:   }
                   2471: 
                   2472:   $string =~ s/^__HASH_REF__//;
                   2473: 
                   2474:   while($string !~ /^__END_HASH_REF__/) {
                   2475:       #key
                   2476:       my $key='';
                   2477:       if($string =~ /^__HASH_REF__/) {
                   2478:           ($key, $string)=&str2hashref($string);
                   2479:           if(defined($key->{'error'})) {
                   2480:               $hash{'error'}='Bad data';
                   2481:               return (\%hash, $string);
                   2482:           }
                   2483:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2484:           ($key, $string)=&str2arrayref($string);
                   2485:           if($key->[0] eq 'Array reference error') {
                   2486:               $hash{'error'}='Bad data';
                   2487:               return (\%hash, $string);
                   2488:           }
                   2489:       } else {
                   2490:           $string =~ s/^(.*?)=//;
1.267     albertel 2491: 	  $key=&unescape($1);
1.265     albertel 2492:       }
                   2493:       $string =~ s/^=//;
                   2494: 
                   2495:       #value
                   2496:       my $value='';
                   2497:       if($string =~ /^__HASH_REF__/) {
                   2498:           ($value, $string)=&str2hashref($string);
                   2499:           if(defined($value->{'error'})) {
                   2500:               $hash{'error'}='Bad data';
                   2501:               return (\%hash, $string);
                   2502:           }
                   2503:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2504:           ($value, $string)=&str2arrayref($string);
                   2505:           if($value->[0] eq 'Array reference error') {
                   2506:               $hash{'error'}='Bad data';
                   2507:               return (\%hash, $string);
                   2508:           }
                   2509:       } else {
                   2510: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2511:       }
                   2512:       $string =~ s/^&//;
                   2513: 
                   2514:       $hash{$key}=$value;
1.204     albertel 2515:   }
1.265     albertel 2516: 
                   2517:   $string =~ s/^__END_HASH_REF__//;
                   2518: 
                   2519:   return (\%hash, $string);
1.204     albertel 2520: }
                   2521: 
                   2522: sub str2array {
1.265     albertel 2523:     my ($string)=@_;
                   2524:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2525:     return @$array;
                   2526: }
                   2527: 
                   2528: sub str2arrayref {
1.204     albertel 2529:   my ($string) = @_;
1.265     albertel 2530:   my @array;
                   2531: 
                   2532:   if($string !~ /^__ARRAY_REF__/) {
                   2533:       if (! ($string eq '' || !defined($string))) {
                   2534: 	  $array[0]='Array reference error';
                   2535:       }
                   2536:       return (\@array, $string);
                   2537:   }
                   2538: 
                   2539:   $string =~ s/^__ARRAY_REF__//;
                   2540: 
                   2541:   while($string !~ /^__END_ARRAY_REF__/) {
                   2542:       my $value='';
                   2543:       if($string =~ /^__HASH_REF__/) {
                   2544:           ($value, $string)=&str2hashref($string);
                   2545:           if(defined($value->{'error'})) {
                   2546:               $array[0] ='Array reference error';
                   2547:               return (\@array, $string);
                   2548:           }
                   2549:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2550:           ($value, $string)=&str2arrayref($string);
                   2551:           if($value->[0] eq 'Array reference error') {
                   2552:               $array[0] ='Array reference error';
                   2553:               return (\@array, $string);
                   2554:           }
                   2555:       } else {
                   2556: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2557:       }
                   2558:       $string =~ s/^&//;
                   2559: 
                   2560:       push(@array, $value);
1.191     harris41 2561:   }
1.265     albertel 2562: 
                   2563:   $string =~ s/^__END_ARRAY_REF__//;
                   2564: 
                   2565:   return (\@array, $string);
1.168     albertel 2566: }
                   2567: 
1.167     albertel 2568: # -------------------------------------------------------------------Temp Store
                   2569: 
1.168     albertel 2570: sub tmpreset {
                   2571:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2572:   if (!$symb) {
                   2573:     $symb=&symbread();
1.620     albertel 2574:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2575:   }
                   2576:   $symb=escape($symb);
                   2577: 
1.620     albertel 2578:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2579:   $namespace=~s/\//\_/g;
                   2580:   $namespace=~s/\W//g;
                   2581: 
1.620     albertel 2582:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2583:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2584:   if ($domain eq 'public' && $stuname eq 'public') {
                   2585:       $stuname=$ENV{'REMOTE_ADDR'};
                   2586:   }
1.168     albertel 2587:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2588:   my %hash;
                   2589:   if (tie(%hash,'GDBM_File',
                   2590: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2591: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2592:     foreach my $key (keys %hash) {
1.180     albertel 2593:       if ($key=~ /:$symb/) {
1.168     albertel 2594: 	delete($hash{$key});
                   2595:       }
                   2596:     }
                   2597:   }
                   2598: }
                   2599: 
1.167     albertel 2600: sub tmpstore {
1.168     albertel 2601:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2602: 
                   2603:   if (!$symb) {
                   2604:     $symb=&symbread();
1.620     albertel 2605:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2606:   }
                   2607:   $symb=escape($symb);
                   2608: 
                   2609:   if (!$namespace) {
                   2610:     # I don't think we would ever want to store this for a course.
                   2611:     # it seems this will only be used if we don't have a course.
1.620     albertel 2612:     #$namespace=$env{'request.course.id'};
1.168     albertel 2613:     #if (!$namespace) {
1.620     albertel 2614:       $namespace=$env{'request.state'};
1.168     albertel 2615:     #}
                   2616:   }
                   2617:   $namespace=~s/\//\_/g;
                   2618:   $namespace=~s/\W//g;
1.620     albertel 2619:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2620:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2621:   if ($domain eq 'public' && $stuname eq 'public') {
                   2622:       $stuname=$ENV{'REMOTE_ADDR'};
                   2623:   }
1.168     albertel 2624:   my $now=time;
                   2625:   my %hash;
                   2626:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2627:   if (tie(%hash,'GDBM_File',
                   2628: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2629: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2630:     $hash{"version:$symb"}++;
                   2631:     my $version=$hash{"version:$symb"};
                   2632:     my $allkeys=''; 
                   2633:     foreach my $key (keys(%$storehash)) {
                   2634:       $allkeys.=$key.':';
1.591     albertel 2635:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2636:     }
                   2637:     $hash{"$version:$symb:timestamp"}=$now;
                   2638:     $allkeys.='timestamp';
                   2639:     $hash{"$version:keys:$symb"}=$allkeys;
                   2640:     if (untie(%hash)) {
                   2641:       return 'ok';
                   2642:     } else {
                   2643:       return "error:$!";
                   2644:     }
                   2645:   } else {
                   2646:     return "error:$!";
                   2647:   }
                   2648: }
1.167     albertel 2649: 
1.168     albertel 2650: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2651: 
1.168     albertel 2652: sub tmprestore {
                   2653:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2654: 
1.168     albertel 2655:   if (!$symb) {
                   2656:     $symb=&symbread();
1.620     albertel 2657:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2658:   }
                   2659:   $symb=escape($symb);
                   2660: 
1.620     albertel 2661:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2662: 
1.620     albertel 2663:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2664:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2665:   if ($domain eq 'public' && $stuname eq 'public') {
                   2666:       $stuname=$ENV{'REMOTE_ADDR'};
                   2667:   }
1.168     albertel 2668:   my %returnhash;
                   2669:   $namespace=~s/\//\_/g;
                   2670:   $namespace=~s/\W//g;
                   2671:   my %hash;
                   2672:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2673:   if (tie(%hash,'GDBM_File',
                   2674: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2675: 	  &GDBM_READER(),0640)) {
1.168     albertel 2676:     my $version=$hash{"version:$symb"};
                   2677:     $returnhash{'version'}=$version;
                   2678:     my $scope;
                   2679:     for ($scope=1;$scope<=$version;$scope++) {
                   2680:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2681:       my @keys=split(/:/,$vkeys);
                   2682:       my $key;
                   2683:       $returnhash{"$scope:keys"}=$vkeys;
                   2684:       foreach $key (@keys) {
1.591     albertel 2685: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2686: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2687:       }
                   2688:     }
1.168     albertel 2689:     if (!(untie(%hash))) {
                   2690:       return "error:$!";
                   2691:     }
                   2692:   } else {
                   2693:     return "error:$!";
                   2694:   }
                   2695:   return %returnhash;
1.167     albertel 2696: }
                   2697: 
1.9       www      2698: # ----------------------------------------------------------------------- Store
                   2699: 
                   2700: sub store {
1.124     www      2701:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2702:     my $home='';
                   2703: 
1.168     albertel 2704:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2705: 
1.213     www      2706:     $symb=&symbclean($symb);
1.122     albertel 2707:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2708: 
1.620     albertel 2709:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2710:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2711: 
                   2712:     &devalidate($symb,$stuname,$domain);
1.109     www      2713: 
                   2714:     $symb=escape($symb);
1.187     www      2715:     if (!$namespace) { 
1.620     albertel 2716:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2717:           return ''; 
                   2718:        } 
                   2719:     }
1.620     albertel 2720:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2721: 
                   2722:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2723:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2724: 
1.12      www      2725:     my $namevalue='';
1.800     albertel 2726:     foreach my $key (keys(%$storehash)) {
                   2727:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2728:     }
1.12      www      2729:     $namevalue=~s/\&$//;
1.187     www      2730:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2731:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2732: }
                   2733: 
1.47      www      2734: # -------------------------------------------------------------- Critical Store
                   2735: 
                   2736: sub cstore {
1.124     www      2737:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2738:     my $home='';
                   2739: 
1.168     albertel 2740:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2741: 
1.213     www      2742:     $symb=&symbclean($symb);
1.122     albertel 2743:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2744: 
1.620     albertel 2745:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2746:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2747: 
                   2748:     &devalidate($symb,$stuname,$domain);
1.109     www      2749: 
                   2750:     $symb=escape($symb);
1.187     www      2751:     if (!$namespace) { 
1.620     albertel 2752:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2753:           return ''; 
                   2754:        } 
                   2755:     }
1.620     albertel 2756:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2757: 
                   2758:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2759:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2760: 
1.47      www      2761:     my $namevalue='';
1.800     albertel 2762:     foreach my $key (keys(%$storehash)) {
                   2763:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2764:     }
1.47      www      2765:     $namevalue=~s/\&$//;
1.187     www      2766:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2767:     return critical
                   2768:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2769: }
                   2770: 
1.9       www      2771: # --------------------------------------------------------------------- Restore
                   2772: 
                   2773: sub restore {
1.124     www      2774:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2775:     my $home='';
                   2776: 
1.168     albertel 2777:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2778: 
1.122     albertel 2779:     if (!$symb) {
                   2780:       unless ($symb=escape(&symbread())) { return ''; }
                   2781:     } else {
1.213     www      2782:       $symb=&escape(&symbclean($symb));
1.122     albertel 2783:     }
1.188     www      2784:     if (!$namespace) { 
1.620     albertel 2785:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2786:           return ''; 
                   2787:        } 
                   2788:     }
1.620     albertel 2789:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2790:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2791:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2792:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2793: 
1.12      www      2794:     my %returnhash=();
1.800     albertel 2795:     foreach my $line (split(/\&/,$answer)) {
                   2796: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2797:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2798:     }
1.75      www      2799:     my $version;
                   2800:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2801:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2802:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2803:        }
1.75      www      2804:     }
1.13      www      2805:     return %returnhash;
1.34      www      2806: }
                   2807: 
                   2808: # ---------------------------------------------------------- Course Description
                   2809: 
                   2810: sub coursedescription {
1.731     albertel 2811:     my ($courseid,$args)=@_;
1.34      www      2812:     $courseid=~s/^\///;
1.49      www      2813:     $courseid=~s/\_/\//g;
1.34      www      2814:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2815:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2816:     my $normalid=$cdomain.'_'.$cnum;
                   2817:     # need to always cache even if we get errors otherwise we keep 
                   2818:     # trying and trying and trying to get the course description.
                   2819:     my %envhash=();
                   2820:     my %returnhash=();
1.731     albertel 2821:     
                   2822:     my $expiretime=600;
                   2823:     if ($env{'request.course.id'} eq $normalid) {
                   2824: 	$expiretime=120;
                   2825:     }
                   2826: 
                   2827:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2828:     if (!$args->{'freshen_cache'}
                   2829: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2830: 	foreach my $key (keys(%env)) {
                   2831: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2832: 	    my ($setting) = $1;
                   2833: 	    $returnhash{$setting} = $env{$key};
                   2834: 	}
                   2835: 	return %returnhash;
                   2836:     }
                   2837: 
                   2838:     # get the data agin
                   2839:     if (!$args->{'one_time'}) {
                   2840: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2841:     }
1.811     albertel 2842: 
1.34      www      2843:     if ($chome ne 'no_host') {
1.302     albertel 2844:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2845:        if (!exists($returnhash{'con_lost'})) {
                   2846:            $returnhash{'home'}= $chome;
                   2847: 	   $returnhash{'domain'} = $cdomain;
                   2848: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2849:            if (!defined($returnhash{'type'})) {
                   2850:                $returnhash{'type'} = 'Course';
                   2851:            }
1.130     albertel 2852:            while (my ($name,$value) = each %returnhash) {
1.53      www      2853:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2854:            }
1.270     www      2855:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2856:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2857: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2858:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2859:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2860:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2861:        }
                   2862:     }
1.731     albertel 2863:     if (!$args->{'one_time'}) {
                   2864: 	&appenv(%envhash);
                   2865:     }
1.302     albertel 2866:     return %returnhash;
1.461     www      2867: }
                   2868: 
                   2869: # -------------------------------------------------See if a user is privileged
                   2870: 
                   2871: sub privileged {
                   2872:     my ($username,$domain)=@_;
                   2873:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2874: 			&homeserver($username,$domain));
                   2875:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2876:     my $now=time;
                   2877:     if ($rolesdump ne '') {
1.800     albertel 2878:         foreach my $entry (split(/&/,$rolesdump)) {
                   2879: 	    if ($entry!~/^rolesdef_/) {
                   2880: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2881: 		$area=~s/\_\w\w$//;
                   2882: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2883: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2884: 		    my $active=1;
                   2885: 		    if ($tend) {
                   2886: 			if ($tend<$now) { $active=0; }
                   2887: 		    }
                   2888: 		    if ($tstart) {
                   2889: 			if ($tstart>$now) { $active=0; }
                   2890: 		    }
                   2891: 		    if ($active) { return 1; }
                   2892: 		}
                   2893: 	    }
                   2894: 	}
                   2895:     }
                   2896:     return 0;
1.9       www      2897: }
1.1       albertel 2898: 
1.103     harris41 2899: # -------------------------------------------------------- Get user privileges
1.11      www      2900: 
                   2901: sub rolesinit {
                   2902:     my ($domain,$username,$authhost)=@_;
                   2903:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2904:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2905:     my %allroles=();
1.678     raeburn  2906:     my %allgroups=();   
1.11      www      2907:     my $now=time;
1.743     albertel 2908:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2909:     my $group_privs;
1.11      www      2910: 
                   2911:     if ($rolesdump ne '') {
1.800     albertel 2912:         foreach my $entry (split(/&/,$rolesdump)) {
                   2913: 	  if ($entry!~/^rolesdef_/) {
                   2914:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2915: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2916:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2917: 	    if ($role=~/^cr/) { 
1.807     albertel 2918: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2919: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2920: 		    ($tend,$tstart)=split('_',$trest);
                   2921: 		} else {
                   2922: 		    $trole=$role;
                   2923: 		}
1.678     raeburn  2924:             } elsif ($role =~ m|^gr/|) {
                   2925:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2926:                 ($trole,$group_privs) = split(/\//,$trole);
                   2927:                 $group_privs = &unescape($group_privs);
1.587     albertel 2928: 	    } else {
                   2929: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2930: 	    }
1.743     albertel 2931: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2932: 					 $username);
                   2933: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2934:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2935:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2936:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2937: 		my $spec=$trole.'.'.$area;
                   2938: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2939: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2940:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2941:                 } elsif ($trole eq 'gr') {
                   2942:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2943: 		} else {
1.567     raeburn  2944:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2945: 		}
1.12      www      2946:             }
1.662     raeburn  2947:           }
1.191     harris41 2948:         }
1.743     albertel 2949:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2950:         $userroles{'user.adv'}    = $adv;
                   2951: 	$userroles{'user.author'} = $author;
1.620     albertel 2952:         $env{'user.adv'}=$adv;
1.11      www      2953:     }
1.743     albertel 2954:     return \%userroles;  
1.11      www      2955: }
                   2956: 
1.567     raeburn  2957: sub set_arearole {
                   2958:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2959: # log the associated role with the area
                   2960:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2961:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2962: }
                   2963: 
                   2964: sub custom_roleprivs {
                   2965:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2966:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2967:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 2968:     if (&hostname($homsvr) ne '') {
1.567     raeburn  2969:         my ($rdummy,$roledef)=
                   2970:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2971:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2972:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2973:             if (defined($syspriv)) {
                   2974:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2975:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2976:             }
                   2977:             if ($tdomain ne '') {
                   2978:                 if (defined($dompriv)) {
                   2979:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2980:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2981:                 }
                   2982:                 if (($trest ne '') && (defined($coursepriv))) {
                   2983:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2984:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2985:                 }
                   2986:             }
                   2987:         }
                   2988:     }
                   2989: }
                   2990: 
1.678     raeburn  2991: sub group_roleprivs {
                   2992:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2993:     my $access = 1;
                   2994:     my $now = time;
                   2995:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2996:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2997:     if ($access) {
1.811     albertel 2998:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2999:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3000:     }
                   3001: }
1.567     raeburn  3002: 
                   3003: sub standard_roleprivs {
                   3004:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3005:     if (defined($pr{$trole.':s'})) {
                   3006:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3007:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3008:     }
                   3009:     if ($tdomain ne '') {
                   3010:         if (defined($pr{$trole.':d'})) {
                   3011:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3012:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3013:         }
                   3014:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3015:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3016:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3017:         }
                   3018:     }
                   3019: }
                   3020: 
                   3021: sub set_userprivs {
1.678     raeburn  3022:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3023:     my $author=0;
                   3024:     my $adv=0;
1.678     raeburn  3025:     my %grouproles = ();
                   3026:     if (keys(%{$allgroups}) > 0) {
                   3027:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3028:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3029:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3030:                 $trole = $1;
                   3031:                 $area = $2;
1.681     raeburn  3032:                 $sec = $3;
                   3033:                 $extendedarea = $area.$sec;
                   3034:                 if (exists($$allgroups{$area})) {
                   3035:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3036:                         my $spec = $trole.'.'.$extendedarea;
                   3037:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3038:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3039:                     }
                   3040:                 }
                   3041:             }
                   3042:         }
                   3043:     }
1.800     albertel 3044:     foreach my $group (keys(%grouproles)) {
                   3045:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3046:     }
1.800     albertel 3047:     foreach my $role (keys(%{$allroles})) {
                   3048:         my %thesepriv;
                   3049:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3050:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3051:             if ($item ne '') {
                   3052:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3053:                 if ($restrictions eq '') {
                   3054:                     $thesepriv{$privilege}='F';
                   3055:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3056:                     $thesepriv{$privilege}.=$restrictions;
                   3057:                 }
                   3058:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3059:             }
                   3060:         }
                   3061:         my $thesestr='';
1.800     albertel 3062:         foreach my $priv (keys(%thesepriv)) {
                   3063: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3064: 	}
                   3065:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3066:     }
                   3067:     return ($author,$adv);
                   3068: }
                   3069: 
1.12      www      3070: # --------------------------------------------------------------- get interface
                   3071: 
                   3072: sub get {
1.131     albertel 3073:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3074:    my $items='';
1.800     albertel 3075:    foreach my $item (@$storearr) {
                   3076:        $items.=&escape($item).'&';
1.191     harris41 3077:    }
1.12      www      3078:    $items=~s/\&$//;
1.620     albertel 3079:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3080:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3081:    my $uhome=&homeserver($uname,$udomain);
                   3082: 
1.133     albertel 3083:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3084:    my @pairs=split(/\&/,$rep);
1.273     albertel 3085:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3086:      return @pairs;
                   3087:    }
1.15      www      3088:    my %returnhash=();
1.42      www      3089:    my $i=0;
1.800     albertel 3090:    foreach my $item (@$storearr) {
                   3091:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3092:       $i++;
1.191     harris41 3093:    }
1.15      www      3094:    return %returnhash;
1.27      www      3095: }
                   3096: 
                   3097: # --------------------------------------------------------------- del interface
                   3098: 
                   3099: sub del {
1.133     albertel 3100:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3101:    my $items='';
1.800     albertel 3102:    foreach my $item (@$storearr) {
                   3103:        $items.=&escape($item).'&';
1.191     harris41 3104:    }
1.27      www      3105:    $items=~s/\&$//;
1.620     albertel 3106:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3107:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3108:    my $uhome=&homeserver($uname,$udomain);
                   3109: 
                   3110:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3111: }
                   3112: 
                   3113: # -------------------------------------------------------------- dump interface
                   3114: 
                   3115: sub dump {
1.755     albertel 3116:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3117:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3118:     if (!$uname) { $uname=$env{'user.name'}; }
                   3119:     my $uhome=&homeserver($uname,$udomain);
                   3120:     if ($regexp) {
                   3121: 	$regexp=&escape($regexp);
                   3122:     } else {
                   3123: 	$regexp='.';
                   3124:     }
                   3125:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3126:     my @pairs=split(/\&/,$rep);
                   3127:     my %returnhash=();
                   3128:     foreach my $item (@pairs) {
                   3129: 	my ($key,$value)=split(/=/,$item,2);
                   3130: 	$key = &unescape($key);
                   3131: 	next if ($key =~ /^error: 2 /);
                   3132: 	$returnhash{$key}=&thaw_unescape($value);
                   3133:     }
                   3134:     return %returnhash;
1.407     www      3135: }
                   3136: 
1.717     albertel 3137: # --------------------------------------------------------- dumpstore interface
                   3138: 
                   3139: sub dumpstore {
                   3140:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3141:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3142:    if (!$uname) { $uname=$env{'user.name'}; }
                   3143:    my $uhome=&homeserver($uname,$udomain);
                   3144:    if ($regexp) {
                   3145:        $regexp=&escape($regexp);
                   3146:    } else {
                   3147:        $regexp='.';
                   3148:    }
                   3149:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3150:    my @pairs=split(/\&/,$rep);
                   3151:    my %returnhash=();
                   3152:    foreach my $item (@pairs) {
                   3153:        my ($key,$value)=split(/=/,$item,2);
                   3154:        next if ($key =~ /^error: 2 /);
                   3155:        $returnhash{$key}=&thaw_unescape($value);
                   3156:    }
                   3157:    return %returnhash;
1.717     albertel 3158: }
                   3159: 
1.407     www      3160: # -------------------------------------------------------------- keys interface
                   3161: 
                   3162: sub getkeys {
                   3163:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3164:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3165:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3166:    my $uhome=&homeserver($uname,$udomain);
                   3167:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3168:    my @keyarray=();
1.800     albertel 3169:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3170:       next if ($key =~ /^error: 2 /);
1.800     albertel 3171:       push(@keyarray,&unescape($key));
1.407     www      3172:    }
                   3173:    return @keyarray;
1.318     matthew  3174: }
                   3175: 
1.319     matthew  3176: # --------------------------------------------------------------- currentdump
                   3177: sub currentdump {
1.328     matthew  3178:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3179:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3180:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3181:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3182:    my $uhome = &homeserver($sname,$sdom);
                   3183:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3184:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3185:    #
1.318     matthew  3186:    my %returnhash=();
1.319     matthew  3187:    #
                   3188:    if ($rep eq "unknown_cmd") { 
                   3189:        # an old lond will not know currentdump
                   3190:        # Do a dump and make it look like a currentdump
1.822     albertel 3191:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3192:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3193:        my %hash = @tmp;
                   3194:        @tmp=();
1.424     matthew  3195:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3196:    } else {
                   3197:        my @pairs=split(/\&/,$rep);
1.800     albertel 3198:        foreach my $pair (@pairs) {
                   3199:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3200:            my ($symb,$param) = split(/:/,$key);
                   3201:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3202:                                                         &thaw_unescape($value);
1.319     matthew  3203:        }
1.191     harris41 3204:    }
1.12      www      3205:    return %returnhash;
1.424     matthew  3206: }
                   3207: 
                   3208: sub convert_dump_to_currentdump{
                   3209:     my %hash = %{shift()};
                   3210:     my %returnhash;
                   3211:     # Code ripped from lond, essentially.  The only difference
                   3212:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3213:     # we might run in to problems with parameter names =~ /^v\./
                   3214:     while (my ($key,$value) = each(%hash)) {
                   3215:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3216: 	$symb  = &unescape($symb);
                   3217: 	$param = &unescape($param);
1.424     matthew  3218:         next if ($v eq 'version' || $symb eq 'keys');
                   3219:         next if (exists($returnhash{$symb}) &&
                   3220:                  exists($returnhash{$symb}->{$param}) &&
                   3221:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3222:         $returnhash{$symb}->{$param}=$value;
                   3223:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3224:     }
                   3225:     #
                   3226:     # Remove all of the keys in the hashes which keep track of
                   3227:     # the version of the parameter.
                   3228:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3229:         # use a foreach because we are going to delete from the hash.
                   3230:         foreach my $key (keys(%$param_hash)) {
                   3231:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3232:         }
                   3233:     }
                   3234:     return \%returnhash;
1.12      www      3235: }
                   3236: 
1.627     albertel 3237: # ------------------------------------------------------ critical inc interface
                   3238: 
                   3239: sub cinc {
                   3240:     return &inc(@_,'critical');
                   3241: }
                   3242: 
1.449     matthew  3243: # --------------------------------------------------------------- inc interface
                   3244: 
                   3245: sub inc {
1.627     albertel 3246:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3247:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3248:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3249:     my $uhome=&homeserver($uname,$udomain);
                   3250:     my $items='';
                   3251:     if (! ref($store)) {
                   3252:         # got a single value, so use that instead
                   3253:         $items = &escape($store).'=&';
                   3254:     } elsif (ref($store) eq 'SCALAR') {
                   3255:         $items = &escape($$store).'=&';        
                   3256:     } elsif (ref($store) eq 'ARRAY') {
                   3257:         $items = join('=&',map {&escape($_);} @{$store});
                   3258:     } elsif (ref($store) eq 'HASH') {
                   3259:         while (my($key,$value) = each(%{$store})) {
                   3260:             $items.= &escape($key).'='.&escape($value).'&';
                   3261:         }
                   3262:     }
                   3263:     $items=~s/\&$//;
1.627     albertel 3264:     if ($critical) {
                   3265: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3266:     } else {
                   3267: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3268:     }
1.449     matthew  3269: }
                   3270: 
1.12      www      3271: # --------------------------------------------------------------- put interface
                   3272: 
                   3273: sub put {
1.134     albertel 3274:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3275:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3276:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3277:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3278:    my $items='';
1.800     albertel 3279:    foreach my $item (keys(%$storehash)) {
                   3280:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3281:    }
1.12      www      3282:    $items=~s/\&$//;
1.134     albertel 3283:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3284: }
                   3285: 
1.631     albertel 3286: # ------------------------------------------------------------ newput interface
                   3287: 
                   3288: sub newput {
                   3289:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3290:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3291:    if (!$uname) { $uname=$env{'user.name'}; }
                   3292:    my $uhome=&homeserver($uname,$udomain);
                   3293:    my $items='';
                   3294:    foreach my $key (keys(%$storehash)) {
                   3295:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3296:    }
                   3297:    $items=~s/\&$//;
                   3298:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3299: }
                   3300: 
                   3301: # ---------------------------------------------------------  putstore interface
                   3302: 
1.524     raeburn  3303: sub putstore {
1.715     albertel 3304:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3305:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3306:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3307:    my $uhome=&homeserver($uname,$udomain);
                   3308:    my $items='';
1.715     albertel 3309:    foreach my $key (keys(%$storehash)) {
                   3310:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3311:    }
1.715     albertel 3312:    $items=~s/\&$//;
1.716     albertel 3313:    my $esc_symb=&escape($symb);
                   3314:    my $esc_v=&escape($version);
1.715     albertel 3315:    my $reply =
1.716     albertel 3316:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3317: 	      $uhome);
                   3318:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3319:        # gfall back to way things use to be done
1.715     albertel 3320:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3321: 			    $uname);
1.524     raeburn  3322:    }
1.715     albertel 3323:    return $reply;
                   3324: }
                   3325: 
                   3326: sub old_putstore {
1.716     albertel 3327:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3328:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3329:     if (!$uname) { $uname=$env{'user.name'}; }
                   3330:     my $uhome=&homeserver($uname,$udomain);
                   3331:     my %newstorehash;
1.800     albertel 3332:     foreach my $item (keys(%$storehash)) {
                   3333: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3334: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3335:     }
                   3336:     my $items='';
                   3337:     my %allitems = ();
1.800     albertel 3338:     foreach my $item (keys(%newstorehash)) {
                   3339: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3340: 	    my $key = $1.':keys:'.$2;
                   3341: 	    $allitems{$key} .= $3.':';
                   3342: 	}
1.800     albertel 3343: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3344:     }
1.800     albertel 3345:     foreach my $item (keys(%allitems)) {
                   3346: 	$allitems{$item} =~ s/\:$//;
                   3347: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3348:     }
                   3349:     $items=~s/\&$//;
                   3350:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3351: }
                   3352: 
1.47      www      3353: # ------------------------------------------------------ critical put interface
                   3354: 
                   3355: sub cput {
1.134     albertel 3356:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3357:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3358:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3359:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3360:    my $items='';
1.800     albertel 3361:    foreach my $item (keys(%$storehash)) {
                   3362:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3363:    }
1.47      www      3364:    $items=~s/\&$//;
1.134     albertel 3365:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3366: }
                   3367: 
                   3368: # -------------------------------------------------------------- eget interface
                   3369: 
                   3370: sub eget {
1.133     albertel 3371:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3372:    my $items='';
1.800     albertel 3373:    foreach my $item (@$storearr) {
                   3374:        $items.=&escape($item).'&';
1.191     harris41 3375:    }
1.12      www      3376:    $items=~s/\&$//;
1.620     albertel 3377:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3378:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3379:    my $uhome=&homeserver($uname,$udomain);
                   3380:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3381:    my @pairs=split(/\&/,$rep);
                   3382:    my %returnhash=();
1.42      www      3383:    my $i=0;
1.800     albertel 3384:    foreach my $item (@$storearr) {
                   3385:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3386:       $i++;
1.191     harris41 3387:    }
1.12      www      3388:    return %returnhash;
                   3389: }
                   3390: 
1.667     albertel 3391: # ------------------------------------------------------------ tmpput interface
                   3392: sub tmpput {
1.802     raeburn  3393:     my ($storehash,$server,$context)=@_;
1.667     albertel 3394:     my $items='';
1.800     albertel 3395:     foreach my $item (keys(%$storehash)) {
                   3396: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3397:     }
                   3398:     $items=~s/\&$//;
1.802     raeburn  3399:     if (defined($context)) {
                   3400:         $items .= ':'.&escape($context);
                   3401:     }
1.667     albertel 3402:     return &reply("tmpput:$items",$server);
                   3403: }
                   3404: 
                   3405: # ------------------------------------------------------------ tmpget interface
                   3406: sub tmpget {
1.688     albertel 3407:     my ($token,$server)=@_;
                   3408:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3409:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3410:     my %returnhash;
                   3411:     foreach my $item (split(/\&/,$rep)) {
                   3412: 	my ($key,$value)=split(/=/,$item);
                   3413: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3414:     }
                   3415:     return %returnhash;
                   3416: }
                   3417: 
1.688     albertel 3418: # ------------------------------------------------------------ tmpget interface
                   3419: sub tmpdel {
                   3420:     my ($token,$server)=@_;
                   3421:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3422:     return &reply("tmpdel:$token",$server);
                   3423: }
                   3424: 
1.765     albertel 3425: # -------------------------------------------------- portfolio access checking
                   3426: 
                   3427: sub portfolio_access {
1.766     albertel 3428:     my ($requrl) = @_;
1.765     albertel 3429:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3430:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3431:     if ($result) {
                   3432:         my %setters;
                   3433:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3434:             my ($startblock,$endblock) =
                   3435:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3436:             if ($startblock && $endblock) {
                   3437:                 return 'B';
                   3438:             }
                   3439:         } else {
                   3440:             my ($startblock,$endblock) =
                   3441:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3442:             if ($startblock && $endblock) {
                   3443:                 return 'B';
                   3444:             }
                   3445:         }
                   3446:     }
1.765     albertel 3447:     if ($result eq 'ok') {
1.766     albertel 3448:        return 'F';
1.765     albertel 3449:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3450:        return 'A';
1.765     albertel 3451:     }
1.766     albertel 3452:     return '';
1.765     albertel 3453: }
                   3454: 
                   3455: sub get_portfolio_access {
1.767     albertel 3456:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3457: 
                   3458:     if (!ref($access_hash)) {
                   3459: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3460: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3461: 						   $file_name);
                   3462: 	$access_hash = $access_controls{$file_name};
                   3463:     }
                   3464: 
1.765     albertel 3465:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3466:     my $now = time;
                   3467:     if (ref($access_hash) eq 'HASH') {
                   3468:         foreach my $key (keys(%{$access_hash})) {
                   3469:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3470:             if ($start > $now) {
                   3471:                 next;
                   3472:             }
                   3473:             if ($end && $end<$now) {
                   3474:                 next;
                   3475:             }
                   3476:             if ($scope eq 'public') {
                   3477:                 $public = $key;
                   3478:                 last;
                   3479:             } elsif ($scope eq 'guest') {
                   3480:                 $guest = $key;
                   3481:             } elsif ($scope eq 'domains') {
                   3482:                 push(@domains,$key);
                   3483:             } elsif ($scope eq 'users') {
                   3484:                 push(@users,$key);
                   3485:             } elsif ($scope eq 'course') {
                   3486:                 push(@courses,$key);
                   3487:             } elsif ($scope eq 'group') {
                   3488:                 push(@groups,$key);
                   3489:             }
                   3490:         }
                   3491:         if ($public) {
                   3492:             return 'ok';
                   3493:         }
                   3494:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3495:             if ($guest) {
                   3496:                 return $guest;
                   3497:             }
                   3498:         } else {
                   3499:             if (@domains > 0) {
                   3500:                 foreach my $domkey (@domains) {
                   3501:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3502:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3503:                             return 'ok';
                   3504:                         }
                   3505:                     }
                   3506:                 }
                   3507:             }
                   3508:             if (@users > 0) {
                   3509:                 foreach my $userkey (@users) {
                   3510:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3511:                         return 'ok';
                   3512:                     }
                   3513:                 }
                   3514:             }
                   3515:             my %roleshash;
                   3516:             my @courses_and_groups = @courses;
                   3517:             push(@courses_and_groups,@groups); 
                   3518:             if (@courses_and_groups > 0) {
                   3519:                 my (%allgroups,%allroles); 
                   3520:                 my ($start,$end,$role,$sec,$group);
                   3521:                 foreach my $envkey (%env) {
1.811     albertel 3522:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3523:                         my $cid = $2.'_'.$3; 
                   3524:                         if ($1 eq 'gr') {
                   3525:                             $group = $4;
                   3526:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3527:                         } else {
                   3528:                             if ($4 eq '') {
                   3529:                                 $sec = 'none';
                   3530:                             } else {
                   3531:                                 $sec = $4;
                   3532:                             }
                   3533:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3534:                         }
1.811     albertel 3535:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3536:                         my $cid = $2.'_'.$3;
                   3537:                         if ($4 eq '') {
                   3538:                             $sec = 'none';
                   3539:                         } else {
                   3540:                             $sec = $4;
                   3541:                         }
                   3542:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3543:                     }
                   3544:                 }
                   3545:                 if (keys(%allroles) == 0) {
                   3546:                     return;
                   3547:                 }
                   3548:                 foreach my $key (@courses_and_groups) {
                   3549:                     my %content = %{$$access_hash{$key}};
                   3550:                     my $cnum = $content{'number'};
                   3551:                     my $cdom = $content{'domain'};
                   3552:                     my $cid = $cdom.'_'.$cnum;
                   3553:                     if (!exists($allroles{$cid})) {
                   3554:                         next;
                   3555:                     }    
                   3556:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3557:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3558:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3559:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3560:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3561:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3562:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3563:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3564:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3565:                                         if (grep/^all$/,@sections) {
                   3566:                                             return 'ok';
                   3567:                                         } else {
                   3568:                                             if (grep/^$sec$/,@sections) {
                   3569:                                                 return 'ok';
                   3570:                                             }
                   3571:                                         }
                   3572:                                     }
                   3573:                                 }
                   3574:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3575:                                     if (grep/^none$/,@groups) {
                   3576:                                         return 'ok';
                   3577:                                     }
                   3578:                                 } else {
                   3579:                                     if (grep/^all$/,@groups) {
                   3580:                                         return 'ok';
                   3581:                                     } 
                   3582:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3583:                                         if (grep/^$group$/,@groups) {
                   3584:                                             return 'ok';
                   3585:                                         }
                   3586:                                     }
                   3587:                                 } 
                   3588:                             }
                   3589:                         }
                   3590:                     }
                   3591:                 }
                   3592:             }
                   3593:             if ($guest) {
                   3594:                 return $guest;
                   3595:             }
                   3596:         }
                   3597:     }
                   3598:     return;
                   3599: }
                   3600: 
                   3601: sub course_group_datechecker {
                   3602:     my ($dates,$now,$status) = @_;
                   3603:     my ($start,$end) = split(/\./,$dates);
                   3604:     if (!$start && !$end) {
                   3605:         return 'ok';
                   3606:     }
                   3607:     if (grep/^active$/,@{$status}) {
                   3608:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3609:             return 'ok';
                   3610:         }
                   3611:     }
                   3612:     if (grep/^previous$/,@{$status}) {
                   3613:         if ($end > $now ) {
                   3614:             return 'ok';
                   3615:         }
                   3616:     }
                   3617:     if (grep/^future$/,@{$status}) {
                   3618:         if ($start > $now) {
                   3619:             return 'ok';
                   3620:         }
                   3621:     }
                   3622:     return; 
                   3623: }
                   3624: 
                   3625: sub parse_portfolio_url {
                   3626:     my ($url) = @_;
                   3627: 
                   3628:     my ($type,$udom,$unum,$group,$file_name);
                   3629:     
1.823     albertel 3630:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3631: 	$type = 1;
                   3632:         $udom = $1;
                   3633:         $unum = $2;
                   3634:         $file_name = $3;
1.823     albertel 3635:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3636: 	$type = 2;
                   3637:         $udom = $1;
                   3638:         $unum = $2;
                   3639:         $group = $3;
                   3640:         $file_name = $3.'/'.$4;
                   3641:     }
                   3642:     if (wantarray) {
                   3643: 	return ($type,$udom,$unum,$file_name,$group);
                   3644:     }
                   3645:     return $type;
                   3646: }
                   3647: 
                   3648: sub is_portfolio_url {
                   3649:     my ($url) = @_;
                   3650:     return scalar(&parse_portfolio_url($url));
                   3651: }
                   3652: 
1.798     raeburn  3653: sub is_portfolio_file {
                   3654:     my ($file) = @_;
1.820     raeburn  3655:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3656:         return 1;
                   3657:     }
                   3658:     return;
                   3659: }
                   3660: 
                   3661: 
1.341     www      3662: # ---------------------------------------------- Custom access rule evaluation
                   3663: 
                   3664: sub customaccess {
                   3665:     my ($priv,$uri)=@_;
1.807     albertel 3666:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3667:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3668:     $udom = &LONCAPA::clean_domain($udom);
                   3669:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3670:     my $access=0;
1.800     albertel 3671:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3672: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3673:         if ($role) {
                   3674: 	   if ($role ne $urole) { next; }
                   3675:         }
1.800     albertel 3676:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3677:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3678:             if ($tdom) {
                   3679: 		if ($tdom ne $udom) { next; }
                   3680:             }
                   3681:             if ($tcrs) {
                   3682: 		if ($tcrs ne $ucrs) { next; }
                   3683:             }
                   3684:             if ($tsec) {
                   3685: 		if ($tsec ne $usec) { next; }
                   3686:             }
                   3687:             $access=($effect eq 'allow');
                   3688:             last;
1.342     www      3689:         }
1.402     bowersj2 3690: 	if ($realm eq '' && $role eq '') {
                   3691:             $access=($effect eq 'allow');
                   3692: 	}
1.341     www      3693:     }
                   3694:     return $access;
                   3695: }
                   3696: 
1.103     harris41 3697: # ------------------------------------------------- Check for a user privilege
1.12      www      3698: 
                   3699: sub allowed {
1.810     raeburn  3700:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3701:     my $ver_orguri=$uri;
1.439     www      3702:     $uri=&deversion($uri);
1.152     www      3703:     my $orguri=$uri;
1.52      www      3704:     $uri=&declutter($uri);
1.809     raeburn  3705: 
1.810     raeburn  3706:     if ($priv eq 'evb') {
                   3707: # Evade communication block restrictions for specified role in a course
                   3708:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3709:             return $1;
                   3710:         } else {
                   3711:             return;
                   3712:         }
                   3713:     }
                   3714: 
1.620     albertel 3715:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3716: # Free bre access to adm and meta resources
1.775     albertel 3717:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3718: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3719: 	&& ($priv eq 'bre')) {
1.14      www      3720: 	return 'F';
1.159     www      3721:     }
                   3722: 
1.545     banghart 3723: # Free bre access to user's own portfolio contents
1.714     raeburn  3724:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3725:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3726: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3727:         my %setters;
                   3728:         my ($startblock,$endblock) = 
                   3729:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3730:         if ($startblock && $endblock) {
                   3731:             return 'B';
                   3732:         } else {
                   3733:             return 'F';
                   3734:         }
1.545     banghart 3735:     }
                   3736: 
1.762     raeburn  3737: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3738:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3739:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3740:         if (exists($env{'request.course.id'})) {
                   3741:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3742:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3743:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3744:                 my $courseprivid=$env{'request.course.id'};
                   3745:                 $courseprivid=~s/\_/\//;
                   3746:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3747:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3748:                     return $1; 
1.762     raeburn  3749:                 } else {
                   3750:                     if ($env{'request.course.sec'}) {
                   3751:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3752:                     }
                   3753:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3754:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3755:                         return $2;
                   3756:                     }
1.714     raeburn  3757:                 }
                   3758:             }
                   3759:         }
                   3760:     }
                   3761: 
1.159     www      3762: # Free bre to public access
                   3763: 
                   3764:     if ($priv eq 'bre') {
1.238     www      3765:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3766: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3767:            return 'F'; 
                   3768:         }
1.238     www      3769:         if ($copyright eq 'priv') {
                   3770:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3771: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3772: 		return '';
                   3773:             }
                   3774:         }
                   3775:         if ($copyright eq 'domain') {
                   3776:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3777: 	    unless (($env{'user.domain'} eq $1) ||
                   3778:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3779: 		return '';
                   3780:             }
1.262     matthew  3781:         }
1.620     albertel 3782:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3783:             # Library role, so allow browsing of resources in this domain.
                   3784:             return 'F';
1.238     www      3785:         }
1.341     www      3786:         if ($copyright eq 'custom') {
                   3787: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3788:         }
1.14      www      3789:     }
1.264     matthew  3790:     # Domain coordinator is trying to create a course
1.620     albertel 3791:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3792:         # uri is the requested domain in this case.
                   3793:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3794:         # a role of dc for the domain in question.
1.620     albertel 3795:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3796:     }
1.29      www      3797: 
1.52      www      3798:     my $thisallowed='';
                   3799:     my $statecond=0;
                   3800:     my $courseprivid='';
                   3801: 
                   3802: # Course
                   3803: 
1.620     albertel 3804:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3805:        $thisallowed.=$1;
                   3806:     }
1.29      www      3807: 
1.52      www      3808: # Domain
                   3809: 
1.620     albertel 3810:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3811:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3812:        $thisallowed.=$1;
                   3813:     }
1.52      www      3814: 
                   3815: # Course: uri itself is a course
1.66      www      3816:     my $courseuri=$uri;
                   3817:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3818:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3819: 
1.620     albertel 3820:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3821:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3822:        $thisallowed.=$1;
                   3823:     }
1.29      www      3824: 
1.665     albertel 3825: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3826: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3827:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3828: 	$thisallowed='';
1.671     raeburn  3829:         my ($match)=&is_on_map($uri);
                   3830:         if ($match) {
                   3831:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3832:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3833:                 $thisallowed.=$1;
                   3834:             }
                   3835:         } else {
1.705     albertel 3836:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3837:             if ($refuri) {
                   3838:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3839:                     $thisallowed='F';
1.671     raeburn  3840:                 } else {
                   3841:                     $refuri=&declutter($refuri);
                   3842:                     my ($match) = &is_on_map($refuri);
                   3843:                     if ($match) {
                   3844:                         $thisallowed='F';
                   3845:                     }
1.669     raeburn  3846:                 }
1.671     raeburn  3847:             }
                   3848:         }
1.314     www      3849:     }
1.492     albertel 3850: 
1.766     albertel 3851:     if ($priv eq 'bre'
                   3852: 	&& $thisallowed ne 'F' 
                   3853: 	&& $thisallowed ne '2'
                   3854: 	&& &is_portfolio_url($uri)) {
                   3855: 	$thisallowed = &portfolio_access($uri);
                   3856:     }
                   3857:     
1.52      www      3858: # Full access at system, domain or course-wide level? Exit.
1.29      www      3859: 
                   3860:     if ($thisallowed=~/F/) {
                   3861: 	return 'F';
                   3862:     }
                   3863: 
1.52      www      3864: # If this is generating or modifying users, exit with special codes
1.29      www      3865: 
1.643     www      3866:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3867: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3868: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3869: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3870: 	    unless ($auname) { return $thisallowed; }
                   3871: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3872: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3873: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3874: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3875: 	}
1.52      www      3876: 	return $thisallowed;
                   3877:     }
                   3878: #
1.103     harris41 3879: # Gathered so far: system, domain and course wide privileges
1.52      www      3880: #
                   3881: # Course: See if uri or referer is an individual resource that is part of 
                   3882: # the course
                   3883: 
1.620     albertel 3884:     if ($env{'request.course.id'}) {
1.232     www      3885: 
1.620     albertel 3886:        $courseprivid=$env{'request.course.id'};
                   3887:        if ($env{'request.course.sec'}) {
                   3888:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3889:        }
                   3890:        $courseprivid=~s/\_/\//;
                   3891:        my $checkreferer=1;
1.232     www      3892:        my ($match,$cond)=&is_on_map($uri);
                   3893:        if ($match) {
                   3894:            $statecond=$cond;
1.620     albertel 3895:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3896:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3897:                $thisallowed.=$1;
                   3898:                $checkreferer=0;
                   3899:            }
1.29      www      3900:        }
1.83      www      3901:        
1.148     www      3902:        if ($checkreferer) {
1.620     albertel 3903: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3904:             unless ($refuri) {
1.800     albertel 3905:                 foreach my $key (keys(%env)) {
                   3906: 		    if ($key=~/^httpref\..*\*/) {
                   3907: 			my $pattern=$key;
1.156     www      3908:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3909:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3910:                         $pattern=~s/\//\\\//g;
1.152     www      3911:                         if ($orguri=~/$pattern/) {
1.800     albertel 3912: 			    $refuri=$env{$key};
1.148     www      3913:                         }
                   3914:                     }
1.191     harris41 3915:                 }
1.148     www      3916:             }
1.232     www      3917: 
1.148     www      3918:          if ($refuri) { 
1.152     www      3919: 	  $refuri=&declutter($refuri);
1.232     www      3920:           my ($match,$cond)=&is_on_map($refuri);
                   3921:             if ($match) {
                   3922:               my $refstatecond=$cond;
1.620     albertel 3923:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3924:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3925:                   $thisallowed.=$1;
1.53      www      3926:                   $uri=$refuri;
                   3927:                   $statecond=$refstatecond;
1.52      www      3928:               }
                   3929:           }
1.148     www      3930:         }
1.29      www      3931:        }
1.52      www      3932:    }
1.29      www      3933: 
1.52      www      3934: #
1.103     harris41 3935: # Gathered now: all privileges that could apply, and condition number
1.52      www      3936: # 
                   3937: #
                   3938: # Full or no access?
                   3939: #
1.29      www      3940: 
1.52      www      3941:     if ($thisallowed=~/F/) {
                   3942: 	return 'F';
                   3943:     }
1.29      www      3944: 
1.52      www      3945:     unless ($thisallowed) {
                   3946:         return '';
                   3947:     }
1.29      www      3948: 
1.52      www      3949: # Restrictions exist, deal with them
                   3950: #
                   3951: #   C:according to course preferences
                   3952: #   R:according to resource settings
                   3953: #   L:unless locked
                   3954: #   X:according to user session state
                   3955: #
                   3956: 
                   3957: # Possibly locked functionality, check all courses
1.54      www      3958: # Locks might take effect only after 10 minutes cache expiration for other
                   3959: # courses, and 2 minutes for current course
1.52      www      3960: 
                   3961:     my $envkey;
                   3962:     if ($thisallowed=~/L/) {
1.620     albertel 3963:         foreach $envkey (keys %env) {
1.54      www      3964:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3965:                my $courseid=$2;
                   3966:                my $roleid=$1.'.'.$2;
1.92      www      3967:                $courseid=~s/^\///;
1.54      www      3968:                my $expiretime=600;
1.620     albertel 3969:                if ($env{'request.role'} eq $roleid) {
1.54      www      3970: 		  $expiretime=120;
                   3971:                }
                   3972: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3973:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3974:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3975: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3976:                }
1.620     albertel 3977:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3978:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3979: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3980:                        &log($env{'user.domain'},$env{'user.name'},
                   3981:                             $env{'user.home'},
1.57      www      3982:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3983:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3984:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3985: 		       return '';
                   3986:                    }
                   3987:                }
1.620     albertel 3988:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3989:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3990: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3991:                        &log($env{'user.domain'},$env{'user.name'},
                   3992:                             $env{'user.home'},
1.57      www      3993:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3994:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3995:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3996: 		       return '';
                   3997:                    }
                   3998:                }
                   3999: 	   }
1.29      www      4000:        }
1.52      www      4001:     }
                   4002:    
                   4003: #
                   4004: # Rest of the restrictions depend on selected course
                   4005: #
                   4006: 
1.620     albertel 4007:     unless ($env{'request.course.id'}) {
1.766     albertel 4008: 	if ($thisallowed eq 'A') {
                   4009: 	    return 'A';
1.814     raeburn  4010:         } elsif ($thisallowed eq 'B') {
                   4011:             return 'B';
1.766     albertel 4012: 	} else {
                   4013: 	    return '1';
                   4014: 	}
1.52      www      4015:     }
1.29      www      4016: 
1.52      www      4017: #
                   4018: # Now user is definitely in a course
                   4019: #
1.53      www      4020: 
                   4021: 
                   4022: # Course preferences
                   4023: 
                   4024:    if ($thisallowed=~/C/) {
1.620     albertel 4025:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4026:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4027:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4028: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4029: 	   if ($priv ne 'pch') { 
                   4030: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4031: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4032: 			$env{'request.course.id'});
                   4033: 	   }
1.237     www      4034:            return '';
                   4035:        }
                   4036: 
1.620     albertel 4037:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4038: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4039: 	   if ($priv ne 'pch') { 
                   4040: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4041: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4042: 			$env{'request.course.id'});
                   4043: 	   }
1.54      www      4044:            return '';
                   4045:        }
1.53      www      4046:    }
                   4047: 
                   4048: # Resource preferences
                   4049: 
                   4050:    if ($thisallowed=~/R/) {
1.620     albertel 4051:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4052:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4053: 	   if ($priv ne 'pch') { 
                   4054: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4055: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4056: 	   }
                   4057: 	   return '';
1.54      www      4058:        }
1.53      www      4059:    }
1.30      www      4060: 
1.246     www      4061: # Restricted by state or randomout?
1.30      www      4062: 
1.52      www      4063:    if ($thisallowed=~/X/) {
1.620     albertel 4064:       if ($env{'acc.randomout'}) {
1.579     albertel 4065: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4066:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4067:             return ''; 
                   4068:          }
1.247     www      4069:       }
                   4070:       if (&condval($statecond)) {
1.52      www      4071: 	 return '2';
                   4072:       } else {
                   4073:          return '';
                   4074:       }
                   4075:    }
1.30      www      4076: 
1.766     albertel 4077:     if ($thisallowed eq 'A') {
                   4078: 	return 'A';
1.814     raeburn  4079:     } elsif ($thisallowed eq 'B') {
                   4080:         return 'B';
1.766     albertel 4081:     }
1.52      www      4082:    return 'F';
1.232     www      4083: }
                   4084: 
1.710     albertel 4085: sub split_uri_for_cond {
                   4086:     my $uri=&deversion(&declutter(shift));
                   4087:     my @uriparts=split(/\//,$uri);
                   4088:     my $filename=pop(@uriparts);
                   4089:     my $pathname=join('/',@uriparts);
                   4090:     return ($pathname,$filename);
                   4091: }
1.232     www      4092: # --------------------------------------------------- Is a resource on the map?
                   4093: 
                   4094: sub is_on_map {
1.710     albertel 4095:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4096:     #Trying to find the conditional for the file
1.620     albertel 4097:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4098: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4099:     if ($match) {
1.289     bowersj2 4100: 	return (1,$1);
                   4101:     } else {
1.434     www      4102: 	return (0,0);
1.289     bowersj2 4103:     }
1.12      www      4104: }
                   4105: 
1.427     www      4106: # --------------------------------------------------------- Get symb from alias
                   4107: 
                   4108: sub get_symb_from_alias {
                   4109:     my $symb=shift;
                   4110:     my ($map,$resid,$url)=&decode_symb($symb);
                   4111: # Already is a symb
                   4112:     if ($url) { return $symb; }
                   4113: # Must be an alias
                   4114:     my $aliassymb='';
                   4115:     my %bighash;
1.620     albertel 4116:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4117:                             &GDBM_READER(),0640)) {
                   4118:         my $rid=$bighash{'mapalias_'.$symb};
                   4119: 	if ($rid) {
                   4120: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4121: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4122: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4123: 	}
                   4124:         untie %bighash;
                   4125:     }
                   4126:     return $aliassymb;
                   4127: }
                   4128: 
1.12      www      4129: # ----------------------------------------------------------------- Define Role
                   4130: 
                   4131: sub definerole {
                   4132:   if (allowed('mcr','/')) {
                   4133:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4134:     foreach my $role (split(':',$sysrole)) {
                   4135: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4136:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4137:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4138: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4139:                return "refused:s:$crole&$cqual"; 
                   4140:             }
                   4141:         }
1.191     harris41 4142:     }
1.800     albertel 4143:     foreach my $role (split(':',$domrole)) {
                   4144: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4145:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4146:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4147: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4148:                return "refused:d:$crole&$cqual"; 
                   4149:             }
                   4150:         }
1.191     harris41 4151:     }
1.800     albertel 4152:     foreach my $role (split(':',$courole)) {
                   4153: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4154:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4155:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4156: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4157:                return "refused:c:$crole&$cqual"; 
                   4158:             }
                   4159:         }
1.191     harris41 4160:     }
1.620     albertel 4161:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4162:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4163: 	        "rolesdef_$rolename=".
                   4164:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4165:     return reply($command,$env{'user.home'});
1.12      www      4166:   } else {
                   4167:     return 'refused';
                   4168:   }
1.105     harris41 4169: }
                   4170: 
                   4171: # ---------------- Make a metadata query against the network of library servers
                   4172: 
                   4173: sub metadata_query {
1.244     matthew  4174:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4175:     my %rhash;
1.244     matthew  4176:     my @server_list = (defined($server_array) ? @$server_array
                   4177:                                               : keys(%libserv) );
                   4178:     for my $server (@server_list) {
1.118     harris41 4179: 	unless ($custom or $customshow) {
                   4180: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4181: 	    $rhash{$server}=$reply;
                   4182: 	}
                   4183: 	else {
                   4184: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4185: 			     &escape($custom).':'.&escape($customshow),
                   4186: 			     $server);
                   4187: 	    $rhash{$server}=$reply;
                   4188: 	}
1.112     harris41 4189:     }
1.118     harris41 4190:     return \%rhash;
1.240     www      4191: }
                   4192: 
                   4193: # ----------------------------------------- Send log queries and wait for reply
                   4194: 
                   4195: sub log_query {
                   4196:     my ($uname,$udom,$query,%filters)=@_;
                   4197:     my $uhome=&homeserver($uname,$udom);
                   4198:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4199:     my $uhost=&hostname($uhome);
1.800     albertel 4200:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4201:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4202:                        $uhome);
1.479     albertel 4203:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4204:     return get_query_reply($queryid);
                   4205: }
                   4206: 
1.818     raeburn  4207: # -------------------------- Update MySQL table for portfolio file
                   4208: 
                   4209: sub update_portfolio_table {
1.821     raeburn  4210:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4211:     my $homeserver = &homeserver($uname,$udom);
                   4212:     my $queryid=
1.821     raeburn  4213:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4214:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4215:     my $reply = &get_query_reply($queryid);
                   4216:     return $reply;
                   4217: }
                   4218: 
1.508     raeburn  4219: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4220: 
                   4221: sub fetch_enrollment_query {
1.511     raeburn  4222:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4223:     my $homeserver;
1.547     raeburn  4224:     my $maxtries = 1;
1.508     raeburn  4225:     if ($context eq 'automated') {
                   4226:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4227:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4228:     } else {
                   4229:         $homeserver = &homeserver($cnum,$dom);
                   4230:     }
1.838     albertel 4231:     my $host=&hostname($homeserver);
1.506     raeburn  4232:     my $cmd = '';
1.800     albertel 4233:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4234:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4235:     }
                   4236:     $cmd =~ s/%%$//;
                   4237:     $cmd = &escape($cmd);
                   4238:     my $query = 'fetchenrollment';
1.620     albertel 4239:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4240:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4241:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4242:         return 'error: '.$queryid;
                   4243:     }
1.506     raeburn  4244:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4245:     my $tries = 1;
                   4246:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4247:         $reply = &get_query_reply($queryid);
                   4248:         $tries ++;
                   4249:     }
1.526     raeburn  4250:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4251:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4252:     } else {
1.515     raeburn  4253:         my @responses = split/:/,$reply;
                   4254:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4255:             foreach my $line (@responses) {
                   4256:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4257:                 $$replyref{$key} = $value;
                   4258:             }
                   4259:         } else {
1.506     raeburn  4260:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4261:             foreach my $line (@responses) {
                   4262:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4263:                 $$replyref{$key} = $value;
                   4264:                 if ($value > 0) {
1.800     albertel 4265:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4266:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4267:                         my $destname = $pathname.'/'.$filename;
                   4268:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4269:                         if ($xml_classlist =~ /^error/) {
                   4270:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4271:                         } else {
1.506     raeburn  4272:                             if ( open(FILE,">$destname") ) {
                   4273:                                 print FILE &unescape($xml_classlist);
                   4274:                                 close(FILE);
1.526     raeburn  4275:                             } else {
                   4276:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4277:                             }
                   4278:                         }
                   4279:                     }
                   4280:                 }
                   4281:             }
                   4282:         }
                   4283:         return 'ok';
                   4284:     }
                   4285:     return 'error';
                   4286: }
                   4287: 
1.242     www      4288: sub get_query_reply {
                   4289:     my $queryid=shift;
1.240     www      4290:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4291:     my $reply='';
                   4292:     for (1..100) {
                   4293: 	sleep 2;
                   4294:         if (-e $replyfile.'.end') {
1.448     albertel 4295: 	    if (open(my $fh,$replyfile)) {
1.240     www      4296:                $reply.=<$fh>;
1.448     albertel 4297:                close($fh);
1.240     www      4298: 	   } else { return 'error: reply_file_error'; }
1.242     www      4299:            return &unescape($reply);
                   4300: 	}
1.240     www      4301:     }
1.242     www      4302:     return 'timeout:'.$queryid;
1.240     www      4303: }
                   4304: 
                   4305: sub courselog_query {
1.241     www      4306: #
                   4307: # possible filters:
                   4308: # url: url or symb
                   4309: # username
                   4310: # domain
                   4311: # action: view, submit, grade
                   4312: # start: timestamp
                   4313: # end: timestamp
                   4314: #
1.240     www      4315:     my (%filters)=@_;
1.620     albertel 4316:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4317:     if ($filters{'url'}) {
                   4318: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4319:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4320:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4321:     }
1.620     albertel 4322:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4323:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4324:     return &log_query($cname,$cdom,'courselog',%filters);
                   4325: }
                   4326: 
                   4327: sub userlog_query {
                   4328:     my ($uname,$udom,%filters)=@_;
                   4329:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4330: }
                   4331: 
1.506     raeburn  4332: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4333: 
                   4334: sub auto_run {
1.508     raeburn  4335:     my ($cnum,$cdom) = @_;
                   4336:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4337:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4338:     return $response;
                   4339: }
1.776     albertel 4340: 
1.506     raeburn  4341: sub auto_get_sections {
1.508     raeburn  4342:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4343:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4344:     my @secs = ();
1.511     raeburn  4345:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4346:     unless ($response eq 'refused') {
                   4347:         @secs = split/:/,$response;
                   4348:     }
                   4349:     return @secs;
                   4350: }
1.776     albertel 4351: 
1.506     raeburn  4352: sub auto_new_course {
1.508     raeburn  4353:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4354:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4355:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4356:     return $response;
                   4357: }
1.776     albertel 4358: 
1.506     raeburn  4359: sub auto_validate_courseID {
1.508     raeburn  4360:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4361:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4362:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4363:     return $response;
                   4364: }
1.776     albertel 4365: 
1.506     raeburn  4366: sub auto_create_password {
1.508     raeburn  4367:     my ($cnum,$cdom,$authparam) = @_;
                   4368:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4369:     my $create_passwd = 0;
                   4370:     my $authchk = '';
1.511     raeburn  4371:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4372:     if ($response eq 'refused') {
                   4373:         $authchk = 'refused';
                   4374:     } else {
                   4375:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4376:     }
                   4377:     return ($authparam,$create_passwd,$authchk);
                   4378: }
                   4379: 
1.706     raeburn  4380: sub auto_photo_permission {
                   4381:     my ($cnum,$cdom,$students) = @_;
                   4382:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4383:     my ($outcome,$perm_reqd,$conditions) = 
                   4384: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4385:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4386: 	return (undef,undef);
                   4387:     }
1.706     raeburn  4388:     return ($outcome,$perm_reqd,$conditions);
                   4389: }
                   4390: 
                   4391: sub auto_checkphotos {
                   4392:     my ($uname,$udom,$pid) = @_;
                   4393:     my $homeserver = &homeserver($uname,$udom);
                   4394:     my ($result,$resulttype);
                   4395:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4396: 				   &escape($uname).':'.&escape($pid),
                   4397: 				   $homeserver));
1.709     albertel 4398:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4399: 	return (undef,undef);
                   4400:     }
1.706     raeburn  4401:     if ($outcome) {
                   4402:         ($result,$resulttype) = split(/:/,$outcome);
                   4403:     } 
                   4404:     return ($result,$resulttype);
                   4405: }
                   4406: 
                   4407: sub auto_photochoice {
                   4408:     my ($cnum,$cdom) = @_;
                   4409:     my $homeserver = &homeserver($cnum,$cdom);
                   4410:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4411: 						       &escape($cdom),
                   4412: 						       $homeserver)));
1.709     albertel 4413:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4414: 	return (undef,undef);
                   4415:     }
1.706     raeburn  4416:     return ($update,$comment);
                   4417: }
                   4418: 
                   4419: sub auto_photoupdate {
                   4420:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4421:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4422:     my $host=&hostname($homeserver);
1.706     raeburn  4423:     my $cmd = '';
                   4424:     my $maxtries = 1;
1.800     albertel 4425:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4426:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4427:     }
                   4428:     $cmd =~ s/%%$//;
                   4429:     $cmd = &escape($cmd);
                   4430:     my $query = 'institutionalphotos';
                   4431:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4432:     unless ($queryid=~/^\Q$host\E\_/) {
                   4433:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4434:         return 'error: '.$queryid;
                   4435:     }
                   4436:     my $reply = &get_query_reply($queryid);
                   4437:     my $tries = 1;
                   4438:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4439:         $reply = &get_query_reply($queryid);
                   4440:         $tries ++;
                   4441:     }
                   4442:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4443:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4444:     } else {
                   4445:         my @responses = split(/:/,$reply);
                   4446:         my $outcome = shift(@responses); 
                   4447:         foreach my $item (@responses) {
                   4448:             my ($key,$value) = split(/=/,$item);
                   4449:             $$photo{$key} = $value;
                   4450:         }
                   4451:         return $outcome;
                   4452:     }
                   4453:     return 'error';
                   4454: }
                   4455: 
1.521     raeburn  4456: sub auto_instcode_format {
1.793     albertel 4457:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4458: 	$cat_order) = @_;
1.521     raeburn  4459:     my $courses = '';
1.772     raeburn  4460:     my @homeservers;
1.521     raeburn  4461:     if ($caller eq 'global') {
1.793     albertel 4462:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4463:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4464:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4465:                     push(@homeservers,$tryserver);
                   4466:                 }
1.584     raeburn  4467:             }
                   4468:         }
1.521     raeburn  4469:     } else {
1.772     raeburn  4470:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4471:     }
1.793     albertel 4472:     foreach my $code (keys(%{$instcodes})) {
                   4473:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4474:     }
                   4475:     chop($courses);
1.772     raeburn  4476:     my $ok_response = 0;
                   4477:     my $response;
                   4478:     while (@homeservers > 0 && $ok_response == 0) {
                   4479:         my $server = shift(@homeservers); 
                   4480:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4481:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4482:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4483: 		split/:/,$response;
1.772     raeburn  4484:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4485:             push(@{$codetitles},&str2array($codetitles_str));
                   4486:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4487:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4488:             $ok_response = 1;
                   4489:         }
                   4490:     }
                   4491:     if ($ok_response) {
1.521     raeburn  4492:         return 'ok';
1.772     raeburn  4493:     } else {
                   4494:         return $response;
1.521     raeburn  4495:     }
                   4496: }
                   4497: 
1.792     raeburn  4498: sub auto_instcode_defaults {
                   4499:     my ($domain,$returnhash,$code_order) = @_;
                   4500:     my @homeservers;
1.793     albertel 4501:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4502:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4503:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4504:                 push(@homeservers,$tryserver);
                   4505:             }
                   4506:         }
                   4507:     }
                   4508:     my $ok_response = 0;
                   4509:     my $response;
                   4510:     while (@homeservers > 0 && $ok_response == 0) {
                   4511:         my $server = shift(@homeservers);
                   4512:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4513:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4514:             foreach my $pair (split(/\&/,$response)) {
                   4515:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4516:                 if ($name eq 'code_order') {
1.796     raeburn  4517:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4518:                 } else {
1.796     raeburn  4519:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4520:                 }
                   4521:             }
1.804     raeburn  4522:             $ok_response = 1;
1.792     raeburn  4523:         }
                   4524:     }
                   4525:     if ($ok_response) {
                   4526:         return 'ok';
                   4527:     } else {
                   4528:         return $response;
                   4529:     }
                   4530: } 
                   4531: 
1.777     albertel 4532: sub auto_validate_class_sec {
1.773     raeburn  4533:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4534:     my $homeserver = &homeserver($cnum,$cdom);
                   4535:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4536:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4537:     return $response;
                   4538: }
                   4539: 
1.679     raeburn  4540: # ------------------------------------------------------- Course Group routines
                   4541: 
                   4542: sub get_coursegroups {
1.809     raeburn  4543:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4544:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4545: }
                   4546: 
1.679     raeburn  4547: sub modify_coursegroup {
                   4548:     my ($cdom,$cnum,$groupsettings) = @_;
                   4549:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4550: }
                   4551: 
1.809     raeburn  4552: sub toggle_coursegroup_status {
                   4553:     my ($cdom,$cnum,$group,$action) = @_;
                   4554:     my ($from_namespace,$to_namespace);
                   4555:     if ($action eq 'delete') {
                   4556:         $from_namespace = 'coursegroups';
                   4557:         $to_namespace = 'deleted_groups';
                   4558:     } else {
                   4559:         $from_namespace = 'deleted_groups';
                   4560:         $to_namespace = 'coursegroups';
                   4561:     }
                   4562:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4563:     if (my $tmp = &error(%curr_group)) {
                   4564:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4565:         return ('read error',$tmp);
                   4566:     } else {
                   4567:         my %savedsettings = %curr_group; 
1.809     raeburn  4568:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4569:         my $deloutcome;
                   4570:         if ($result eq 'ok') {
1.809     raeburn  4571:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4572:         } else {
                   4573:             return ('write error',$result);
                   4574:         }
                   4575:         if ($deloutcome eq 'ok') {
                   4576:             return 'ok';
                   4577:         } else {
                   4578:             return ('delete error',$deloutcome);
                   4579:         }
                   4580:     }
                   4581: }
                   4582: 
1.679     raeburn  4583: sub modify_group_roles {
                   4584:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4585:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4586:     my $role = 'gr/'.&escape($userprivs);
                   4587:     my ($uname,$udom) = split(/:/,$user);
                   4588:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4589:     if ($result eq 'ok') {
                   4590:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4591:     }
1.679     raeburn  4592:     return $result;
                   4593: }
                   4594: 
                   4595: sub modify_coursegroup_membership {
                   4596:     my ($cdom,$cnum,$membership) = @_;
                   4597:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4598:     return $result;
                   4599: }
                   4600: 
1.682     raeburn  4601: sub get_active_groups {
                   4602:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4603:     my $now = time;
                   4604:     my %groups = ();
                   4605:     foreach my $key (keys(%env)) {
1.811     albertel 4606:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4607:             my ($start,$end) = split(/\./,$env{$key});
                   4608:             if (($end!=0) && ($end<$now)) { next; }
                   4609:             if (($start!=0) && ($start>$now)) { next; }
                   4610:             if ($1 eq $cdom && $2 eq $cnum) {
                   4611:                 $groups{$3} = $env{$key} ;
                   4612:             }
                   4613:         }
                   4614:     }
                   4615:     return %groups;
                   4616: }
                   4617: 
1.683     raeburn  4618: sub get_group_membership {
                   4619:     my ($cdom,$cnum,$group) = @_;
                   4620:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4621: }
                   4622: 
                   4623: sub get_users_groups {
                   4624:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4625:     my @usersgroups;
1.683     raeburn  4626:     my $cachetime=1800;
                   4627: 
                   4628:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4629:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4630:     if (defined($cached)) {
1.734     albertel 4631:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4632:     } else {  
                   4633:         $grouplist = '';
1.816     raeburn  4634:         my $courseurl = &courseid_to_courseurl($courseid);
                   4635:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4636:         my $access_end = $env{'course.'.$courseid.
                   4637:                               '.default_enrollment_end_date'};
                   4638:         my $now = time;
                   4639:         foreach my $key (keys(%roleshash)) {
                   4640:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4641:                 my $group = $1;
                   4642:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4643:                     my $start = $2;
                   4644:                     my $end = $1;
                   4645:                     if ($start == -1) { next; } # deleted from group
                   4646:                     if (($start!=0) && ($start>$now)) { next; }
                   4647:                     if (($end!=0) && ($end<$now)) {
                   4648:                         if ($access_end && $access_end < $now) {
                   4649:                             if ($access_end - $end < 86400) {
                   4650:                                 push(@usersgroups,$group);
1.733     raeburn  4651:                             }
                   4652:                         }
1.817     raeburn  4653:                         next;
1.733     raeburn  4654:                     }
1.817     raeburn  4655:                     push(@usersgroups,$group);
1.683     raeburn  4656:                 }
                   4657:             }
                   4658:         }
1.817     raeburn  4659:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4660:         $grouplist = join(':',@usersgroups);
                   4661:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4662:     }
1.733     raeburn  4663:     return @usersgroups;
1.683     raeburn  4664: }
                   4665: 
                   4666: sub devalidate_getgroups_cache {
                   4667:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4668:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4669: 
1.683     raeburn  4670:     my $hashid="$udom:$uname:$courseid";
                   4671:     &devalidate_cache_new('getgroups',$hashid);
                   4672: }
                   4673: 
1.12      www      4674: # ------------------------------------------------------------------ Plain Text
                   4675: 
                   4676: sub plaintext {
1.742     raeburn  4677:     my ($short,$type,$cid) = @_;
1.758     albertel 4678:     if ($short =~ /^cr/) {
                   4679: 	return (split('/',$short))[-1];
                   4680:     }
1.742     raeburn  4681:     if (!defined($cid)) {
                   4682:         $cid = $env{'request.course.id'};
                   4683:     }
                   4684:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4685:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4686:                                           '.plaintext'});
                   4687:     }
                   4688:     my %rolenames = (
                   4689:                       Course => 'std',
                   4690:                       Group => 'alt1',
                   4691:                     );
                   4692:     if (defined($type) && 
                   4693:          defined($rolenames{$type}) && 
                   4694:          defined($prp{$short}{$rolenames{$type}})) {
                   4695:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4696:     } else {
                   4697:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4698:     }
1.12      www      4699: }
                   4700: 
                   4701: # ----------------------------------------------------------------- Assign Role
                   4702: 
                   4703: sub assignrole {
1.357     www      4704:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4705:     my $mrole;
                   4706:     if ($role =~ /^cr\//) {
1.393     www      4707:         my $cwosec=$url;
1.811     albertel 4708:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4709: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4710:            &logthis('Refused custom assignrole: '.
                   4711:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4712: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4713:            return 'refused'; 
                   4714:         }
1.21      www      4715:         $mrole='cr';
1.678     raeburn  4716:     } elsif ($role =~ /^gr\//) {
                   4717:         my $cwogrp=$url;
1.811     albertel 4718:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4719:         unless (&allowed('mdg',$cwogrp)) {
                   4720:             &logthis('Refused group assignrole: '.
                   4721:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4722:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4723:             return 'refused';
                   4724:         }
                   4725:         $mrole='gr';
1.21      www      4726:     } else {
1.82      www      4727:         my $cwosec=$url;
1.811     albertel 4728:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4729:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4730:            &logthis('Refused assignrole: '.
                   4731:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4732: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4733:            return 'refused'; 
                   4734:         }
1.21      www      4735:         $mrole=$role;
                   4736:     }
1.620     albertel 4737:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4738:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4739:     if ($end) { $command.='_'.$end; }
1.21      www      4740:     if ($start) {
                   4741: 	if ($end) { 
1.81      www      4742:            $command.='_'.$start; 
1.21      www      4743:         } else {
1.81      www      4744:            $command.='_0_'.$start;
1.21      www      4745:         }
                   4746:     }
1.739     raeburn  4747:     my $origstart = $start;
                   4748:     my $origend = $end;
1.357     www      4749: # actually delete
                   4750:     if ($deleteflag) {
1.373     www      4751: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4752: # modify command to delete the role
1.620     albertel 4753:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4754:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4755: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4756: # set start and finish to negative values for userrolelog
                   4757:            $start=-1;
                   4758:            $end=-1;
                   4759:         }
                   4760:     }
                   4761: # send command
1.349     www      4762:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4763: # log new user role if status is ok
1.349     www      4764:     if ($answer eq 'ok') {
1.663     raeburn  4765: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4766: # for course roles, perform group memberships changes triggered by role change.
                   4767:         unless ($role =~ /^gr/) {
                   4768:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4769:                                              $origstart);
                   4770:         }
1.349     www      4771:     }
                   4772:     return $answer;
1.169     harris41 4773: }
                   4774: 
                   4775: # -------------------------------------------------- Modify user authentication
1.197     www      4776: # Overrides without validation
                   4777: 
1.169     harris41 4778: sub modifyuserauth {
                   4779:     my ($udom,$uname,$umode,$upass)=@_;
                   4780:     my $uhome=&homeserver($uname,$udom);
1.197     www      4781:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4782:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4783:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4784:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4785:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4786: 		     &escape($upass),$uhome);
1.620     albertel 4787:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4788:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4789:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4790:     &log($udom,,$uname,$uhome,
1.620     albertel 4791:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4792:                                      $env{'user.name'}.', '.$umode.
1.197     www      4793:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4794:     unless ($reply eq 'ok') {
1.197     www      4795:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4796: 	return 'error: '.$reply;
                   4797:     }   
1.170     harris41 4798:     return 'ok';
1.80      www      4799: }
                   4800: 
1.81      www      4801: # --------------------------------------------------------------- Modify a user
1.80      www      4802: 
1.81      www      4803: sub modifyuser {
1.206     matthew  4804:     my ($udom,    $uname, $uid,
                   4805:         $umode,   $upass, $first,
                   4806:         $middle,  $last,  $gene,
1.387     www      4807:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4808:     $udom= &LONCAPA::clean_domain($udom);
                   4809:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4810:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4811:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4812: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4813:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4814:                                      ' desiredhome not specified'). 
1.620     albertel 4815:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4816:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4817:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4818: # ----------------------------------------------------------------- Create User
1.406     albertel 4819:     if (($uhome eq 'no_host') && 
                   4820: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4821:         my $unhome='';
1.209     matthew  4822:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4823:             $unhome = $desiredhome;
1.620     albertel 4824: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4825: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4826:         } else { # load balancing routine for determining $unhome
1.80      www      4827:             my $tryserver;
1.81      www      4828:             my $loadm=10000000;
1.80      www      4829:             foreach $tryserver (keys %libserv) {
                   4830: 	       if ($hostdom{$tryserver} eq $udom) {
                   4831:                   my $answer=reply('load',$tryserver);
                   4832:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4833: 		      $loadm=$answer;
                   4834:                       $unhome=$tryserver;
                   4835:                   }
                   4836: 	       }
                   4837: 	    }
                   4838:         }
                   4839:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4840: 	    return 'error: unable to find a home server for '.$uname.
                   4841:                    ' in domain '.$udom;
1.80      www      4842:         }
                   4843:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4844:                          &escape($upass),$unhome);
                   4845: 	unless ($reply eq 'ok') {
                   4846:             return 'error: '.$reply;
                   4847:         }   
1.230     stredwic 4848:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4849:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4850: 	    return 'error: unable verify users home machine.';
1.80      www      4851:         }
1.209     matthew  4852:     }   # End of creation of new user
1.80      www      4853: # ---------------------------------------------------------------------- Add ID
                   4854:     if ($uid) {
                   4855:        $uid=~tr/A-Z/a-z/;
                   4856:        my %uidhash=&idrget($udom,$uname);
1.196     www      4857:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4858:          && (!$forceid)) {
1.80      www      4859: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4860: 	      return 'error: user id "'.$uid.'" does not match '.
                   4861:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4862:           }
                   4863:        } else {
                   4864: 	  &idput($udom,($uname => $uid));
                   4865:        }
                   4866:     }
                   4867: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4868:     my @tmp=&get('environment',
1.134     albertel 4869: 		   ['firstname','middlename','lastname','generation'],
                   4870: 		   $udom,$uname);
1.313     matthew  4871:     my %names;
                   4872:     if ($tmp[0] =~ m/^error:.*/) { 
                   4873:         %names=(); 
                   4874:     } else {
                   4875:         %names = @tmp;
                   4876:     }
1.388     www      4877: #
                   4878: # Make sure to not trash student environment if instructor does not bother
                   4879: # to supply name and email information
                   4880: #
                   4881:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4882:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4883:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4884:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4885:     if ($email) {
                   4886:        $email=~s/[^\w\@\.\-\,]//gs;
                   4887:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4888: 			   $names{'critnotification'} = $email;
                   4889: 			   $names{'permanentemail'} = $email; }
                   4890:     }
1.134     albertel 4891:     my $reply = &put('environment', \%names, $udom,$uname);
                   4892:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4893:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4894:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4895:              $umode.', '.$first.', '.$middle.', '.
                   4896: 	     $last.', '.$gene.' by '.
1.620     albertel 4897:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4898:     return 'ok';
1.80      www      4899: }
                   4900: 
1.81      www      4901: # -------------------------------------------------------------- Modify student
1.80      www      4902: 
1.81      www      4903: sub modifystudent {
                   4904:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4905:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4906:     if (!$cid) {
1.620     albertel 4907: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4908: 	    return 'not_in_class';
                   4909: 	}
1.80      www      4910:     }
                   4911: # --------------------------------------------------------------- Make the user
1.81      www      4912:     my $reply=&modifyuser
1.209     matthew  4913: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4914:          $desiredhome,$email);
1.80      www      4915:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4916:     # This will cause &modify_student_enrollment to get the uid from the
                   4917:     # students environment
                   4918:     $uid = undef if (!$forceid);
1.455     albertel 4919:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4920: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4921:     return $reply;
                   4922: }
                   4923: 
                   4924: sub modify_student_enrollment {
1.515     raeburn  4925:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4926:     my ($cdom,$cnum,$chome);
                   4927:     if (!$cid) {
1.620     albertel 4928: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4929: 	    return 'not_in_class';
                   4930: 	}
1.620     albertel 4931: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4932: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4933:     } else {
                   4934: 	($cdom,$cnum)=split(/_/,$cid);
                   4935:     }
1.620     albertel 4936:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4937:     if (!$chome) {
1.457     raeburn  4938: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4939:     }
1.455     albertel 4940:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4941:     # Make sure the user exists
1.81      www      4942:     my $uhome=&homeserver($uname,$udom);
                   4943:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4944: 	return 'error: no such user';
                   4945:     }
1.297     matthew  4946:     # Get student data if we were not given enough information
                   4947:     if (!defined($first)  || $first  eq '' || 
                   4948:         !defined($last)   || $last   eq '' || 
                   4949:         !defined($uid)    || $uid    eq '' || 
                   4950:         !defined($middle) || $middle eq '' || 
                   4951:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4952:         # They did not supply us with enough data to enroll the student, so
                   4953:         # we need to pick up more information.
1.297     matthew  4954:         my %tmp = &get('environment',
1.294     matthew  4955:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4956:                        ,$udom,$uname);
                   4957: 
1.800     albertel 4958:         #foreach my $key (keys(%tmp)) {
                   4959:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4960:         #}
1.294     matthew  4961:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4962:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4963:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4964:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4965:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4966:     }
1.556     albertel 4967:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4968:     my $reply=cput('classlist',
                   4969: 		   {"$uname:$udom" => 
1.515     raeburn  4970: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4971: 		   $cdom,$cnum);
1.81      www      4972:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4973: 	return 'error: '.$reply;
1.652     albertel 4974:     } else {
                   4975: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4976:     }
1.297     matthew  4977:     # Add student role to user
1.83      www      4978:     my $uurl='/'.$cid;
1.81      www      4979:     $uurl=~s/\_/\//g;
                   4980:     if ($usec) {
                   4981: 	$uurl.='/'.$usec;
                   4982:     }
                   4983:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4984: }
                   4985: 
1.556     albertel 4986: sub format_name {
                   4987:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4988:     my $name;
                   4989:     if ($first ne 'lastname') {
                   4990: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4991:     } else {
                   4992: 	if ($lastname=~/\S/) {
                   4993: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4994: 	    $name=~s/\s+,/,/;
                   4995: 	} else {
                   4996: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4997: 	}
                   4998:     }
                   4999:     $name=~s/^\s+//;
                   5000:     $name=~s/\s+$//;
                   5001:     $name=~s/\s+/ /g;
                   5002:     return $name;
                   5003: }
                   5004: 
1.84      www      5005: # ------------------------------------------------- Write to course preferences
                   5006: 
                   5007: sub writecoursepref {
                   5008:     my ($courseid,%prefs)=@_;
                   5009:     $courseid=~s/^\///;
                   5010:     $courseid=~s/\_/\//g;
                   5011:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5012:     my $chome=homeserver($cnum,$cdomain);
                   5013:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5014: 	return 'error: no such course';
                   5015:     }
                   5016:     my $cstring='';
1.800     albertel 5017:     foreach my $pref (keys(%prefs)) {
                   5018: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5019:     }
1.84      www      5020:     $cstring=~s/\&$//;
                   5021:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5022: }
                   5023: 
                   5024: # ---------------------------------------------------------- Make/modify course
                   5025: 
                   5026: sub createcourse {
1.741     raeburn  5027:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5028:         $course_owner,$crstype)=@_;
1.84      www      5029:     $url=&declutter($url);
                   5030:     my $cid='';
1.264     matthew  5031:     unless (&allowed('ccc',$udom)) {
1.84      www      5032:         return 'refused';
                   5033:     }
                   5034: # ------------------------------------------------------------------- Create ID
1.674     www      5035:    my $uname=int(1+rand(9)).
                   5036:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5037:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5038:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5039: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5040:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5041:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5042:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5043:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5044:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5045:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5046:            return 'error: unable to generate unique course-ID';
                   5047:        } 
                   5048:    }
1.264     matthew  5049: # ------------------------------------------------ Check supplied server name
1.620     albertel 5050:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  5051:     if (! exists($libserv{$course_server})) {
                   5052:         return 'error:bad server name '.$course_server;
                   5053:     }
1.84      www      5054: # ------------------------------------------------------------- Make the course
                   5055:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5056:                       $course_server);
1.84      www      5057:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5058:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5059:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5060: 	return 'error: no such course';
                   5061:     }
1.271     www      5062: # ----------------------------------------------------------------- Course made
1.516     raeburn  5063: # log existence
                   5064:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5065:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5066:                   &escape($crstype),$uhome);
1.358     www      5067:     &flushcourselogs();
                   5068: # set toplevel url
1.271     www      5069:     my $topurl=$url;
                   5070:     unless ($nonstandard) {
                   5071: # ------------------------------------------ For standard courses, make top url
                   5072:         my $mapurl=&clutter($url);
1.278     www      5073:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5074:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5075: <map>
                   5076: <resource id="1" type="start"></resource>
                   5077: <resource id="2" src="$mapurl"></resource>
                   5078: <resource id="3" type="finish"></resource>
                   5079: <link index="1" from="1" to="2"></link>
                   5080: <link index="2" from="2" to="3"></link>
                   5081: </map>
                   5082: ENDINITMAP
                   5083:         $topurl=&declutter(
1.638     albertel 5084:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5085:                           );
                   5086:     }
                   5087: # ----------------------------------------------------------- Write preferences
1.84      www      5088:     &writecoursepref($udom.'_'.$uname,
                   5089:                      ('description' => $description,
1.271     www      5090:                       'url'         => $topurl));
1.84      www      5091:     return '/'.$udom.'/'.$uname;
                   5092: }
                   5093: 
1.813     albertel 5094: sub is_course {
                   5095:     my ($cdom,$cnum) = @_;
                   5096:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5097: 				undef,'.');
                   5098:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5099:         return 1;
                   5100:     }
                   5101:     return 0;
                   5102: }
                   5103: 
1.21      www      5104: # ---------------------------------------------------------- Assign Custom Role
                   5105: 
                   5106: sub assigncustomrole {
1.357     www      5107:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5108:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5109:                        $end,$start,$deleteflag);
1.21      www      5110: }
                   5111: 
                   5112: # ----------------------------------------------------------------- Revoke Role
                   5113: 
                   5114: sub revokerole {
1.357     www      5115:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5116:     my $now=time;
1.357     www      5117:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5118: }
                   5119: 
                   5120: # ---------------------------------------------------------- Revoke Custom Role
                   5121: 
                   5122: sub revokecustomrole {
1.357     www      5123:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5124:     my $now=time;
1.357     www      5125:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5126:            $deleteflag);
1.17      www      5127: }
                   5128: 
1.533     banghart 5129: # ------------------------------------------------------------ Disk usage
1.535     albertel 5130: sub diskusage {
1.533     banghart 5131:     my ($udom,$uname,$directoryRoot)=@_;
                   5132:     $directoryRoot =~ s/\/$//;
1.535     albertel 5133:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5134:     return $listing;
1.512     banghart 5135: }
                   5136: 
1.566     banghart 5137: sub is_locked {
                   5138:     my ($file_name, $domain, $user) = @_;
                   5139:     my @check;
                   5140:     my $is_locked;
                   5141:     push @check, $file_name;
1.613     albertel 5142:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5143: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5144:     my ($tmp)=keys(%locked);
                   5145:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5146:     
1.566     banghart 5147:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5148:         $is_locked = 'false';
                   5149:         foreach my $entry (@{$locked{$file_name}}) {
                   5150:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5151:                $is_locked = 'true';
                   5152:                last;
1.745     raeburn  5153:            }
                   5154:        }
1.566     banghart 5155:     } else {
                   5156:         $is_locked = 'false';
                   5157:     }
                   5158: }
                   5159: 
1.759     albertel 5160: sub declutter_portfile {
                   5161:     my ($file) = @_;
1.833     albertel 5162:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5163:     return $file;
                   5164: }
                   5165: 
1.559     banghart 5166: # ------------------------------------------------------------- Mark as Read Only
                   5167: 
                   5168: sub mark_as_readonly {
                   5169:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5170:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5171:     my ($tmp)=keys(%current_permissions);
                   5172:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5173:     foreach my $file (@{$files}) {
1.759     albertel 5174: 	$file = &declutter_portfile($file);
1.561     banghart 5175:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5176:     }
1.613     albertel 5177:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5178:     return;
                   5179: }
                   5180: 
1.572     banghart 5181: # ------------------------------------------------------------Save Selected Files
                   5182: 
                   5183: sub save_selected_files {
                   5184:     my ($user, $path, @files) = @_;
                   5185:     my $filename = $user."savedfiles";
1.573     banghart 5186:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5187:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5188:     foreach my $file (@files) {
1.620     albertel 5189:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5190:     }
                   5191:     foreach my $file (@other_files) {
1.574     banghart 5192:         print (OUT $file."\n");
1.572     banghart 5193:     }
1.574     banghart 5194:     close (OUT);
1.572     banghart 5195:     return 'ok';
                   5196: }
                   5197: 
1.574     banghart 5198: sub clear_selected_files {
                   5199:     my ($user) = @_;
                   5200:     my $filename = $user."savedfiles";
                   5201:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5202:     print (OUT undef);
                   5203:     close (OUT);
                   5204:     return ("ok");    
                   5205: }
                   5206: 
1.572     banghart 5207: sub files_in_path {
                   5208:     my ($user, $path) = @_;
                   5209:     my $filename = $user."savedfiles";
                   5210:     my %return_files;
1.574     banghart 5211:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5212:     while (my $line_in = <IN>) {
1.574     banghart 5213:         chomp ($line_in);
                   5214:         my @paths_and_file = split (m!/!, $line_in);
                   5215:         my $file_part = pop (@paths_and_file);
                   5216:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5217:         $path_part.='/';
                   5218:         my $path_and_file = $path_part.$file_part;
                   5219:         if ($path_part eq $path) {
                   5220:             $return_files{$file_part}= 'selected';
                   5221:         }
                   5222:     }
1.574     banghart 5223:     close (IN);
                   5224:     return (\%return_files);
1.572     banghart 5225: }
                   5226: 
                   5227: # called in portfolio select mode, to show files selected NOT in current directory
                   5228: sub files_not_in_path {
                   5229:     my ($user, $path) = @_;
                   5230:     my $filename = $user."savedfiles";
                   5231:     my @return_files;
                   5232:     my $path_part;
1.800     albertel 5233:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5234:     while (my $line = <IN>) {
1.572     banghart 5235:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5236:         my @paths_and_file = split(m|/|, $line);
                   5237:         my $file_part = pop(@paths_and_file);
                   5238:         chomp($file_part);
                   5239:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5240:         $path_part .= '/';
                   5241:         my $path_and_file = $path_part.$file_part;
                   5242:         if ($path_part ne $path) {
1.800     albertel 5243:             push(@return_files, ($path_and_file));
1.572     banghart 5244:         }
                   5245:     }
1.800     albertel 5246:     close(OUT);
1.574     banghart 5247:     return (@return_files);
1.572     banghart 5248: }
                   5249: 
1.745     raeburn  5250: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5251: 
1.745     raeburn  5252: sub get_portfile_permissions {
                   5253:     my ($domain,$user) = @_;
1.613     albertel 5254:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5255:     my ($tmp)=keys(%current_permissions);
                   5256:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5257:     return \%current_permissions;
                   5258: }
                   5259: 
                   5260: #---------------------------------------------Get portfolio file access controls
                   5261: 
1.749     raeburn  5262: sub get_access_controls {
1.745     raeburn  5263:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5264:     my %access;
                   5265:     my $real_file = $file;
                   5266:     $file =~ s/\.meta$//;
1.745     raeburn  5267:     if (defined($file)) {
1.749     raeburn  5268:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5269:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5270:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5271:             }
                   5272:         }
1.745     raeburn  5273:     } else {
1.749     raeburn  5274:         foreach my $key (keys(%{$current_permissions})) {
                   5275:             if ($key =~ /\0accesscontrol$/) {
                   5276:                 if (defined($group)) {
                   5277:                     if ($key !~ m-^\Q$group\E/-) {
                   5278:                         next;
                   5279:                     }
                   5280:                 }
                   5281:                 my ($fullpath) = split(/\0/,$key);
                   5282:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5283:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5284:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5285:                     }
                   5286:                 }
                   5287:             }
                   5288:         }
                   5289:     }
                   5290:     return %access;
                   5291: }
                   5292: 
                   5293: sub modify_access_controls {
                   5294:     my ($file_name,$changes,$domain,$user)=@_;
                   5295:     my ($outcome,$deloutcome);
                   5296:     my %store_permissions;
                   5297:     my %new_values;
                   5298:     my %new_control;
                   5299:     my %translation;
                   5300:     my @deletions = ();
                   5301:     my $now = time;
                   5302:     if (exists($$changes{'activate'})) {
                   5303:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5304:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5305:             my $numnew = scalar(@newitems);
                   5306:             for (my $i=0; $i<$numnew; $i++) {
                   5307:                 my $newkey = $newitems[$i];
                   5308:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5309:                 if ($newkey =~ /^\d+:/) { 
                   5310:                     $newkey =~ s/^(\d+)/$newid/;
                   5311:                     $translation{$1} = $newid;
                   5312:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5313:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5314:                     $translation{$1} = $newid;
                   5315:                 }
1.749     raeburn  5316:                 $new_values{$file_name."\0".$newkey} = 
                   5317:                                           $$changes{'activate'}{$newitems[$i]};
                   5318:                 $new_control{$newkey} = $now;
                   5319:             }
                   5320:         }
                   5321:     }
                   5322:     my %todelete;
                   5323:     my %changed_items;
                   5324:     foreach my $action ('delete','update') {
                   5325:         if (exists($$changes{$action})) {
                   5326:             if (ref($$changes{$action}) eq 'HASH') {
                   5327:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5328:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5329:                     if ($action eq 'delete') { 
                   5330:                         $todelete{$itemnum} = 1;
                   5331:                     } else {
                   5332:                         $changed_items{$itemnum} = $key;
                   5333:                     }
                   5334:                 }
1.745     raeburn  5335:             }
                   5336:         }
1.749     raeburn  5337:     }
                   5338:     # get lock on access controls for file.
                   5339:     my $lockhash = {
                   5340:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5341:                                                        ':'.$env{'user.domain'},
                   5342:                    }; 
                   5343:     my $tries = 0;
                   5344:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5345:    
                   5346:     while (($gotlock ne 'ok') && $tries <3) {
                   5347:         $tries ++;
                   5348:         sleep 1;
                   5349:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5350:     }
                   5351:     if ($gotlock eq 'ok') {
                   5352:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5353:         my ($tmp)=keys(%curr_permissions);
                   5354:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5355:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5356:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5357:             if (ref($curr_controls) eq 'HASH') {
                   5358:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5359:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5360:                     if (defined($todelete{$itemnum})) {
                   5361:                         push(@deletions,$file_name."\0".$control_item);
                   5362:                     } else {
                   5363:                         if (defined($changed_items{$itemnum})) {
                   5364:                             $new_control{$changed_items{$itemnum}} = $now;
                   5365:                             push(@deletions,$file_name."\0".$control_item);
                   5366:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5367:                         } else {
                   5368:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5369:                         }
                   5370:                     }
1.745     raeburn  5371:                 }
                   5372:             }
                   5373:         }
1.749     raeburn  5374:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5375:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5376:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5377:         #  remove lock
                   5378:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5379:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5380:         my ($file,$group);
                   5381:         if (&is_course($domain,$user)) {
                   5382:             ($group,$file) = split(/\//,$file_name,2);
                   5383:         } else {
                   5384:             $file = $file_name;
                   5385:         }
                   5386:         my $sqlresult =
                   5387:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5388:                                     $group);
1.749     raeburn  5389:     } else {
                   5390:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5391:     }
1.749     raeburn  5392:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5393: }
                   5394: 
1.827     raeburn  5395: sub make_public_indefinitely {
                   5396:     my ($requrl) = @_;
                   5397:     my $now = time;
                   5398:     my $action = 'activate';
                   5399:     my $aclnum = 0;
                   5400:     if (&is_portfolio_url($requrl)) {
                   5401:         my (undef,$udom,$unum,$file_name,$group) =
                   5402:             &parse_portfolio_url($requrl);
                   5403:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5404:         my %access_controls = &get_access_controls($current_perms,
                   5405:                                                    $group,$file_name);
                   5406:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5407:             my ($num,$scope,$end,$start) = 
                   5408:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5409:             if ($scope eq 'public') {
                   5410:                 if ($start <= $now && $end == 0) {
                   5411:                     $action = 'none';
                   5412:                 } else {
                   5413:                     $action = 'update';
                   5414:                     $aclnum = $num;
                   5415:                 }
                   5416:                 last;
                   5417:             }
                   5418:         }
                   5419:         if ($action eq 'none') {
                   5420:              return 'ok';
                   5421:         } else {
                   5422:             my %changes;
                   5423:             my $newend = 0;
                   5424:             my $newstart = $now;
                   5425:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5426:             $changes{$action}{$newkey} = {
                   5427:                 type => 'public',
                   5428:                 time => {
                   5429:                     start => $newstart,
                   5430:                     end   => $newend,
                   5431:                 },
                   5432:             };
                   5433:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5434:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5435:             return $outcome;
                   5436:         }
                   5437:     } else {
                   5438:         return 'invalid';
                   5439:     }
                   5440: }
                   5441: 
1.745     raeburn  5442: #------------------------------------------------------Get Marked as Read Only
                   5443: 
                   5444: sub get_marked_as_readonly {
                   5445:     my ($domain,$user,$what,$group) = @_;
                   5446:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5447:     my @readonly_files;
1.629     banghart 5448:     my $cmp1=$what;
                   5449:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5450:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5451:         if (defined($group)) {
                   5452:             if ($file_name !~ m-^\Q$group\E/-) {
                   5453:                 next;
                   5454:             }
                   5455:         }
1.561     banghart 5456:         if (ref($value) eq "ARRAY"){
                   5457:             foreach my $stored_what (@{$value}) {
1.629     banghart 5458:                 my $cmp2=$stored_what;
1.759     albertel 5459:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5460:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5461:                 }
1.629     banghart 5462:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5463:                     push(@readonly_files, $file_name);
1.745     raeburn  5464:                     last;
1.563     banghart 5465:                 } elsif (!defined($what)) {
                   5466:                     push(@readonly_files, $file_name);
1.745     raeburn  5467:                     last;
1.561     banghart 5468:                 }
                   5469:             }
1.745     raeburn  5470:         }
1.561     banghart 5471:     }
                   5472:     return @readonly_files;
                   5473: }
1.577     banghart 5474: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5475: 
1.577     banghart 5476: sub get_marked_as_readonly_hash {
1.745     raeburn  5477:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5478:     my %readonly_files;
1.745     raeburn  5479:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5480:         if (defined($group)) {
                   5481:             if ($file_name !~ m-^\Q$group\E/-) {
                   5482:                 next;
                   5483:             }
                   5484:         }
1.577     banghart 5485:         if (ref($value) eq "ARRAY"){
                   5486:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5487:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5488:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5489:                         if ($lock_descriptor eq 'graded') {
                   5490:                             $readonly_files{$file_name} = 'graded';
                   5491:                         } elsif ($lock_descriptor eq 'handback') {
                   5492:                             $readonly_files{$file_name} = 'handback';
                   5493:                         } else {
                   5494:                             if (!exists($readonly_files{$file_name})) {
                   5495:                                 $readonly_files{$file_name} = 'locked';
                   5496:                             }
                   5497:                         }
1.745     raeburn  5498:                     }
1.750     banghart 5499:                 } 
1.577     banghart 5500:             }
                   5501:         } 
                   5502:     }
                   5503:     return %readonly_files;
                   5504: }
1.559     banghart 5505: # ------------------------------------------------------------ Unmark as Read Only
                   5506: 
                   5507: sub unmark_as_readonly {
1.629     banghart 5508:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5509:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5510:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5511:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5512:     my $symb_crs = $what;
                   5513:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5514:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5515:     my ($tmp)=keys(%current_permissions);
                   5516:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5517:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5518:     foreach my $file (@readonly_files) {
1.759     albertel 5519: 	my $clean_file = &declutter_portfile($file);
                   5520: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5521: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5522:         my @new_locks;
                   5523:         my @del_keys;
                   5524:         if (ref($current_locks) eq "ARRAY"){
                   5525:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5526:                 my $compare=$locker;
1.749     raeburn  5527:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5528:                     $compare=join('',@{$locker});
1.746     raeburn  5529:                     if ($compare ne $symb_crs) {
                   5530:                         push(@new_locks, $locker);
                   5531:                     }
1.563     banghart 5532:                 }
                   5533:             }
1.650     albertel 5534:             if (scalar(@new_locks) > 0) {
1.563     banghart 5535:                 $current_permissions{$file} = \@new_locks;
                   5536:             } else {
                   5537:                 push(@del_keys, $file);
1.613     albertel 5538:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5539:                 delete($current_permissions{$file});
1.563     banghart 5540:             }
                   5541:         }
1.561     banghart 5542:     }
1.613     albertel 5543:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5544:     return;
                   5545: }
1.512     banghart 5546: 
1.17      www      5547: # ------------------------------------------------------------ Directory lister
                   5548: 
                   5549: sub dirlist {
1.253     stredwic 5550:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5551: 
1.18      www      5552:     $uri=~s/^\///;
                   5553:     $uri=~s/\/$//;
1.253     stredwic 5554:     my ($udom, $uname);
                   5555:     (undef,$udom,$uname)=split(/\//,$uri);
                   5556:     if(defined($userdomain)) {
                   5557:         $udom = $userdomain;
                   5558:     }
                   5559:     if(defined($username)) {
                   5560:         $uname = $username;
                   5561:     }
                   5562: 
                   5563:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5564:     if(defined($alternateDirectoryRoot)) {
                   5565:         $dirRoot = $alternateDirectoryRoot;
                   5566:         $dirRoot =~ s/\/$//;
1.751     banghart 5567:     }
1.253     stredwic 5568: 
                   5569:     if($udom) {
                   5570:         if($uname) {
1.800     albertel 5571:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5572: 				 &homeserver($uname,$udom));
1.605     matthew  5573:             my @listing_results;
                   5574:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5575:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5576: 				  &homeserver($uname,$udom));
1.605     matthew  5577:                 @listing_results = split(/:/,$listing);
                   5578:             } else {
                   5579:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5580:             }
                   5581:             return @listing_results;
1.253     stredwic 5582:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5583:             my %allusers;
                   5584:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5585:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5586:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5587: 					 $udom, $tryserver);
1.605     matthew  5588:                     my @listing_results;
                   5589:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5590:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5591: 					  $udom, $tryserver);
1.605     matthew  5592:                         @listing_results = split(/:/,$listing);
                   5593:                     } else {
                   5594:                         @listing_results =
                   5595:                             map { &unescape($_); } split(/:/,$listing);
                   5596:                     }
                   5597:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5598:                         $listing_results[0] ne 'empty'       &&
                   5599:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5600:                         foreach my $line (@listing_results) {
                   5601:                             my ($entry) = split(/&/,$line,2);
                   5602:                             $allusers{$entry} = 1;
1.253     stredwic 5603:                         }
                   5604:                     }
1.191     harris41 5605:                 }
1.253     stredwic 5606:             }
                   5607:             my $alluserstr='';
1.800     albertel 5608:             foreach my $user (sort(keys(%allusers))) {
                   5609:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5610:             }
                   5611:             $alluserstr=~s/:$//;
                   5612:             return split(/:/,$alluserstr);
                   5613:         } else {
1.800     albertel 5614:             return ('missing user name');
1.253     stredwic 5615:         }
                   5616:     } elsif(!defined($alternateDirectoryRoot)) {
                   5617:         my $tryserver;
                   5618:         my %alldom=();
1.800     albertel 5619:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5620:             $alldom{$hostdom{$tryserver}}=1;
                   5621:         }
                   5622:         my $alldomstr='';
1.800     albertel 5623:         foreach my $domain (sort(keys(%alldom))) {
                   5624:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5625:         }
                   5626:         $alldomstr=~s/:$//;
                   5627:         return split(/:/,$alldomstr);       
                   5628:     } else {
1.800     albertel 5629:         return ('missing domain');
1.275     stredwic 5630:     }
                   5631: }
                   5632: 
                   5633: # --------------------------------------------- GetFileTimestamp
                   5634: # This function utilizes dirlist and returns the date stamp for
                   5635: # when it was last modified.  It will also return an error of -1
                   5636: # if an error occurs
                   5637: 
1.410     matthew  5638: ##
                   5639: ## FIXME: This subroutine assumes its caller knows something about the
                   5640: ## directory structure of the home server for the student ($root).
                   5641: ## Not a good assumption to make.  Since this is for looking up files
                   5642: ## in user directories, the full path should be constructed by lond, not
                   5643: ## whatever machine we request data from.
                   5644: ##
1.275     stredwic 5645: sub GetFileTimestamp {
                   5646:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5647:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5648:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5649:     my $subdir=$studentName.'__';
                   5650:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5651:     my $proname="$studentDomain/$subdir/$studentName";
                   5652:     $proname .= '/'.$filename;
1.375     matthew  5653:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5654:                                               $studentName, $root);
1.275     stredwic 5655:     my @stats = split('&', $fileStat);
                   5656:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5657:         # @stats contains first the filename, then the stat output
                   5658:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5659:     } else {
                   5660:         return -1;
1.253     stredwic 5661:     }
1.26      www      5662: }
                   5663: 
1.712     albertel 5664: sub stat_file {
                   5665:     my ($uri) = @_;
1.787     albertel 5666:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5667: 
1.712     albertel 5668:     my ($udom,$uname,$file,$dir);
                   5669:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5670: 	($udom,$uname,$file) =
1.811     albertel 5671: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5672: 	$file = 'userfiles/'.$file;
1.740     www      5673: 	$dir = &propath($udom,$uname);
1.712     albertel 5674:     }
                   5675:     if ($uri =~ m-^/res/-) {
                   5676: 	($udom,$uname) = 
1.807     albertel 5677: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5678: 	$file = $uri;
                   5679:     }
                   5680: 
                   5681:     if (!$udom || !$uname || !$file) {
                   5682: 	# unable to handle the uri
                   5683: 	return ();
                   5684:     }
                   5685: 
                   5686:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5687:     my @stats = split('&', $result);
1.721     banghart 5688:     
1.712     albertel 5689:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5690: 	shift(@stats); #filename is first
                   5691: 	return @stats;
                   5692:     }
                   5693:     return ();
                   5694: }
                   5695: 
1.26      www      5696: # -------------------------------------------------------- Value of a Condition
                   5697: 
1.713     albertel 5698: # gets the value of a specific preevaluated condition
                   5699: #    stored in the string  $env{user.state.<cid>}
                   5700: # or looks up a condition reference in the bighash and if if hasn't
                   5701: # already been evaluated recurses into docondval to get the value of
                   5702: # the condition, then memoizing it to 
                   5703: #   $env{user.state.<cid>.<condition>}
1.40      www      5704: sub directcondval {
                   5705:     my $number=shift;
1.620     albertel 5706:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5707: 	&Apache::lonuserstate::evalstate();
                   5708:     }
1.713     albertel 5709:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5710: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5711:     } elsif ($number =~ /^_/) {
                   5712: 	my $sub_condition;
                   5713: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5714: 		&GDBM_READER(),0640)) {
                   5715: 	    $sub_condition=$bighash{'conditions'.$number};
                   5716: 	    untie(%bighash);
                   5717: 	}
                   5718: 	my $value = &docondval($sub_condition);
                   5719: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5720: 	return $value;
                   5721:     }
1.620     albertel 5722:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5723:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5724:     } else {
                   5725:        return 2;
                   5726:     }
                   5727: }
                   5728: 
1.713     albertel 5729: # get the collection of conditions for this resource
1.26      www      5730: sub condval {
                   5731:     my $condidx=shift;
1.54      www      5732:     my $allpathcond='';
1.713     albertel 5733:     foreach my $cond (split(/\|/,$condidx)) {
                   5734: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5735: 	    $allpathcond.=
                   5736: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5737: 	}
1.191     harris41 5738:     }
1.54      www      5739:     $allpathcond=~s/\|$//;
1.713     albertel 5740:     return &docondval($allpathcond);
                   5741: }
                   5742: 
                   5743: #evaluates an expression of conditions
                   5744: sub docondval {
                   5745:     my ($allpathcond) = @_;
                   5746:     my $result=0;
                   5747:     if ($env{'request.course.id'}
                   5748: 	&& defined($allpathcond)) {
                   5749: 	my $operand='|';
                   5750: 	my @stack;
                   5751: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5752: 	    if ($chunk eq '(') {
                   5753: 		push @stack,($operand,$result);
                   5754: 	    } elsif ($chunk eq ')') {
                   5755: 		my $before=pop @stack;
                   5756: 		if (pop @stack eq '&') {
                   5757: 		    $result=$result>$before?$before:$result;
                   5758: 		} else {
                   5759: 		    $result=$result>$before?$result:$before;
                   5760: 		}
                   5761: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5762: 		$operand=$chunk;
                   5763: 	    } else {
                   5764: 		my $new=directcondval($chunk);
                   5765: 		if ($operand eq '&') {
                   5766: 		    $result=$result>$new?$new:$result;
                   5767: 		} else {
                   5768: 		    $result=$result>$new?$result:$new;
                   5769: 		}
                   5770: 	    }
                   5771: 	}
1.26      www      5772:     }
                   5773:     return $result;
1.421     albertel 5774: }
                   5775: 
                   5776: # ---------------------------------------------------- Devalidate courseresdata
                   5777: 
                   5778: sub devalidatecourseresdata {
                   5779:     my ($coursenum,$coursedomain)=@_;
                   5780:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5781:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5782: }
                   5783: 
1.763     www      5784: 
1.200     www      5785: # --------------------------------------------------- Course Resourcedata Query
                   5786: 
1.624     albertel 5787: sub get_courseresdata {
                   5788:     my ($coursenum,$coursedomain)=@_;
1.200     www      5789:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5790:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5791:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5792:     my %dumpreply;
1.417     albertel 5793:     unless (defined($cached)) {
1.624     albertel 5794: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5795: 	$result=\%dumpreply;
1.251     albertel 5796: 	my ($tmp) = keys(%dumpreply);
                   5797: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5798: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5799: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5800: 	    return $tmp;
1.416     albertel 5801: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5802: 	    $result=undef;
1.599     albertel 5803: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5804: 	}
                   5805:     }
1.624     albertel 5806:     return $result;
                   5807: }
                   5808: 
1.633     albertel 5809: sub devalidateuserresdata {
                   5810:     my ($uname,$udom)=@_;
                   5811:     my $hashid="$udom:$uname";
                   5812:     &devalidate_cache_new('userres',$hashid);
                   5813: }
                   5814: 
1.624     albertel 5815: sub get_userresdata {
                   5816:     my ($uname,$udom)=@_;
                   5817:     #most student don\'t have any data set, check if there is some data
                   5818:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5819: 
                   5820:     my $hashid="$udom:$uname";
                   5821:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5822:     if (!defined($cached)) {
                   5823: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5824: 	$result=\%resourcedata;
                   5825: 	&do_cache_new('userres',$hashid,$result,600);
                   5826:     }
                   5827:     my ($tmp)=keys(%$result);
                   5828:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5829: 	return $result;
                   5830:     }
                   5831:     #error 2 occurs when the .db doesn't exist
                   5832:     if ($tmp!~/error: 2 /) {
1.672     albertel 5833: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5834: 		 " Trying to get resource data for ".
                   5835: 		 $uname." at ".$udom.": ".
                   5836: 		 $tmp."</font>");
                   5837:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5838: 	#&EXT_cache_set($udom,$uname);
                   5839: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5840: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5841:     }
                   5842:     return $tmp;
                   5843: }
                   5844: 
                   5845: sub resdata {
                   5846:     my ($name,$domain,$type,@which)=@_;
                   5847:     my $result;
                   5848:     if ($type eq 'course') {
                   5849: 	$result=&get_courseresdata($name,$domain);
                   5850:     } elsif ($type eq 'user') {
                   5851: 	$result=&get_userresdata($name,$domain);
                   5852:     }
                   5853:     if (!ref($result)) { return $result; }    
1.251     albertel 5854:     foreach my $item (@which) {
1.417     albertel 5855: 	if (defined($result->{$item})) {
                   5856: 	    return $result->{$item};
1.251     albertel 5857: 	}
1.250     albertel 5858:     }
1.291     albertel 5859:     return undef;
1.200     www      5860: }
                   5861: 
1.379     matthew  5862: #
                   5863: # EXT resource caching routines
                   5864: #
                   5865: 
                   5866: sub clear_EXT_cache_status {
1.383     albertel 5867:     &delenv('cache.EXT.');
1.379     matthew  5868: }
                   5869: 
                   5870: sub EXT_cache_status {
                   5871:     my ($target_domain,$target_user) = @_;
1.383     albertel 5872:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5873:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5874:         # We know already the user has no data
                   5875:         return 1;
                   5876:     } else {
                   5877:         return 0;
                   5878:     }
                   5879: }
                   5880: 
                   5881: sub EXT_cache_set {
                   5882:     my ($target_domain,$target_user) = @_;
1.383     albertel 5883:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5884:     #&appenv($cachename => time);
1.379     matthew  5885: }
                   5886: 
1.28      www      5887: # --------------------------------------------------------- Value of a Variable
1.58      www      5888: sub EXT {
1.715     albertel 5889: 
1.395     albertel 5890:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5891:     unless ($varname) { return ''; }
1.218     albertel 5892:     #get real user name/domain, courseid and symb
                   5893:     my $courseid;
1.359     albertel 5894:     my $publicuser;
1.427     www      5895:     if ($symbparm) {
                   5896: 	$symbparm=&get_symb_from_alias($symbparm);
                   5897:     }
1.218     albertel 5898:     if (!($uname && $udom)) {
1.790     albertel 5899:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5900:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5901:     } else {
1.620     albertel 5902: 	$courseid=$env{'request.course.id'};
1.218     albertel 5903:     }
1.48      www      5904:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5905:     my $rest;
1.320     albertel 5906:     if (defined($therest[0])) {
1.48      www      5907:        $rest=join('.',@therest);
                   5908:     } else {
                   5909:        $rest='';
                   5910:     }
1.320     albertel 5911: 
1.57      www      5912:     my $qualifierrest=$qualifier;
                   5913:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5914:     my $spacequalifierrest=$space;
                   5915:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5916:     if ($realm eq 'user') {
1.48      www      5917: # --------------------------------------------------------------- user.resource
                   5918: 	if ($space eq 'resource') {
1.651     albertel 5919: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5920: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5921: 		 &&
1.744     albertel 5922: 		 ($symbparm eq &symbread()) ) {	
                   5923: 		# if we are in the middle of processing the resource the
                   5924: 		# get the value we are planning on committing
                   5925:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5926:                     return $Apache::lonhomework::results{$qualifierrest};
                   5927:                 } else {
                   5928:                     return $Apache::lonhomework::history{$qualifierrest};
                   5929:                 }
1.335     albertel 5930: 	    } else {
1.359     albertel 5931: 		my %restored;
1.620     albertel 5932: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5933: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5934: 		} else {
                   5935: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5936: 		}
1.335     albertel 5937: 		return $restored{$qualifierrest};
                   5938: 	    }
1.48      www      5939: # ----------------------------------------------------------------- user.access
                   5940:         } elsif ($space eq 'access') {
1.218     albertel 5941: 	    # FIXME - not supporting calls for a specific user
1.48      www      5942:             return &allowed($qualifier,$rest);
                   5943: # ------------------------------------------ user.preferences, user.environment
                   5944:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5945: 	    if (($uname eq $env{'user.name'}) &&
                   5946: 		($udom eq $env{'user.domain'})) {
                   5947: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5948: 	    } else {
1.359     albertel 5949: 		my %returnhash;
                   5950: 		if (!$publicuser) {
                   5951: 		    %returnhash=&userenvironment($udom,$uname,
                   5952: 						 $qualifierrest);
                   5953: 		}
1.218     albertel 5954: 		return $returnhash{$qualifierrest};
                   5955: 	    }
1.48      www      5956: # ----------------------------------------------------------------- user.course
                   5957:         } elsif ($space eq 'course') {
1.218     albertel 5958: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5959:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5960: # ------------------------------------------------------------------- user.role
                   5961:         } elsif ($space eq 'role') {
1.218     albertel 5962: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5963:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5964:             if ($qualifier eq 'value') {
                   5965: 		return $role;
                   5966:             } elsif ($qualifier eq 'extent') {
                   5967:                 return $where;
                   5968:             }
                   5969: # ----------------------------------------------------------------- user.domain
                   5970:         } elsif ($space eq 'domain') {
1.218     albertel 5971:             return $udom;
1.48      www      5972: # ------------------------------------------------------------------- user.name
                   5973:         } elsif ($space eq 'name') {
1.218     albertel 5974:             return $uname;
1.48      www      5975: # ---------------------------------------------------- Any other user namespace
1.29      www      5976:         } else {
1.359     albertel 5977: 	    my %reply;
                   5978: 	    if (!$publicuser) {
                   5979: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5980: 	    }
                   5981: 	    return $reply{$qualifierrest};
1.48      www      5982:         }
1.236     www      5983:     } elsif ($realm eq 'query') {
                   5984: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5985:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5986: 						[$spacequalifierrest]);
1.620     albertel 5987: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5988:    } elsif ($realm eq 'request') {
1.48      www      5989: # ------------------------------------------------------------- request.browser
                   5990:         if ($space eq 'browser') {
1.430     www      5991: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5992: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5993: 		    return 1;
                   5994: 		} else {
                   5995: 		    return 0;
                   5996: 		}
                   5997: 	    } else {
1.620     albertel 5998: 		return $env{'browser.'.$qualifier};
1.430     www      5999: 	    }
1.57      www      6000: # ------------------------------------------------------------ request.filename
                   6001:         } else {
1.620     albertel 6002:             return $env{'request.'.$spacequalifierrest};
1.29      www      6003:         }
1.28      www      6004:     } elsif ($realm eq 'course') {
1.48      www      6005: # ---------------------------------------------------------- course.description
1.620     albertel 6006:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6007:     } elsif ($realm eq 'resource') {
1.165     www      6008: 
1.620     albertel 6009: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6010: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6011: 	}
1.693     albertel 6012: 
                   6013: 	if ($space eq 'title') {
                   6014: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6015: 	    return &gettitle($symbparm);
                   6016: 	}
                   6017: 	
                   6018: 	if ($space eq 'map') {
                   6019: 	    my ($map) = &decode_symb($symbparm);
                   6020: 	    return &symbread($map);
                   6021: 	}
                   6022: 
                   6023: 	my ($section, $group, @groups);
1.593     albertel 6024: 	my ($courselevelm,$courselevel);
1.539     albertel 6025: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6026: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6027: 
1.218     albertel 6028: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6029: 
1.60      www      6030: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6031: 	    my $symbp=$symbparm;
1.735     albertel 6032: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6033: 
                   6034: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6035: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6036: 
1.620     albertel 6037: 	    if (($env{'user.name'} eq $uname) &&
                   6038: 		($env{'user.domain'} eq $udom)) {
                   6039: 		$section=$env{'request.course.sec'};
1.733     raeburn  6040:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6041:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6042: 	    } else {
1.539     albertel 6043: 		if (! defined($usection)) {
1.551     albertel 6044: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6045: 		} else {
                   6046: 		    $section = $usection;
                   6047: 		}
1.733     raeburn  6048:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6049: 	    }
                   6050: 
                   6051: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6052: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6053: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6054: 
1.593     albertel 6055: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6056: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6057: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6058: 
1.60      www      6059: # ----------------------------------------------------------- first, check user
1.624     albertel 6060: 
                   6061: 	    my $userreply=&resdata($uname,$udom,'user',
                   6062: 				       ($courselevelr,$courselevelm,
                   6063: 					$courselevel));
                   6064: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6065: 
1.594     albertel 6066: # ------------------------------------------------ second, check some of course
1.684     raeburn  6067:             my $coursereply;
1.691     raeburn  6068:             if (@groups > 0) {
                   6069:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6070:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6071:                 if (defined($coursereply)) { return $coursereply; }
                   6072:             }
1.96      www      6073: 
1.684     raeburn  6074: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6075: 				     $env{'course.'.$courseid.'.domain'},
                   6076: 				     'course',
                   6077: 				     ($seclevelr,$seclevelm,$seclevel,
                   6078: 				      $courselevelr));
1.287     albertel 6079: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6080: 
1.60      www      6081: # ------------------------------------------------------ third, check map parms
1.218     albertel 6082: 	    my %parmhash=();
                   6083: 	    my $thisparm='';
                   6084: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6085: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6086: 		    &GDBM_READER(),0640)) {
1.218     albertel 6087: 		$thisparm=$parmhash{$symbparm};
                   6088: 		untie(%parmhash);
                   6089: 	    }
                   6090: 	    if ($thisparm) { return $thisparm; }
                   6091: 	}
1.594     albertel 6092: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6093: 
1.218     albertel 6094: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6095: 	my $filename;
                   6096: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6097: 	if ($symbparm) {
1.409     www      6098: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6099: 	} else {
1.620     albertel 6100: 	    $filename=$env{'request.filename'};
1.282     albertel 6101: 	}
                   6102: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6103: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6104: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6105: 	if (defined($metadata)) { return $metadata; }
1.142     www      6106: 
1.594     albertel 6107: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6108: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6109: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6110: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6111: 				     $env{'course.'.$courseid.'.domain'},
                   6112: 				     'course',
                   6113: 				     ($courselevelm,$courselevel));
1.593     albertel 6114: 	    if (defined($coursereply)) { return $coursereply; }
                   6115: 	}
1.145     www      6116: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6117: 	unless ($space eq '0') {
1.336     albertel 6118: 	    my @parts=split(/_/,$space);
                   6119: 	    my $id=pop(@parts);
                   6120: 	    my $part=join('_',@parts);
                   6121: 	    if ($part eq '') { $part='0'; }
                   6122: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6123: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6124: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6125: 	}
1.395     albertel 6126: 	if ($recurse) { return undef; }
                   6127: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6128: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6129: 
1.48      www      6130: # ---------------------------------------------------- Any other user namespace
                   6131:     } elsif ($realm eq 'environment') {
                   6132: # ----------------------------------------------------------------- environment
1.620     albertel 6133: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6134: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6135: 	} else {
1.770     albertel 6136: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6137: 		return '';
                   6138: 	    }
1.219     albertel 6139: 	    my %returnhash=&userenvironment($udom,$uname,
                   6140: 					    $spacequalifierrest);
                   6141: 	    return $returnhash{$spacequalifierrest};
                   6142: 	}
1.28      www      6143:     } elsif ($realm eq 'system') {
1.48      www      6144: # ----------------------------------------------------------------- system.time
                   6145: 	if ($space eq 'time') {
                   6146: 	    return time;
                   6147:         }
1.696     albertel 6148:     } elsif ($realm eq 'server') {
                   6149: # ----------------------------------------------------------------- system.time
                   6150: 	if ($space eq 'name') {
                   6151: 	    return $ENV{'SERVER_NAME'};
                   6152:         }
1.28      www      6153:     }
1.48      www      6154:     return '';
1.61      www      6155: }
                   6156: 
1.691     raeburn  6157: sub check_group_parms {
                   6158:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6159:     my @groupitems = ();
                   6160:     my $resultitem;
                   6161:     my @levels = ($symbparm,$mapparm,$what);
                   6162:     foreach my $group (@{$groups}) {
                   6163:         foreach my $level (@levels) {
                   6164:              my $item = $courseid.'.['.$group.'].'.$level;
                   6165:              push(@groupitems,$item);
                   6166:         }
                   6167:     }
                   6168:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6169:                             $env{'course.'.$courseid.'.domain'},
                   6170:                                      'course',@groupitems);
                   6171:     return $coursereply;
                   6172: }
                   6173: 
                   6174: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6175:     my ($courseid,@groups) = @_;
                   6176:     @groups = sort(@groups);
1.691     raeburn  6177:     return @groups;
                   6178: }
                   6179: 
1.395     albertel 6180: sub packages_tab_default {
                   6181:     my ($uri,$varname)=@_;
                   6182:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6183: 
                   6184:     my (@extension,@specifics,$do_default);
                   6185:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6186: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6187: 	if ($pack_type eq 'default') {
                   6188: 	    $do_default=1;
                   6189: 	} elsif ($pack_type eq 'extension') {
                   6190: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6191: 	} else {
                   6192: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6193: 	}
                   6194:     }
                   6195:     # first look for a package that matches the requested part id
                   6196:     foreach my $package (@specifics) {
                   6197: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6198: 	next if ($pack_part ne $part);
                   6199: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6200: 	    return $packagetab{"$pack_type&$name&default"};
                   6201: 	}
                   6202:     }
                   6203:     # look for any possible matching non extension_ package
                   6204:     foreach my $package (@specifics) {
                   6205: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6206: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6207: 	    return $packagetab{"$pack_type&$name&default"};
                   6208: 	}
1.585     albertel 6209: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6210: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6211: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6212: 	}
                   6213:     }
1.738     albertel 6214:     # look for any posible extension_ match
                   6215:     foreach my $package (@extension) {
                   6216: 	my ($package,$pack_type)=@{$package};
                   6217: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6218: 	    return $packagetab{"$pack_type&$name&default"};
                   6219: 	}
                   6220: 	if (defined($packagetab{$package."&$name&default"})) {
                   6221: 	    return $packagetab{$package."&$name&default"};
                   6222: 	}
                   6223:     }
                   6224:     # look for a global default setting
                   6225:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6226: 	return $packagetab{"default&$name&default"};
                   6227:     }
1.395     albertel 6228:     return undef;
                   6229: }
                   6230: 
1.334     albertel 6231: sub add_prefix_and_part {
                   6232:     my ($prefix,$part)=@_;
                   6233:     my $keyroot;
                   6234:     if (defined($prefix) && $prefix !~ /^__/) {
                   6235: 	# prefix that has a part already
                   6236: 	$keyroot=$prefix;
                   6237:     } elsif (defined($prefix)) {
                   6238: 	# prefix that is missing a part
                   6239: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6240:     } else {
                   6241: 	# no prefix at all
                   6242: 	if (defined($part)) { $keyroot='_'.$part; }
                   6243:     }
                   6244:     return $keyroot;
                   6245: }
                   6246: 
1.71      www      6247: # ---------------------------------------------------------------- Get metadata
                   6248: 
1.599     albertel 6249: my %metaentry;
1.71      www      6250: sub metadata {
1.176     www      6251:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6252:     $uri=&declutter($uri);
1.288     albertel 6253:     # if it is a non metadata possible uri return quickly
1.529     albertel 6254:     if (($uri eq '') || 
                   6255: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6256: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6257:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6258: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6259: 	return undef;
1.288     albertel 6260:     }
1.73      www      6261:     my $filename=$uri;
                   6262:     $uri=~s/\.meta$//;
1.172     www      6263: #
                   6264: # Is the metadata already cached?
1.177     www      6265: # Look at timestamp of caching
1.172     www      6266: # Everything is cached by the main uri, libraries are never directly cached
                   6267: #
1.428     albertel 6268:     if (!defined($liburi)) {
1.599     albertel 6269: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6270: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6271:     }
                   6272:     {
1.172     www      6273: #
                   6274: # Is this a recursive call for a library?
                   6275: #
1.599     albertel 6276: #	if (! exists($metacache{$uri})) {
                   6277: #	    $metacache{$uri}={};
                   6278: #	}
1.171     www      6279:         if ($liburi) {
                   6280: 	    $liburi=&declutter($liburi);
                   6281:             $filename=$liburi;
1.401     bowersj2 6282:         } else {
1.599     albertel 6283: 	    &devalidate_cache_new('meta',$uri);
                   6284: 	    undef(%metaentry);
1.401     bowersj2 6285: 	}
1.140     www      6286:         my %metathesekeys=();
1.73      www      6287:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6288: 	my $metastring;
1.768     albertel 6289: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6290: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6291: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6292: 	    $metastring=&getfile($file);
1.489     albertel 6293: 	}
1.208     albertel 6294:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6295:         my $token;
1.140     www      6296:         undef %metathesekeys;
1.71      www      6297:         while ($token=$parser->get_token) {
1.339     albertel 6298: 	    if ($token->[0] eq 'S') {
                   6299: 		if (defined($token->[2]->{'package'})) {
1.172     www      6300: #
                   6301: # This is a package - get package info
                   6302: #
1.339     albertel 6303: 		    my $package=$token->[2]->{'package'};
                   6304: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6305: 		    if (defined($token->[2]->{'id'})) { 
                   6306: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6307: 		    }
1.599     albertel 6308: 		    if ($metaentry{':packages'}) {
                   6309: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6310: 		    } else {
1.599     albertel 6311: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6312: 		    }
1.736     albertel 6313: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6314: 			my $part=$keyroot;
                   6315: 			$part=~s/^\_//;
1.736     albertel 6316: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6317: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6318: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6319: 			    # ignore package.tab specified default values
                   6320:                             # here &package_tab_default() will fetch those
                   6321: 			    if ($subp eq 'default') { next; }
1.736     albertel 6322: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6323: 			    my $unikey;
                   6324: 			    if ($pack =~ /_0$/) {
                   6325: 				$unikey='parameter_0_'.$name;
                   6326: 				$part=0;
                   6327: 			    } else {
                   6328: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6329: 			    }
1.339     albertel 6330: 			    if ($subp eq 'display') {
                   6331: 				$value.=' [Part: '.$part.']';
                   6332: 			    }
1.599     albertel 6333: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6334: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6335: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6336: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6337: 			    }
1.599     albertel 6338: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6339: 				$metaentry{':'.$unikey}=
                   6340: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6341: 			    }
1.339     albertel 6342: 			}
                   6343: 		    }
                   6344: 		} else {
1.172     www      6345: #
                   6346: # This is not a package - some other kind of start tag
1.339     albertel 6347: #
                   6348: 		    my $entry=$token->[1];
                   6349: 		    my $unikey;
                   6350: 		    if ($entry eq 'import') {
                   6351: 			$unikey='';
                   6352: 		    } else {
                   6353: 			$unikey=$entry;
                   6354: 		    }
                   6355: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6356: 
                   6357: 		    if (defined($token->[2]->{'id'})) { 
                   6358: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6359: 		    }
1.175     www      6360: 
1.339     albertel 6361: 		    if ($entry eq 'import') {
1.175     www      6362: #
                   6363: # Importing a library here
1.339     albertel 6364: #
                   6365: 			if ($depthcount<20) {
                   6366: 			    my $location=$parser->get_text('/import');
                   6367: 			    my $dir=$filename;
                   6368: 			    $dir=~s|[^/]*$||;
                   6369: 			    $location=&filelocation($dir,$location);
1.736     albertel 6370: 			    my $metadata = 
                   6371: 				&metadata($uri,'keys', $location,$unikey,
                   6372: 					  $depthcount+1);
                   6373: 			    foreach my $meta (split(',',$metadata)) {
                   6374: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6375: 				$metathesekeys{$meta}=1;
1.339     albertel 6376: 			    }
                   6377: 			}
                   6378: 		    } else { 
                   6379: 			
                   6380: 			if (defined($token->[2]->{'name'})) { 
                   6381: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6382: 			}
                   6383: 			$metathesekeys{$unikey}=1;
1.736     albertel 6384: 			foreach my $param (@{$token->[3]}) {
                   6385: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6386: 				$token->[2]->{$param};
1.339     albertel 6387: 			}
                   6388: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6389: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6390: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6391: 		 # only ws inside the tag, and not in default, so use default
                   6392: 		 # as value
1.599     albertel 6393: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6394: 			} else {
1.321     albertel 6395: 		  # either something interesting inside the tag or default
                   6396:                   # uninteresting
1.599     albertel 6397: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6398: 			}
1.172     www      6399: # end of not-a-package not-a-library import
1.339     albertel 6400: 		    }
1.172     www      6401: # end of not-a-package start tag
1.339     albertel 6402: 		}
1.172     www      6403: # the next is the end of "start tag"
1.339     albertel 6404: 	    }
                   6405: 	}
1.483     albertel 6406: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6407: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6408: 	    #no specific packages #how's our extension
                   6409: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6410: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6411: 					 \%metathesekeys);
                   6412: 	}
1.599     albertel 6413: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6414: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6415: 		#no specific packages well let's get default then
                   6416: 		if ($key!~/^default&/) { next; }
1.488     albertel 6417: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6418: 					     \%metathesekeys);
                   6419: 	    }
                   6420: 	}
1.338     www      6421: # are there custom rights to evaluate
1.599     albertel 6422: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6423: 
1.338     www      6424:     #
                   6425:     # Importing a rights file here
1.339     albertel 6426:     #
                   6427: 	    unless ($depthcount) {
1.599     albertel 6428: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6429: 		my $dir=$filename;
                   6430: 		$dir=~s|[^/]*$||;
                   6431: 		$location=&filelocation($dir,$location);
1.736     albertel 6432: 		my $rights_metadata =
                   6433: 		    &metadata($uri,'keys',$location,'_rights',
                   6434: 			      $depthcount+1);
                   6435: 		foreach my $rights (split(',',$rights_metadata)) {
                   6436: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6437: 		    $metathesekeys{$rights}=1;
1.339     albertel 6438: 		}
                   6439: 	    }
                   6440: 	}
1.737     albertel 6441: 	# uniqifiy package listing
                   6442: 	my %seen;
                   6443: 	my @uniq_packages =
                   6444: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6445: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6446: 
                   6447: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6448: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6449: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6450: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6451: # this is the end of "was not already recently cached
1.71      www      6452:     }
1.599     albertel 6453:     return $metaentry{':'.$what};
1.261     albertel 6454: }
                   6455: 
1.488     albertel 6456: sub metadata_create_package_def {
1.483     albertel 6457:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6458:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6459:     if ($subp eq 'default') { next; }
                   6460:     
1.599     albertel 6461:     if (defined($metaentry{':packages'})) {
                   6462: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6463:     } else {
1.599     albertel 6464: 	$metaentry{':packages'}=$package;
1.483     albertel 6465:     }
                   6466:     my $value=$packagetab{$key};
                   6467:     my $unikey;
                   6468:     $unikey='parameter_0_'.$name;
1.599     albertel 6469:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6470:     $$metathesekeys{$unikey}=1;
1.599     albertel 6471:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6472: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6473:     }
1.599     albertel 6474:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6475: 	$metaentry{':'.$unikey}=
                   6476: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6477:     }
                   6478: }
                   6479: 
1.261     albertel 6480: sub metadata_generate_part0 {
                   6481:     my ($metadata,$metacache,$uri) = @_;
                   6482:     my %allnames;
1.737     albertel 6483:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6484: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6485: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6486: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6487: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6488: 	    $allnames{$name}=$part;
                   6489: 	  }
                   6490: 	}
                   6491:     }
                   6492:     foreach my $name (keys(%allnames)) {
                   6493:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6494:       my $key=":parameter_0_$name";
1.261     albertel 6495:       $$metacache{"$key.part"}='0';
                   6496:       $$metacache{"$key.name"}=$name;
1.428     albertel 6497:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6498: 					   $allnames{$name}.'_'.$name.
                   6499: 					   '.type'};
1.428     albertel 6500:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6501: 			     '.display'};
1.644     www      6502:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6503:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6504:       $$metacache{"$key.display"}=$olddis;
                   6505:     }
1.71      www      6506: }
                   6507: 
1.764     albertel 6508: # ------------------------------------------------------ Devalidate title cache
                   6509: 
                   6510: sub devalidate_title_cache {
                   6511:     my ($url)=@_;
                   6512:     if (!$env{'request.course.id'}) { return; }
                   6513:     my $symb=&symbread($url);
                   6514:     if (!$symb) { return; }
                   6515:     my $key=$env{'request.course.id'}."\0".$symb;
                   6516:     &devalidate_cache_new('title',$key);
                   6517: }
                   6518: 
1.301     www      6519: # ------------------------------------------------- Get the title of a resource
                   6520: 
                   6521: sub gettitle {
                   6522:     my $urlsymb=shift;
                   6523:     my $symb=&symbread($urlsymb);
1.534     albertel 6524:     if ($symb) {
1.620     albertel 6525: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6526: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6527: 	if (defined($cached)) { 
                   6528: 	    return $result;
                   6529: 	}
1.534     albertel 6530: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6531: 	my $title='';
                   6532: 	my %bighash;
1.620     albertel 6533: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6534: 		&GDBM_READER(),0640)) {
                   6535: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6536: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6537: 	    untie %bighash;
                   6538: 	}
                   6539: 	$title=~s/\&colon\;/\:/gs;
                   6540: 	if ($title) {
1.599     albertel 6541: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6542: 	}
                   6543: 	$urlsymb=$url;
                   6544:     }
                   6545:     my $title=&metadata($urlsymb,'title');
                   6546:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6547:     return $title;
1.301     www      6548: }
1.613     albertel 6549: 
1.614     albertel 6550: sub get_slot {
                   6551:     my ($which,$cnum,$cdom)=@_;
                   6552:     if (!$cnum || !$cdom) {
1.790     albertel 6553: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6554: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6555: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6556:     }
1.703     albertel 6557:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6558:     my %slotinfo;
                   6559:     if (exists($remembered{$key})) {
                   6560: 	$slotinfo{$which} = $remembered{$key};
                   6561:     } else {
                   6562: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6563: 	&Apache::lonhomework::showhash(%slotinfo);
                   6564: 	my ($tmp)=keys(%slotinfo);
                   6565: 	if ($tmp=~/^error:/) { return (); }
                   6566: 	$remembered{$key} = $slotinfo{$which};
                   6567:     }
1.616     albertel 6568:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6569: 	return %{$slotinfo{$which}};
                   6570:     }
                   6571:     return $slotinfo{$which};
1.614     albertel 6572: }
1.31      www      6573: # ------------------------------------------------- Update symbolic store links
                   6574: 
                   6575: sub symblist {
                   6576:     my ($mapname,%newhash)=@_;
1.438     www      6577:     $mapname=&deversion(&declutter($mapname));
1.31      www      6578:     my %hash;
1.620     albertel 6579:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6580:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6581:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6582: 	    foreach my $url (keys %newhash) {
                   6583: 		next if ($url eq 'last_known'
                   6584: 			 && $env{'form.no_update_last_known'});
                   6585: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6586: 						    $newhash{$url}->[1],
                   6587: 						    $newhash{$url}->[0]);
1.191     harris41 6588:             }
1.31      www      6589:             if (untie(%hash)) {
                   6590: 		return 'ok';
                   6591:             }
                   6592:         }
                   6593:     }
                   6594:     return 'error';
1.212     www      6595: }
                   6596: 
                   6597: # --------------------------------------------------------------- Verify a symb
                   6598: 
                   6599: sub symbverify {
1.510     www      6600:     my ($symb,$thisurl)=@_;
                   6601:     my $thisfn=$thisurl;
1.439     www      6602:     $thisfn=&declutter($thisfn);
1.215     www      6603: # direct jump to resource in page or to a sequence - will construct own symbs
                   6604:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6605: # check URL part
1.409     www      6606:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6607: 
1.431     www      6608:     unless ($url eq $thisfn) { return 0; }
1.213     www      6609: 
1.216     www      6610:     $symb=&symbclean($symb);
1.510     www      6611:     $thisurl=&deversion($thisurl);
1.439     www      6612:     $thisfn=&deversion($thisfn);
1.213     www      6613: 
                   6614:     my %bighash;
                   6615:     my $okay=0;
1.431     www      6616: 
1.620     albertel 6617:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6618:                             &GDBM_READER(),0640)) {
1.510     www      6619:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6620:         unless ($ids) { 
1.510     www      6621:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6622:         }
                   6623:         if ($ids) {
                   6624: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6625: 	    foreach my $id (split(/\,/,$ids)) {
                   6626: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6627:                if (
                   6628:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6629:    eq $symb) { 
1.620     albertel 6630: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6631: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6632: 		       $okay=1; 
                   6633: 		   }
                   6634: 	       }
1.216     www      6635: 	   }
                   6636:         }
1.213     www      6637: 	untie(%bighash);
                   6638:     }
                   6639:     return $okay;
1.31      www      6640: }
                   6641: 
1.210     www      6642: # --------------------------------------------------------------- Clean-up symb
                   6643: 
                   6644: sub symbclean {
                   6645:     my $symb=shift;
1.568     albertel 6646:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6647: # remove version from map
                   6648:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6649: 
1.210     www      6650: # remove version from URL
                   6651:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6652: 
1.507     www      6653: # remove wrapper
                   6654: 
1.510     www      6655:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6656:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6657:     return $symb;
1.409     www      6658: }
                   6659: 
                   6660: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6661: 
                   6662: sub encode_symb {
                   6663:     my ($map,$resid,$url)=@_;
                   6664:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6665: }
1.409     www      6666: 
                   6667: sub decode_symb {
1.568     albertel 6668:     my $symb=shift;
                   6669:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6670:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6671:     return (&fixversion($map),$resid,&fixversion($url));
                   6672: }
                   6673: 
                   6674: sub fixversion {
                   6675:     my $fn=shift;
1.609     banghart 6676:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6677:     my %bighash;
                   6678:     my $uri=&clutter($fn);
1.620     albertel 6679:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6680: # is this cached?
1.599     albertel 6681:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6682:     if (defined($cached)) { return $result; }
                   6683: # unfortunately not cached, or expired
1.620     albertel 6684:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6685: 	    &GDBM_READER(),0640)) {
                   6686:  	if ($bighash{'version_'.$uri}) {
                   6687:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6688:  	    unless (($version eq 'mostrecent') || 
                   6689: 		    ($version==&getversion($uri))) {
1.440     www      6690:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6691:  	    }
                   6692:  	}
                   6693:  	untie %bighash;
1.413     www      6694:     }
1.599     albertel 6695:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6696: }
                   6697: 
                   6698: sub deversion {
                   6699:     my $url=shift;
                   6700:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6701:     return $url;
1.210     www      6702: }
                   6703: 
1.31      www      6704: # ------------------------------------------------------ Return symb list entry
                   6705: 
                   6706: sub symbread {
1.249     www      6707:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6708:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6709:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6710: # no filename provided? try from environment
1.44      www      6711:     unless ($thisfn) {
1.620     albertel 6712:         if ($env{'request.symb'}) {
                   6713: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6714: 	}
1.620     albertel 6715: 	$thisfn=$env{'request.filename'};
1.44      www      6716:     }
1.569     albertel 6717:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6718: # is that filename actually a symb? Verify, clean, and return
                   6719:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6720: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6721: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6722: 	}
1.242     www      6723:     }
1.44      www      6724:     $thisfn=declutter($thisfn);
1.31      www      6725:     my %hash;
1.37      www      6726:     my %bighash;
                   6727:     my $syval='';
1.620     albertel 6728:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6729:         my $targetfn = $thisfn;
1.609     banghart 6730:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6731:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6732:         }
1.687     albertel 6733: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6734: 	    $targetfn=$1;
                   6735: 	}
1.620     albertel 6736:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6737:                       &GDBM_READER(),0640)) {
1.481     raeburn  6738: 	    $syval=$hash{$targetfn};
1.37      www      6739:             untie(%hash);
                   6740:         }
                   6741: # ---------------------------------------------------------- There was an entry
                   6742:         if ($syval) {
1.601     albertel 6743: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6744: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6745: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6746: 		    #return $env{$cache_str}='';
1.601     albertel 6747: 		#}    
                   6748: 		#$syval.=$1;
                   6749: 	    #}
1.37      www      6750:         } else {
                   6751: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6752:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6753:                             &GDBM_READER(),0640)) {
1.37      www      6754: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6755:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6756:               unless ($ids) { 
                   6757:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6758:               }
                   6759:               unless ($ids) {
                   6760: # alias?
                   6761: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6762:               }
1.37      www      6763:               if ($ids) {
                   6764: # ------------------------------------------------------------------- Has ID(s)
                   6765:                  my @possibilities=split(/\,/,$ids);
1.39      www      6766:                  if ($#possibilities==0) {
                   6767: # ----------------------------------------------- There is only one possibility
1.37      www      6768: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6769: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6770: 						    $resid,$thisfn);
1.249     www      6771:                  } elsif (!$donotrecurse) {
1.39      www      6772: # ------------------------------------------ There is more than one possibility
                   6773:                      my $realpossible=0;
1.800     albertel 6774:                      foreach my $id (@possibilities) {
                   6775: 			 my $file=$bighash{'src_'.$id};
1.39      www      6776:                          if (&allowed('bre',$file)) {
1.800     albertel 6777:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6778:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6779: 				$realpossible++;
1.626     albertel 6780:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6781: 						    $resid,$thisfn);
1.39      www      6782:                             }
                   6783: 			 }
1.191     harris41 6784:                      }
1.39      www      6785: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6786:                  } else {
                   6787:                      $syval='';
1.37      www      6788:                  }
                   6789: 	      }
                   6790:               untie(%bighash)
1.481     raeburn  6791:            }
1.31      www      6792:         }
1.62      www      6793:         if ($syval) {
1.620     albertel 6794: 	    return $env{$cache_str}=$syval;
1.62      www      6795:         }
1.31      www      6796:     }
1.44      www      6797:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6798:     return $env{$cache_str}='';
1.31      www      6799: }
                   6800: 
                   6801: # ---------------------------------------------------------- Return random seed
                   6802: 
1.32      www      6803: sub numval {
                   6804:     my $txt=shift;
                   6805:     $txt=~tr/A-J/0-9/;
                   6806:     $txt=~tr/a-j/0-9/;
                   6807:     $txt=~tr/K-T/0-9/;
                   6808:     $txt=~tr/k-t/0-9/;
                   6809:     $txt=~tr/U-Z/0-5/;
                   6810:     $txt=~tr/u-z/0-5/;
                   6811:     $txt=~s/\D//g;
1.564     albertel 6812:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6813:     return int($txt);
1.368     albertel 6814: }
                   6815: 
1.484     albertel 6816: sub numval2 {
                   6817:     my $txt=shift;
                   6818:     $txt=~tr/A-J/0-9/;
                   6819:     $txt=~tr/a-j/0-9/;
                   6820:     $txt=~tr/K-T/0-9/;
                   6821:     $txt=~tr/k-t/0-9/;
                   6822:     $txt=~tr/U-Z/0-5/;
                   6823:     $txt=~tr/u-z/0-5/;
                   6824:     $txt=~s/\D//g;
                   6825:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6826:     my $total;
                   6827:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6828:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6829:     return int($total);
                   6830: }
                   6831: 
1.575     albertel 6832: sub numval3 {
                   6833:     use integer;
                   6834:     my $txt=shift;
                   6835:     $txt=~tr/A-J/0-9/;
                   6836:     $txt=~tr/a-j/0-9/;
                   6837:     $txt=~tr/K-T/0-9/;
                   6838:     $txt=~tr/k-t/0-9/;
                   6839:     $txt=~tr/U-Z/0-5/;
                   6840:     $txt=~tr/u-z/0-5/;
                   6841:     $txt=~s/\D//g;
                   6842:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6843:     my $total;
                   6844:     foreach my $val (@txts) { $total+=$val; }
                   6845:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6846:     return $total;
                   6847: }
                   6848: 
1.675     albertel 6849: sub digest {
                   6850:     my ($data)=@_;
                   6851:     my $digest=&Digest::MD5::md5($data);
                   6852:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6853:     my ($e,$f);
                   6854:     {
                   6855:         use integer;
                   6856:         $e=($a+$b);
                   6857:         $f=($c+$d);
                   6858:         if ($_64bit) {
                   6859:             $e=(($e<<32)>>32);
                   6860:             $f=(($f<<32)>>32);
                   6861:         }
                   6862:     }
                   6863:     if (wantarray) {
                   6864: 	return ($e,$f);
                   6865:     } else {
                   6866: 	my $g;
                   6867: 	{
                   6868: 	    use integer;
                   6869: 	    $g=($e+$f);
                   6870: 	    if ($_64bit) {
                   6871: 		$g=(($g<<32)>>32);
                   6872: 	    }
                   6873: 	}
                   6874: 	return $g;
                   6875:     }
                   6876: }
                   6877: 
1.368     albertel 6878: sub latest_rnd_algorithm_id {
1.675     albertel 6879:     return '64bit5';
1.366     albertel 6880: }
1.32      www      6881: 
1.503     albertel 6882: sub get_rand_alg {
                   6883:     my ($courseid)=@_;
1.790     albertel 6884:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6885:     if ($courseid) {
1.620     albertel 6886: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6887:     }
                   6888:     return &latest_rnd_algorithm_id();
                   6889: }
                   6890: 
1.562     albertel 6891: sub validCODE {
                   6892:     my ($CODE)=@_;
                   6893:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6894:     return 0;
                   6895: }
                   6896: 
1.491     albertel 6897: sub getCODE {
1.620     albertel 6898:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6899:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6900: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6901: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6902: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6903:     }
                   6904:     return undef;
                   6905: }
                   6906: 
1.31      www      6907: sub rndseed {
1.155     albertel 6908:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6909: 
1.790     albertel 6910:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6911:     if (!$symb) {
1.366     albertel 6912: 	unless ($symb=$wsymb) { return time; }
                   6913:     }
                   6914:     if (!$courseid) { $courseid=$wcourseid; }
                   6915:     if (!$domain) { $domain=$wdomain; }
                   6916:     if (!$username) { $username=$wusername }
1.503     albertel 6917:     my $which=&get_rand_alg();
1.803     albertel 6918: 
1.491     albertel 6919:     if (defined(&getCODE())) {
1.675     albertel 6920: 	if ($which eq '64bit5') {
                   6921: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6922: 	} elsif ($which eq '64bit4') {
1.575     albertel 6923: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6924: 	} else {
                   6925: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6926: 	}
1.675     albertel 6927:     } elsif ($which eq '64bit5') {
                   6928: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6929:     } elsif ($which eq '64bit4') {
                   6930: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6931:     } elsif ($which eq '64bit3') {
                   6932: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6933:     } elsif ($which eq '64bit2') {
                   6934: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6935:     } elsif ($which eq '64bit') {
                   6936: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6937:     }
                   6938:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6939: }
                   6940: 
                   6941: sub rndseed_32bit {
                   6942:     my ($symb,$courseid,$domain,$username)=@_;
                   6943:     {
                   6944: 	use integer;
                   6945: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6946: 	my $symbseed=numval($symb) << 22;
                   6947: 	my $namechck=unpack("%32C*",$username) << 17;
                   6948: 	my $nameseed=numval($username) << 12;
                   6949: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6950: 	my $courseseed=unpack("%32C*",$courseid);
                   6951: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6952: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6953: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6954: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6955: 	return $num;
                   6956:     }
                   6957: }
                   6958: 
                   6959: sub rndseed_64bit {
                   6960:     my ($symb,$courseid,$domain,$username)=@_;
                   6961:     {
                   6962: 	use integer;
                   6963: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6964: 	my $symbseed=numval($symb) << 10;
                   6965: 	my $namechck=unpack("%32S*",$username);
                   6966: 	
                   6967: 	my $nameseed=numval($username) << 21;
                   6968: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6969: 	my $courseseed=unpack("%32S*",$courseid);
                   6970: 	
                   6971: 	my $num1=$symbchck+$symbseed+$namechck;
                   6972: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6973: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6974: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6975: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6976: 	return "$num1,$num2";
1.155     albertel 6977:     }
1.366     albertel 6978: }
                   6979: 
1.443     albertel 6980: sub rndseed_64bit2 {
                   6981:     my ($symb,$courseid,$domain,$username)=@_;
                   6982:     {
                   6983: 	use integer;
                   6984: 	# strings need to be an even # of cahracters long, it it is odd the
                   6985:         # last characters gets thrown away
                   6986: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6987: 	my $symbseed=numval($symb) << 10;
                   6988: 	my $namechck=unpack("%32S*",$username.' ');
                   6989: 	
                   6990: 	my $nameseed=numval($username) << 21;
1.501     albertel 6991: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6992: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6993: 	
                   6994: 	my $num1=$symbchck+$symbseed+$namechck;
                   6995: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6996: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6997: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6998: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6999: 	return "$num1,$num2";
                   7000:     }
                   7001: }
                   7002: 
                   7003: sub rndseed_64bit3 {
                   7004:     my ($symb,$courseid,$domain,$username)=@_;
                   7005:     {
                   7006: 	use integer;
                   7007: 	# strings need to be an even # of cahracters long, it it is odd the
                   7008:         # last characters gets thrown away
                   7009: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7010: 	my $symbseed=numval2($symb) << 10;
                   7011: 	my $namechck=unpack("%32S*",$username.' ');
                   7012: 	
                   7013: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7014: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7015: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7016: 	
                   7017: 	my $num1=$symbchck+$symbseed+$namechck;
                   7018: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7019: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7020: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7021: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7022: 	
1.503     albertel 7023: 	return "$num1:$num2";
1.443     albertel 7024:     }
                   7025: }
                   7026: 
1.575     albertel 7027: sub rndseed_64bit4 {
                   7028:     my ($symb,$courseid,$domain,$username)=@_;
                   7029:     {
                   7030: 	use integer;
                   7031: 	# strings need to be an even # of cahracters long, it it is odd the
                   7032:         # last characters gets thrown away
                   7033: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7034: 	my $symbseed=numval3($symb) << 10;
                   7035: 	my $namechck=unpack("%32S*",$username.' ');
                   7036: 	
                   7037: 	my $nameseed=numval3($username) << 21;
                   7038: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7039: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7040: 	
                   7041: 	my $num1=$symbchck+$symbseed+$namechck;
                   7042: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7043: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7044: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7046: 	
                   7047: 	return "$num1:$num2";
                   7048:     }
                   7049: }
                   7050: 
1.675     albertel 7051: sub rndseed_64bit5 {
                   7052:     my ($symb,$courseid,$domain,$username)=@_;
                   7053:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7054:     return "$num1:$num2";
                   7055: }
                   7056: 
1.366     albertel 7057: sub rndseed_CODE_64bit {
                   7058:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7059:     {
1.366     albertel 7060: 	use integer;
1.443     albertel 7061: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7062: 	my $symbseed=numval2($symb);
1.491     albertel 7063: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7064: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7065: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7066: 	my $num1=$symbseed+$CODEchck;
                   7067: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7068: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7069: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7070: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7071: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7072: 	return "$num1:$num2";
1.366     albertel 7073:     }
                   7074: }
                   7075: 
1.575     albertel 7076: sub rndseed_CODE_64bit4 {
                   7077:     my ($symb,$courseid,$domain,$username)=@_;
                   7078:     {
                   7079: 	use integer;
                   7080: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7081: 	my $symbseed=numval3($symb);
                   7082: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7083: 	my $CODEseed=numval3(&getCODE());
                   7084: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7085: 	my $num1=$symbseed+$CODEchck;
                   7086: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7087: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7088: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7089: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7090: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7091: 	return "$num1:$num2";
                   7092:     }
                   7093: }
                   7094: 
1.675     albertel 7095: sub rndseed_CODE_64bit5 {
                   7096:     my ($symb,$courseid,$domain,$username)=@_;
                   7097:     my $code = &getCODE();
                   7098:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7099:     return "$num1:$num2";
                   7100: }
                   7101: 
1.366     albertel 7102: sub setup_random_from_rndseed {
                   7103:     my ($rndseed)=@_;
1.503     albertel 7104:     if ($rndseed =~/([,:])/) {
                   7105: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7106: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7107:     } else {
                   7108: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7109:     }
1.36      albertel 7110: }
                   7111: 
1.474     albertel 7112: sub latest_receipt_algorithm_id {
1.835     albertel 7113:     return 'receipt3';
1.474     albertel 7114: }
                   7115: 
1.480     www      7116: sub recunique {
                   7117:     my $fucourseid=shift;
                   7118:     my $unique;
1.835     albertel 7119:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7120: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7121: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7122:     } else {
                   7123: 	$unique=$perlvar{'lonReceipt'};
                   7124:     }
                   7125:     return unpack("%32C*",$unique);
                   7126: }
                   7127: 
                   7128: sub recprefix {
                   7129:     my $fucourseid=shift;
                   7130:     my $prefix;
1.835     albertel 7131:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7132: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7133: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7134:     } else {
                   7135: 	$prefix=$perlvar{'lonHostID'};
                   7136:     }
                   7137:     return unpack("%32C*",$prefix);
                   7138: }
                   7139: 
1.76      www      7140: sub ireceipt {
1.474     albertel 7141:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7142: 
                   7143:     my $return =&recprefix($fucourseid).'-';
                   7144: 
                   7145:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7146: 	$env{'request.state'} eq 'construct') {
                   7147: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7148: 	return $return;
                   7149:     }
                   7150: 
1.76      www      7151:     my $cuname=unpack("%32C*",$funame);
                   7152:     my $cudom=unpack("%32C*",$fudom);
                   7153:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7154:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7155:     my $cunique=&recunique($fucourseid);
1.474     albertel 7156:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7157:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7158: 
1.790     albertel 7159: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7160: 			       
                   7161: 	$return.= ($cunique%$cuname+
                   7162: 		   $cunique%$cudom+
                   7163: 		   $cusymb%$cuname+
                   7164: 		   $cusymb%$cudom+
                   7165: 		   $cucourseid%$cuname+
                   7166: 		   $cucourseid%$cudom+
                   7167: 		   $cpart%$cuname+
                   7168: 		   $cpart%$cudom);
                   7169:     } else {
                   7170: 	$return.= ($cunique%$cuname+
                   7171: 		   $cunique%$cudom+
                   7172: 		   $cusymb%$cuname+
                   7173: 		   $cusymb%$cudom+
                   7174: 		   $cucourseid%$cuname+
                   7175: 		   $cucourseid%$cudom);
                   7176:     }
                   7177:     return $return;
1.76      www      7178: }
                   7179: 
                   7180: sub receipt {
1.474     albertel 7181:     my ($part)=@_;
1.790     albertel 7182:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7183:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7184: }
1.260     ng       7185: 
1.790     albertel 7186: sub whichuser {
                   7187:     my ($passedsymb)=@_;
                   7188:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7189:     if (defined($env{'form.grade_symb'})) {
                   7190: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7191: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7192: 	if (!$allowed &&
                   7193: 	    exists($env{'request.course.sec'}) &&
                   7194: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7195: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7196: 			      '/'.$env{'request.course.sec'});
                   7197: 	}
                   7198: 	if ($allowed) {
                   7199: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7200: 	    $courseid=$tmp_courseid;
                   7201: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7202: 	    ($name)=&get_env_multiple('form.grade_username');
                   7203: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7204: 	}
                   7205:     }
                   7206:     if (!$passedsymb) {
                   7207: 	$symb=&symbread();
                   7208:     } else {
                   7209: 	$symb=$passedsymb;
                   7210:     }
                   7211:     $courseid=$env{'request.course.id'};
                   7212:     $domain=$env{'user.domain'};
                   7213:     $name=$env{'user.name'};
                   7214:     if ($name eq 'public' && $domain eq 'public') {
                   7215: 	if (!defined($env{'form.username'})) {
                   7216: 	    $env{'form.username'}.=time.rand(10000000);
                   7217: 	}
                   7218: 	$name.=$env{'form.username'};
                   7219:     }
                   7220:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7221: 
                   7222: }
                   7223: 
1.36      albertel 7224: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7225: # returns either the contents of the file or 
                   7226: # -1 if the file doesn't exist
1.481     raeburn  7227: #
                   7228: # if the target is a file that was uploaded via DOCS, 
                   7229: # a check will be made to see if a current copy exists on the local server,
                   7230: # if it does this will be served, otherwise a copy will be retrieved from
                   7231: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7232: # the local server.   
1.472     albertel 7233: 
1.36      albertel 7234: sub getfile {
1.538     albertel 7235:     my ($file) = @_;
1.609     banghart 7236:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7237:     &repcopy($file);
                   7238:     return &readfile($file);
                   7239: }
                   7240: 
                   7241: sub repcopy_userfile {
                   7242:     my ($file)=@_;
1.609     banghart 7243:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7244:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7245:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7246: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7247:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7248:     if (-e "$file") {
1.828     www      7249: # we already have a local copy, check it out
1.538     albertel 7250: 	my @fileinfo = stat($file);
1.828     www      7251: 	my $rtncode;
                   7252: 	my $info;
1.538     albertel 7253: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7254: 	if ($lwpresp ne 'ok') {
1.828     www      7255: # there is no such file anymore, even though we had a local copy
1.482     albertel 7256: 	    if ($rtncode eq '404') {
1.538     albertel 7257: 		unlink($file);
1.482     albertel 7258: 	    }
                   7259: 	    return -1;
                   7260: 	}
                   7261: 	if ($info < $fileinfo[9]) {
1.828     www      7262: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7263: 	    return 'ok';
1.828     www      7264: 	} else {
                   7265: # the file is outdated, get rid of it
                   7266: 	    unlink($file);
1.482     albertel 7267: 	}
1.828     www      7268:     }
                   7269: # one way or the other, at this point, we don't have the file
                   7270: # construct the correct path for the file
                   7271:     my @parts = ($cdom,$cnum); 
                   7272:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7273: 	push @parts, split(/\//,$1);
                   7274:     }
                   7275:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7276:     foreach my $part (@parts) {
                   7277: 	$path .= '/'.$part;
                   7278: 	if (!-e $path) {
                   7279: 	    mkdir($path,0770);
1.482     albertel 7280: 	}
                   7281:     }
1.828     www      7282: # now the path exists for sure
                   7283: # get a user agent
                   7284:     my $ua=new LWP::UserAgent;
                   7285:     my $transferfile=$file.'.in.transfer';
                   7286: # FIXME: this should flock
                   7287:     if (-e $transferfile) { return 'ok'; }
                   7288:     my $request;
                   7289:     $uri=~s/^\///;
1.838     albertel 7290:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7291:     my $response=$ua->request($request,$transferfile);
                   7292: # did it work?
                   7293:     if ($response->is_error()) {
                   7294: 	unlink($transferfile);
                   7295: 	&logthis("Userfile repcopy failed for $uri");
                   7296: 	return -1;
                   7297:     }
                   7298: # worked, rename the transfer file
                   7299:     rename($transferfile,$file);
1.607     raeburn  7300:     return 'ok';
1.481     raeburn  7301: }
                   7302: 
1.517     albertel 7303: sub tokenwrapper {
                   7304:     my $uri=shift;
1.552     albertel 7305:     $uri=~s|^http\://([^/]+)||;
                   7306:     $uri=~s|^/||;
1.620     albertel 7307:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7308:     my $token=$1;
1.552     albertel 7309:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7310:     if ($udom && $uname && $file) {
                   7311: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7312:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7313:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7314:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7315:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7316:     } else {
                   7317:         return '/adm/notfound.html';
                   7318:     }
                   7319: }
                   7320: 
1.828     www      7321: # call with reqtype HEAD: get last modification time
                   7322: # call with reqtype GET: get the file contents
                   7323: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7324: #
1.481     raeburn  7325: sub getuploaded {
                   7326:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7327:     $uri=~s/^\///;
1.838     albertel 7328:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7329:     my $ua=new LWP::UserAgent;
                   7330:     my $request=new HTTP::Request($reqtype,$uri);
                   7331:     my $response=$ua->request($request);
                   7332:     $$rtncode = $response->code;
1.482     albertel 7333:     if (! $response->is_success()) {
                   7334: 	return 'failed';
                   7335:     }      
                   7336:     if ($reqtype eq 'HEAD') {
1.486     www      7337: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7338:     } elsif ($reqtype eq 'GET') {
                   7339: 	$$info = $response->content;
1.472     albertel 7340:     }
1.482     albertel 7341:     return 'ok';
1.36      albertel 7342: }
                   7343: 
1.481     raeburn  7344: sub readfile {
                   7345:     my $file = shift;
                   7346:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7347:     my $fh;
                   7348:     open($fh,"<$file");
                   7349:     my $a='';
1.800     albertel 7350:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7351:     return $a;
                   7352: }
                   7353: 
1.36      albertel 7354: sub filelocation {
1.590     banghart 7355:     my ($dir,$file) = @_;
                   7356:     my $location;
                   7357:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7358: 
                   7359:     if ($file =~ m-^/adm/-) {
                   7360: 	$file=~s-^/adm/wrapper/-/-;
                   7361: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7362:     }
1.590     banghart 7363:     if ($file=~m:^/~:) { # is a contruction space reference
                   7364:         $location = $file;
                   7365:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7366:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7367: 	# is a correct contruction space reference
                   7368:         $location = $file;
1.609     banghart 7369:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7370:         my ($udom,$uname,$filename)=
1.811     albertel 7371:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7372:         my $home=&homeserver($uname,$udom);
                   7373:         my $is_me=0;
                   7374:         my @ids=&current_machine_ids();
                   7375:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7376:         if ($is_me) {
1.740     www      7377:   	    $location=&propath($udom,$uname).
1.590     banghart 7378:   	      '/userfiles/'.$filename;
                   7379:         } else {
                   7380:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7381:   	      $udom.'/'.$uname.'/'.$filename;
                   7382:         }
                   7383:     } else {
                   7384:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7385:         $file=~s:^/res/:/:;
                   7386:         if ( !( $file =~ m:^/:) ) {
                   7387:             $location = $dir. '/'.$file;
                   7388:         } else {
                   7389:             $location = '/home/httpd/html/res'.$file;
                   7390:         }
1.59      albertel 7391:     }
1.590     banghart 7392:     $location=~s://+:/:g; # remove duplicate /
                   7393:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7394:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7395:     return $location;
1.46      www      7396: }
1.36      albertel 7397: 
1.46      www      7398: sub hreflocation {
                   7399:     my ($dir,$file)=@_;
1.460     albertel 7400:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7401: 	$file=filelocation($dir,$file);
1.700     albertel 7402:     } elsif ($file=~m-^/adm/-) {
                   7403: 	$file=~s-^/adm/wrapper/-/-;
                   7404: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7405:     }
                   7406:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7407: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7408:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7409: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7410:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7411: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7412: 	    -/uploaded/$1/$2/-x;
1.46      www      7413:     }
1.462     albertel 7414:     return $file;
1.465     albertel 7415: }
                   7416: 
                   7417: sub current_machine_domains {
1.838     albertel 7418:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7419:     my @domains;
1.838     albertel 7420:     my %hostname = &all_hostnames();
1.465     albertel 7421:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7422: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7423: 	if ($hostname eq $name) {
                   7424: 	    push(@domains,$hostdom{$id});
                   7425: 	}
                   7426:     }
                   7427:     return @domains;
                   7428: }
                   7429: 
                   7430: sub current_machine_ids {
1.838     albertel 7431:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7432:     my @ids;
1.838     albertel 7433:     my %hostname = &all_hostnames();
1.465     albertel 7434:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7435: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7436: 	if ($hostname eq $name) {
                   7437: 	    push(@ids,$id);
                   7438: 	}
                   7439:     }
                   7440:     return @ids;
1.31      www      7441: }
                   7442: 
1.824     raeburn  7443: sub additional_machine_domains {
                   7444:     my @domains;
                   7445:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7446:     while( my $line = <$fh>) {
                   7447:         $line =~ s/\s//g;
                   7448:         push(@domains,$line);
                   7449:     }
                   7450:     return @domains;
                   7451: }
                   7452: 
                   7453: sub default_login_domain {
                   7454:     my $domain = $perlvar{'lonDefDomain'};
                   7455:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7456:     foreach my $posdom (&current_machine_domains(),
                   7457:                         &additional_machine_domains()) {
                   7458:         if (lc($posdom) eq lc($testdomain)) {
                   7459:             $domain=$posdom;
                   7460:             last;
                   7461:         }
                   7462:     }
                   7463:     return $domain;
                   7464: }
                   7465: 
1.31      www      7466: # ------------------------------------------------------------- Declutters URLs
                   7467: 
                   7468: sub declutter {
                   7469:     my $thisfn=shift;
1.569     albertel 7470:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7471:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7472:     $thisfn=~s/^\///;
1.697     albertel 7473:     $thisfn=~s|^adm/wrapper/||;
                   7474:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7475:     $thisfn=~s/^res\///;
1.235     www      7476:     $thisfn=~s/\?.+$//;
1.268     www      7477:     return $thisfn;
                   7478: }
                   7479: 
                   7480: # ------------------------------------------------------------- Clutter up URLs
                   7481: 
                   7482: sub clutter {
                   7483:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7484:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7485:        $thisfn='/res'.$thisfn; 
                   7486:     }
1.694     albertel 7487:     if ($thisfn !~m|/adm|) {
1.695     albertel 7488: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7489: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7490: 	} else {
                   7491: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7492: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7493: 	    if ($embstyle eq 'ssi'
                   7494: 		|| ($embstyle eq 'hdn')
                   7495: 		|| ($embstyle eq 'rat')
                   7496: 		|| ($embstyle eq 'prv')
                   7497: 		|| ($embstyle eq 'ign')) {
                   7498: 		#do nothing with these
                   7499: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7500: 		|| ($embstyle eq 'emb')
                   7501: 		|| ($embstyle eq 'wrp')) {
                   7502: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7503: 	    } elsif ($embstyle eq 'unk'
                   7504: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7505: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7506: 	    } else {
1.718     www      7507: #		&logthis("Got a blank emb style");
1.695     albertel 7508: 	    }
1.694     albertel 7509: 	}
                   7510:     }
1.31      www      7511:     return $thisfn;
1.12      www      7512: }
                   7513: 
1.787     albertel 7514: sub clutter_with_no_wrapper {
                   7515:     my $uri = &clutter(shift);
                   7516:     if ($uri =~ m-^/adm/-) {
                   7517: 	$uri =~ s-^/adm/wrapper/-/-;
                   7518: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7519:     }
                   7520:     return $uri;
                   7521: }
                   7522: 
1.557     albertel 7523: sub freeze_escape {
                   7524:     my ($value)=@_;
                   7525:     if (ref($value)) {
                   7526: 	$value=&nfreeze($value);
                   7527: 	return '__FROZEN__'.&escape($value);
                   7528:     }
                   7529:     return &escape($value);
                   7530: }
                   7531: 
1.11      www      7532: 
1.557     albertel 7533: sub thaw_unescape {
                   7534:     my ($value)=@_;
                   7535:     if ($value =~ /^__FROZEN__/) {
                   7536: 	substr($value,0,10,undef);
                   7537: 	$value=&unescape($value);
                   7538: 	return &thaw($value);
                   7539:     }
                   7540:     return &unescape($value);
                   7541: }
                   7542: 
1.436     albertel 7543: sub correct_line_ends {
                   7544:     my ($result)=@_;
                   7545:     $$result =~s/\r\n/\n/mg;
                   7546:     $$result =~s/\r/\n/mg;
1.415     albertel 7547: }
1.1       albertel 7548: # ================================================================ Main Program
                   7549: 
1.184     www      7550: sub goodbye {
1.204     albertel 7551:    &logthis("Starting Shut down");
1.443     albertel 7552: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7553:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7554: #converted
1.599     albertel 7555: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7556:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7557: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7558: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7559: #1.1 only
1.599     albertel 7560: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7561: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7562: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7563: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7564:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7565:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7566:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7567:    &flushcourselogs();
                   7568:    &logthis("Shutting down");
                   7569: }
                   7570: 
1.179     www      7571: BEGIN {
1.228     harris41 7572: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7573:     unless ($readit) {
1.217     harris41 7574: {
1.781     raeburn  7575:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7576:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7577: }
1.1       albertel 7578: 
1.327     albertel 7579: # ------------------------------------------------------------ Read domain file
                   7580: {
                   7581:     %domaindescription = ();
                   7582:     %domain_auth_def = ();
                   7583:     %domain_auth_arg_def = ();
1.448     albertel 7584:     my $fh;
                   7585:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7586: 	while (my $line = <$fh>) {
                   7587:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7588: #           next if /^\#/;
1.801     foxr     7589:            chomp $line;
1.403     www      7590:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7591: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7592: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7593:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7594: 	   $domaindescription{$domain}=$domain_description;
                   7595: 	   $domain_lang_def{$domain}=$def_lang;
                   7596: 	   $domain_city{$domain}=$city;
                   7597: 	   $domain_longi{$domain}=$longi;
                   7598: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7599:            $domain_primary{$domain}=$primary;
1.403     www      7600: 
1.448     albertel 7601:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7602: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7603: 	}
1.327     albertel 7604:     }
1.448     albertel 7605:     close ($fh);
1.327     albertel 7606: }
                   7607: 
                   7608: 
1.1       albertel 7609: # ------------------------------------------------------------- Read hosts file
                   7610: {
1.838     albertel 7611:     my %hostname;
1.448     albertel 7612:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7613: 
                   7614:     while (my $configline=<$config>) {
1.303     matthew  7615:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7616:        chomp($configline);
1.595     albertel 7617:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7618:        $name=~s/\s//g;
1.595     albertel 7619:        if ($id && $domain && $role && $name) {
1.252     albertel 7620: 	 $hostname{$id}=$name;
                   7621: 	 $hostdom{$id}=$domain;
                   7622: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7623:        }
1.1       albertel 7624:     }
1.448     albertel 7625:     close($config);
1.619     albertel 7626:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7627:     #&get_iphost();
1.838     albertel 7628: 
                   7629:     sub hostname {
                   7630: 	my ($lonid) = @_;
                   7631: 	return $hostname{$lonid};
                   7632:     }
                   7633:     sub all_hostnames {
                   7634: 	return %hostname;
                   7635:     }
1.1       albertel 7636: }
                   7637: 
1.839     albertel 7638: sub get_hosts_from_ip {
                   7639:     my ($ip) = @_;
                   7640:     my %iphosts = &get_iphost();
                   7641:     if (ref($iphosts{$ip})) {
                   7642: 	return @{$iphosts{$ip}};
                   7643:     }
                   7644:     return;
                   7645: }
                   7646: 
1.598     albertel 7647: sub get_iphost {
                   7648:     if (%iphost) { return %iphost; }
1.653     albertel 7649:     my %name_to_ip;
1.838     albertel 7650:     my %hostname = &all_hostnames();
1.598     albertel 7651:     foreach my $id (keys(%hostname)) {
                   7652: 	my $name=$hostname{$id};
1.653     albertel 7653: 	my $ip;
                   7654: 	if (!exists($name_to_ip{$name})) {
                   7655: 	    $ip = gethostbyname($name);
                   7656: 	    if (!$ip || length($ip) ne 4) {
1.826     www      7657: 		&logthis("Skipping host $id name $name no IP found");
1.653     albertel 7658: 		next;
                   7659: 	    }
                   7660: 	    $ip=inet_ntoa($ip);
                   7661: 	    $name_to_ip{$name} = $ip;
                   7662: 	} else {
                   7663: 	    $ip = $name_to_ip{$name};
1.598     albertel 7664: 	}
                   7665: 	push(@{$iphost{$ip}},$id);
                   7666:     }
                   7667:     return %iphost;
                   7668: }
                   7669: 
1.1       albertel 7670: # ------------------------------------------------------ Read spare server file
                   7671: {
1.448     albertel 7672:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7673: 
                   7674:     while (my $configline=<$config>) {
                   7675:        chomp($configline);
1.284     matthew  7676:        if ($configline) {
1.784     albertel 7677: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7678: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7679: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7680:        }
                   7681:     }
1.448     albertel 7682:     close($config);
1.1       albertel 7683: }
1.11      www      7684: # ------------------------------------------------------------ Read permissions
                   7685: {
1.448     albertel 7686:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7687: 
                   7688:     while (my $configline=<$config>) {
1.448     albertel 7689: 	chomp($configline);
                   7690: 	if ($configline) {
                   7691: 	    my ($role,$perm)=split(/ /,$configline);
                   7692: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7693: 	}
1.11      www      7694:     }
1.448     albertel 7695:     close($config);
1.11      www      7696: }
                   7697: 
                   7698: # -------------------------------------------- Read plain texts for permissions
                   7699: {
1.448     albertel 7700:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7701: 
                   7702:     while (my $configline=<$config>) {
1.448     albertel 7703: 	chomp($configline);
                   7704: 	if ($configline) {
1.742     raeburn  7705: 	    my ($short,@plain)=split(/:/,$configline);
                   7706:             %{$prp{$short}} = ();
                   7707: 	    if (@plain > 0) {
                   7708:                 $prp{$short}{'std'} = $plain[0];
                   7709:                 for (my $i=1; $i<@plain; $i++) {
                   7710:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7711:                 }
                   7712:             }
1.448     albertel 7713: 	}
1.135     www      7714:     }
1.448     albertel 7715:     close($config);
1.135     www      7716: }
                   7717: 
                   7718: # ---------------------------------------------------------- Read package table
                   7719: {
1.448     albertel 7720:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7721: 
                   7722:     while (my $configline=<$config>) {
1.483     albertel 7723: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7724: 	chomp($configline);
                   7725: 	my ($short,$plain)=split(/:/,$configline);
                   7726: 	my ($pack,$name)=split(/\&/,$short);
                   7727: 	if ($plain ne '') {
                   7728: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7729: 	    $packagetab{$short}=$plain; 
                   7730: 	}
1.11      www      7731:     }
1.448     albertel 7732:     close($config);
1.329     matthew  7733: }
                   7734: 
                   7735: # ------------- set up temporary directory
                   7736: {
                   7737:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7738: 
1.11      www      7739: }
                   7740: 
1.794     albertel 7741: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7742: 				'compress_threshold'=> 20_000,
                   7743:  			        });
1.185     www      7744: 
1.281     www      7745: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7746: $dumpcount=0;
1.22      www      7747: 
1.163     harris41 7748: &logtouch();
1.672     albertel 7749: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7750: $readit=1;
1.564     albertel 7751:     {
                   7752: 	use integer;
                   7753: 	my $test=(2**32)+1;
1.568     albertel 7754: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7755: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7756:     }
1.195     www      7757: }
1.1       albertel 7758: }
1.179     www      7759: 
1.1       albertel 7760: 1;
1.191     harris41 7761: __END__
                   7762: 
1.243     albertel 7763: =pod
                   7764: 
1.191     harris41 7765: =head1 NAME
                   7766: 
1.243     albertel 7767: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7768: 
                   7769: =head1 SYNOPSIS
                   7770: 
1.243     albertel 7771: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7772: 
                   7773:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7774: 
1.243     albertel 7775: Common parameters:
                   7776: 
                   7777: =over 4
                   7778: 
                   7779: =item *
                   7780: 
                   7781: $uname : an internal username (if $cname expecting a course Id specifically)
                   7782: 
                   7783: =item *
                   7784: 
                   7785: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7786: 
                   7787: =item *
                   7788: 
                   7789: $symb : a resource instance identifier
                   7790: 
                   7791: =item *
                   7792: 
                   7793: $namespace : the name of a .db file that contains the data needed or
                   7794: being set.
                   7795: 
                   7796: =back
                   7797: 
1.394     bowersj2 7798: =head1 OVERVIEW
1.191     harris41 7799: 
1.394     bowersj2 7800: lonnet provides subroutines which interact with the
                   7801: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7802: about classes, users, and resources.
1.243     albertel 7803: 
                   7804: For many of these objects you can also use this to store data about
                   7805: them or modify them in various ways.
1.191     harris41 7806: 
1.394     bowersj2 7807: =head2 Symbs
1.191     harris41 7808: 
1.394     bowersj2 7809: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7810: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7811: map, the resource number of the resource in the map, and the URL of
                   7812: the resource itself. The latter is somewhat redundant, but might help
                   7813: if maps change.
                   7814: 
                   7815: An example is
                   7816: 
                   7817:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7818: 
                   7819: The respective map entry is
                   7820: 
                   7821:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7822:   title="Problem 2">
                   7823:  </resource>
                   7824: 
                   7825: Symbs are used by the random number generator, as well as to store and
                   7826: restore data specific to a certain instance of for example a problem.
                   7827: 
                   7828: =head2 Storing And Retrieving Data
                   7829: 
                   7830: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7831: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7832: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7833: is is the non-critical message twin of cstore. These functions are for
                   7834: handlers to store a perl hash to a user's permanent data space in an
                   7835: easy manner, and to retrieve it again on another call. It is expected
                   7836: that a handler would use this once at the beginning to retrieve data,
                   7837: and then again once at the end to send only the new data back.
                   7838: 
                   7839: The data is stored in the user's data directory on the user's
                   7840: homeserver under the ID of the course.
                   7841: 
                   7842: The hash that is returned by restore will have all of the previous
                   7843: value for all of the elements of the hash.
                   7844: 
                   7845: Example:
                   7846: 
                   7847:  #creating a hash
                   7848:  my %hash;
                   7849:  $hash{'foo'}='bar';
                   7850: 
                   7851:  #storing it
                   7852:  &Apache::lonnet::cstore(\%hash);
                   7853: 
                   7854:  #changing a value
                   7855:  $hash{'foo'}='notbar';
                   7856: 
                   7857:  #adding a new value
                   7858:  $hash{'bar'}='foo';
                   7859:  &Apache::lonnet::cstore(\%hash);
                   7860: 
                   7861:  #retrieving the hash
                   7862:  my %history=&Apache::lonnet::restore();
                   7863: 
                   7864:  #print the hash
                   7865:  foreach my $key (sort(keys(%history))) {
                   7866:    print("\%history{$key} = $history{$key}");
                   7867:  }
                   7868: 
                   7869: Will print out:
1.191     harris41 7870: 
1.394     bowersj2 7871:  %history{1:foo} = bar
                   7872:  %history{1:keys} = foo:timestamp
                   7873:  %history{1:timestamp} = 990455579
                   7874:  %history{2:bar} = foo
                   7875:  %history{2:foo} = notbar
                   7876:  %history{2:keys} = foo:bar:timestamp
                   7877:  %history{2:timestamp} = 990455580
                   7878:  %history{bar} = foo
                   7879:  %history{foo} = notbar
                   7880:  %history{timestamp} = 990455580
                   7881:  %history{version} = 2
                   7882: 
                   7883: Note that the special hash entries C<keys>, C<version> and
                   7884: C<timestamp> were added to the hash. C<version> will be equal to the
                   7885: total number of versions of the data that have been stored. The
                   7886: C<timestamp> attribute will be the UNIX time the hash was
                   7887: stored. C<keys> is available in every historical section to list which
                   7888: keys were added or changed at a specific historical revision of a
                   7889: hash.
                   7890: 
                   7891: B<Warning>: do not store the hash that restore returns directly. This
                   7892: will cause a mess since it will restore the historical keys as if the
                   7893: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7894: 
1.394     bowersj2 7895: Calling convention:
1.191     harris41 7896: 
1.394     bowersj2 7897:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7898:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7899: 
1.394     bowersj2 7900: For more detailed information, see lonnet specific documentation.
1.191     harris41 7901: 
1.394     bowersj2 7902: =head1 RETURN MESSAGES
1.191     harris41 7903: 
1.394     bowersj2 7904: =over 4
1.191     harris41 7905: 
1.394     bowersj2 7906: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7907: 
1.394     bowersj2 7908: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7909: when the connection is brought back up
1.191     harris41 7910: 
1.394     bowersj2 7911: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7912: for later delivery
1.191     harris41 7913: 
1.394     bowersj2 7914: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7915: 
1.394     bowersj2 7916: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7917: that was requested
1.191     harris41 7918: 
1.243     albertel 7919: =back
1.191     harris41 7920: 
1.243     albertel 7921: =head1 PUBLIC SUBROUTINES
1.191     harris41 7922: 
1.243     albertel 7923: =head2 Session Environment Functions
1.191     harris41 7924: 
1.243     albertel 7925: =over 4
1.191     harris41 7926: 
1.394     bowersj2 7927: =item * 
                   7928: X<appenv()>
                   7929: B<appenv(%hash)>: the value of %hash is written to
                   7930: the user envirnoment file, and will be restored for each access this
1.620     albertel 7931: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7932: process
1.191     harris41 7933: 
                   7934: =item *
1.394     bowersj2 7935: X<delenv()>
                   7936: B<delenv($regexp)>: removes all items from the session
                   7937: environment file that matches the regular expression in $regexp. The
1.620     albertel 7938: values are also delted from the current processes %env.
1.191     harris41 7939: 
1.795     albertel 7940: =item * get_env_multiple($name) 
                   7941: 
                   7942: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7943: values may be defined and end up as an array ref.
                   7944: 
                   7945: returns an array of values
                   7946: 
1.243     albertel 7947: =back
                   7948: 
                   7949: =head2 User Information
1.191     harris41 7950: 
1.243     albertel 7951: =over 4
1.191     harris41 7952: 
                   7953: =item *
1.394     bowersj2 7954: X<queryauthenticate()>
                   7955: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7956: authentication scheme
                   7957: 
                   7958: =item *
1.394     bowersj2 7959: X<authenticate()>
                   7960: B<authenticate($uname,$upass,$udom)>: try to
                   7961: authenticate user from domain's lib servers (first use the current
                   7962: one). C<$upass> should be the users password.
1.191     harris41 7963: 
                   7964: =item *
1.394     bowersj2 7965: X<homeserver()>
                   7966: B<homeserver($uname,$udom)>: find the server which has
                   7967: the user's directory and files (there must be only one), this caches
                   7968: the answer, and also caches if there is a borken connection.
1.191     harris41 7969: 
                   7970: =item *
1.394     bowersj2 7971: X<idget()>
                   7972: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7973: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7974: username, and only 1 username per ID in a specific domain) (returns
                   7975: hash: id=>name,id=>name)
1.191     harris41 7976: 
                   7977: =item *
1.394     bowersj2 7978: X<idrget()>
                   7979: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7980: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7981: 
                   7982: =item *
1.394     bowersj2 7983: X<idput()>
                   7984: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7985: 
                   7986: =item *
1.394     bowersj2 7987: X<rolesinit()>
                   7988: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7989: 
                   7990: =item *
1.551     albertel 7991: X<getsection()>
                   7992: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7993: course $cname, return section name/number or '' for "not in course"
                   7994: and '-1' for "no section"
                   7995: 
                   7996: =item *
1.394     bowersj2 7997: X<userenvironment()>
                   7998: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7999: passed in @what from the requested user's environment, returns a hash
                   8000: 
                   8001: =back
                   8002: 
                   8003: =head2 User Roles
                   8004: 
                   8005: =over 4
                   8006: 
                   8007: =item *
                   8008: 
1.810     raeburn  8009: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8010:  F: full access
                   8011:  U,I,K: authentication modes (cxx only)
                   8012:  '': forbidden
                   8013:  1: user needs to choose course
                   8014:  2: browse allowed
1.766     albertel 8015:  A: passphrase authentication needed
1.243     albertel 8016: 
                   8017: =item *
                   8018: 
                   8019: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8020: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8021: and course level
                   8022: 
                   8023: =item *
                   8024: 
                   8025: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8026: explanation of a user role term
                   8027: 
1.832     raeburn  8028: =item *
                   8029: 
1.834     albertel 8030: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
                   8031: optional.  Returns a hash of a user's roles, with keys set to
                   8032: colon-sparated $uname,$udom,and $role, and value set to
                   8033: colon-separated start and end times for the role. If no username and
                   8034: domain are specified, will default to current user/domain. Types,
                   8035: roles, and roledoms are references to arrays, of role statuses
                   8036: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
                   8037: of the roles which can be used to restrict the list if roles
                   8038: reported. If no array ref is provided for types, will default to
                   8039: return only active roles.
                   8040: 
1.243     albertel 8041: =back
                   8042: 
                   8043: =head2 User Modification
                   8044: 
                   8045: =over 4
                   8046: 
                   8047: =item *
                   8048: 
                   8049: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8050: user for the level given by URL.  Optional start and end dates (leave empty
                   8051: string or zero for "no date")
1.191     harris41 8052: 
                   8053: =item *
                   8054: 
1.243     albertel 8055: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8056: change a users, password, possible return values are: ok,
                   8057: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8058: refused
1.191     harris41 8059: 
                   8060: =item *
                   8061: 
1.243     albertel 8062: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8063: 
                   8064: =item *
                   8065: 
1.243     albertel 8066: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8067: modify user
1.191     harris41 8068: 
                   8069: =item *
                   8070: 
1.286     matthew  8071: modifystudent
                   8072: 
                   8073: modify a students enrollment and identification information.
                   8074: The course id is resolved based on the current users environment.  
                   8075: This means the envoking user must be a course coordinator or otherwise
                   8076: associated with a course.
                   8077: 
1.297     matthew  8078: This call is essentially a wrapper for lonnet::modifyuser and
                   8079: lonnet::modify_student_enrollment
1.286     matthew  8080: 
                   8081: Inputs: 
                   8082: 
                   8083: =over 4
                   8084: 
                   8085: =item B<$udom> Students loncapa domain
                   8086: 
                   8087: =item B<$uname> Students loncapa login name
                   8088: 
                   8089: =item B<$uid> Students id/student number
                   8090: 
                   8091: =item B<$umode> Students authentication mode
                   8092: 
                   8093: =item B<$upass> Students password
                   8094: 
                   8095: =item B<$first> Students first name
                   8096: 
                   8097: =item B<$middle> Students middle name
                   8098: 
                   8099: =item B<$last> Students last name
                   8100: 
                   8101: =item B<$gene> Students generation
                   8102: 
                   8103: =item B<$usec> Students section in course
                   8104: 
                   8105: =item B<$end> Unix time of the roles expiration
                   8106: 
                   8107: =item B<$start> Unix time of the roles start date
                   8108: 
                   8109: =item B<$forceid> If defined, allow $uid to be changed
                   8110: 
                   8111: =item B<$desiredhome> server to use as home server for student
                   8112: 
                   8113: =back
1.297     matthew  8114: 
                   8115: =item *
                   8116: 
                   8117: modify_student_enrollment
                   8118: 
                   8119: Change a students enrollment status in a class.  The environment variable
                   8120: 'role.request.course' must be defined for this function to proceed.
                   8121: 
                   8122: Inputs:
                   8123: 
                   8124: =over 4
                   8125: 
                   8126: =item $udom, students domain
                   8127: 
                   8128: =item $uname, students name
                   8129: 
                   8130: =item $uid, students user id
                   8131: 
                   8132: =item $first, students first name
                   8133: 
                   8134: =item $middle
                   8135: 
                   8136: =item $last
                   8137: 
                   8138: =item $gene
                   8139: 
                   8140: =item $usec
                   8141: 
                   8142: =item $end
                   8143: 
                   8144: =item $start
                   8145: 
                   8146: =back
                   8147: 
1.191     harris41 8148: 
                   8149: =item *
                   8150: 
1.243     albertel 8151: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8152: custom role; give a custom role to a user for the level given by URL.  Specify
                   8153: name and domain of role author, and role name
1.191     harris41 8154: 
                   8155: =item *
                   8156: 
1.243     albertel 8157: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8158: 
                   8159: =item *
                   8160: 
1.243     albertel 8161: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8162: 
                   8163: =back
                   8164: 
                   8165: =head2 Course Infomation
                   8166: 
                   8167: =over 4
1.191     harris41 8168: 
                   8169: =item *
                   8170: 
1.631     albertel 8171: coursedescription($courseid) : returns a hash of information about the
                   8172: specified course id, including all environment settings for the
                   8173: course, the description of the course will be in the hash under the
                   8174: key 'description'
1.191     harris41 8175: 
                   8176: =item *
                   8177: 
1.624     albertel 8178: resdata($name,$domain,$type,@which) : request for current parameter
                   8179: setting for a specific $type, where $type is either 'course' or 'user',
                   8180: @what should be a list of parameters to ask about. This routine caches
                   8181: answers for 5 minutes.
1.243     albertel 8182: 
                   8183: =back
                   8184: 
                   8185: =head2 Course Modification
                   8186: 
                   8187: =over 4
1.191     harris41 8188: 
                   8189: =item *
                   8190: 
1.243     albertel 8191: writecoursepref($courseid,%prefs) : write preferences (environment
                   8192: database) for a course
1.191     harris41 8193: 
                   8194: =item *
                   8195: 
1.243     albertel 8196: createcourse($udom,$description,$url) : make/modify course
                   8197: 
                   8198: =back
                   8199: 
                   8200: =head2 Resource Subroutines
                   8201: 
                   8202: =over 4
1.191     harris41 8203: 
                   8204: =item *
                   8205: 
1.243     albertel 8206: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8207: 
                   8208: =item *
                   8209: 
1.243     albertel 8210: repcopy($filename) : subscribes to the requested file, and attempts to
                   8211: replicate from the owning library server, Might return
1.607     raeburn  8212: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8213: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8214: resource. Expects the local filesystem pathname
                   8215: (/home/httpd/html/res/....)
                   8216: 
                   8217: =back
                   8218: 
                   8219: =head2 Resource Information
                   8220: 
                   8221: =over 4
1.191     harris41 8222: 
                   8223: =item *
                   8224: 
1.243     albertel 8225: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8226: a vairety of different possible values, $varname should be a request
                   8227: string, and the other parameters can be used to specify who and what
                   8228: one is asking about.
                   8229: 
                   8230: Possible values for $varname are environment.lastname (or other item
                   8231: from the envirnment hash), user.name (or someother aspect about the
                   8232: user), resource.0.maxtries (or some other part and parameter of a
                   8233: resource)
1.204     albertel 8234: 
                   8235: =item *
                   8236: 
1.243     albertel 8237: directcondval($number) : get current value of a condition; reads from a state
                   8238: string
1.204     albertel 8239: 
                   8240: =item *
                   8241: 
1.243     albertel 8242: condval($condidx) : value of condition index based on state
1.204     albertel 8243: 
                   8244: =item *
                   8245: 
1.243     albertel 8246: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8247: resource's metadata, $what should be either a specific key, or either
                   8248: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8249: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8250: 
                   8251: this function automatically caches all requests
1.191     harris41 8252: 
                   8253: =item *
                   8254: 
1.243     albertel 8255: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8256: network of library servers; returns file handle of where SQL and regex results
                   8257: will be stored for query
1.191     harris41 8258: 
                   8259: =item *
                   8260: 
1.243     albertel 8261: symbread($filename) : return symbolic list entry (filename argument optional);
                   8262: returns the data handle
1.191     harris41 8263: 
                   8264: =item *
                   8265: 
1.243     albertel 8266: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8267: a possible symb for the URL in $thisfn, and if is an encryypted
                   8268: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8269: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8270: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8271: 
1.191     harris41 8272: 
                   8273: =item *
                   8274: 
1.243     albertel 8275: symbclean($symb) : removes versions numbers from a symb, returns the
                   8276: cleaned symb
1.191     harris41 8277: 
                   8278: =item *
                   8279: 
1.243     albertel 8280: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8281: course map, user must be in a course for it to work.
1.191     harris41 8282: 
                   8283: =item *
                   8284: 
1.243     albertel 8285: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8286: 
                   8287: =item *
                   8288: 
1.243     albertel 8289: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8290: a random seed, all arguments are optional, if they aren't sent it uses the
                   8291: environment to derive them. Note: if symb isn't sent and it can't get one
                   8292: from &symbread it will use the current time as its return value
1.191     harris41 8293: 
                   8294: =item *
                   8295: 
1.243     albertel 8296: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8297: unfakeable, receipt
1.191     harris41 8298: 
                   8299: =item *
                   8300: 
1.620     albertel 8301: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8302: 
                   8303: =item *
                   8304: 
1.243     albertel 8305: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8306: 
                   8307: =item *
                   8308: 
1.243     albertel 8309: 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 8310: 
                   8311: =item *
                   8312: 
1.243     albertel 8313: 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 8314: 
                   8315: =item *
                   8316: 
1.243     albertel 8317: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8318: 
                   8319: =item *
                   8320: 
1.243     albertel 8321: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8322: forcing spreadsheet to reevaluate the resource scores next time.
                   8323: 
                   8324: =back
                   8325: 
                   8326: =head2 Storing/Retreiving Data
                   8327: 
                   8328: =over 4
1.191     harris41 8329: 
                   8330: =item *
                   8331: 
1.243     albertel 8332: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8333: for this url; hashref needs to be given and should be a \%hashname; the
                   8334: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8335: be derived from the env
1.191     harris41 8336: 
                   8337: =item *
                   8338: 
1.243     albertel 8339: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8340: uses critical subroutine
1.191     harris41 8341: 
                   8342: =item *
                   8343: 
1.243     albertel 8344: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8345: all args are optional
1.191     harris41 8346: 
                   8347: =item *
                   8348: 
1.717     albertel 8349: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8350: dumps the complete (or key matching regexp) namespace into a hash
                   8351: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8352: normally &store()ed into
                   8353: 
                   8354: $range should be either an integer '100' (give me the first 100
                   8355:                                            matching records)
                   8356:               or be  two integers sperated by a - with no spaces
                   8357:                  '30-50' (give me the 30th through the 50th matching
                   8358:                           records)
                   8359: 
                   8360: 
                   8361: =item *
                   8362: 
                   8363: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8364: replaces a &store() version of data with a replacement set of data
                   8365: for a particular resource in a namespace passed in the $storehash hash 
                   8366: reference
                   8367: 
                   8368: =item *
                   8369: 
1.243     albertel 8370: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8371: works very similar to store/cstore, but all data is stored in a
                   8372: temporary location and can be reset using tmpreset, $storehash should
                   8373: be a hash reference, returns nothing on success
1.191     harris41 8374: 
                   8375: =item *
                   8376: 
1.243     albertel 8377: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8378: similar to restore, but all data is stored in a temporary location and
                   8379: can be reset using tmpreset. Returns a hash of values on success,
                   8380: error string otherwise.
1.191     harris41 8381: 
                   8382: =item *
                   8383: 
1.243     albertel 8384: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8385: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8386: 
                   8387: =item *
                   8388: 
1.243     albertel 8389: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8390: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8391: 
                   8392: =item *
                   8393: 
1.243     albertel 8394: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8395: namesp ($udom and $uname are optional)
1.191     harris41 8396: 
                   8397: =item *
                   8398: 
1.702     albertel 8399: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8400: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8401: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8402: 
1.702     albertel 8403: $range should be either an integer '100' (give me the first 100
                   8404:                                            matching records)
                   8405:               or be  two integers sperated by a - with no spaces
                   8406:                  '30-50' (give me the 30th through the 50th matching
                   8407:                           records)
1.449     matthew  8408: =item *
                   8409: 
                   8410: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8411: $store can be a scalar, an array reference, or if the amount to be 
                   8412: incremented is > 1, a hash reference.
                   8413: 
                   8414: ($udom and $uname are optional)
1.191     harris41 8415: 
                   8416: =item *
                   8417: 
1.243     albertel 8418: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8419: ($udom and $uname are optional)
1.191     harris41 8420: 
                   8421: =item *
                   8422: 
1.243     albertel 8423: cput($namespace,$storehash,$udom,$uname) : critical put
                   8424: ($udom and $uname are optional)
1.191     harris41 8425: 
                   8426: =item *
                   8427: 
1.748     albertel 8428: newput($namespace,$storehash,$udom,$uname) :
                   8429: 
                   8430: Attempts to store the items in the $storehash, but only if they don't
                   8431: currently exist, if this succeeds you can be certain that you have 
                   8432: successfully created a new key value pair in the $namespace db.
                   8433: 
                   8434: 
                   8435: Args:
                   8436:  $namespace: name of database to store values to
                   8437:  $storehash: hashref to store to the db
                   8438:  $udom: (optional) domain of user containing the db
                   8439:  $uname: (optional) name of user caontaining the db
                   8440: 
                   8441: Returns:
                   8442:  'ok' -> succeeded in storing all keys of $storehash
                   8443:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8444:                         least <key> already existed in the db (other
                   8445:                         requested keys may also already exist)
                   8446:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8447:  'con_lost' -> unable to contact request server
                   8448:  'refused' -> action was not allowed by remote machine
                   8449: 
                   8450: 
                   8451: =item *
                   8452: 
1.243     albertel 8453: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8454: reference filled in from namesp (encrypts the return communication)
                   8455: ($udom and $uname are optional)
1.191     harris41 8456: 
                   8457: =item *
                   8458: 
1.243     albertel 8459: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8460: critical subroutine
                   8461: 
1.806     raeburn  8462: =item *
                   8463: 
                   8464: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8465: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8466: 
                   8467: =item *
                   8468: 
                   8469: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8470: 
1.243     albertel 8471: =back
                   8472: 
                   8473: =head2 Network Status Functions
                   8474: 
                   8475: =over 4
1.191     harris41 8476: 
                   8477: =item *
                   8478: 
                   8479: dirlist($uri) : return directory list based on URI
                   8480: 
                   8481: =item *
                   8482: 
1.243     albertel 8483: spareserver() : find server with least workload from spare.tab
                   8484: 
                   8485: =back
                   8486: 
                   8487: =head2 Apache Request
                   8488: 
                   8489: =over 4
1.191     harris41 8490: 
                   8491: =item *
                   8492: 
1.243     albertel 8493: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8494: localhost, posts hash
                   8495: 
                   8496: =back
                   8497: 
                   8498: =head2 Data to String to Data
                   8499: 
                   8500: =over 4
1.191     harris41 8501: 
                   8502: =item *
                   8503: 
1.243     albertel 8504: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8505: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8506: 
                   8507: =item *
                   8508: 
1.243     albertel 8509: hashref2str($hashref) : convert a hashref into a string complete with
                   8510: escaping and '=' and '&' separators, supports elements that are
                   8511: arrayrefs and hashrefs
1.191     harris41 8512: 
                   8513: =item *
                   8514: 
1.243     albertel 8515: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8516: with escaping and '&' separators, supports elements that are arrayrefs
                   8517: and hashrefs
1.191     harris41 8518: 
                   8519: =item *
                   8520: 
1.243     albertel 8521: str2hash($string) : convert string to hash using unescaping and
                   8522: splitting on '=' and '&', supports elements that are arrayrefs and
                   8523: hashrefs
1.191     harris41 8524: 
                   8525: =item *
                   8526: 
1.243     albertel 8527: str2array($string) : convert string to hash using unescaping and
                   8528: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8529: 
                   8530: =back
                   8531: 
                   8532: =head2 Logging Routines
                   8533: 
                   8534: =over 4
                   8535: 
                   8536: These routines allow one to make log messages in the lonnet.log and
                   8537: lonnet.perm logfiles.
1.191     harris41 8538: 
                   8539: =item *
                   8540: 
1.243     albertel 8541: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8542: 
                   8543: =item *
                   8544: 
1.243     albertel 8545: logthis() : append message to the normal lonnet.log file, it gets
                   8546: preiodically rolled over and deleted.
1.191     harris41 8547: 
                   8548: =item *
                   8549: 
1.243     albertel 8550: logperm() : append a permanent message to lonnet.perm.log, this log
                   8551: file never gets deleted by any automated portion of the system, only
                   8552: messages of critical importance should go in here.
                   8553: 
                   8554: =back
                   8555: 
                   8556: =head2 General File Helper Routines
                   8557: 
                   8558: =over 4
1.191     harris41 8559: 
                   8560: =item *
                   8561: 
1.481     raeburn  8562: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8563: (a) files in /uploaded
                   8564:   (i) If a local copy of the file exists - 
                   8565:       compares modification date of local copy with last-modified date for 
                   8566:       definitive version stored on home server for course. If local copy is 
                   8567:       stale, requests a new version from the home server and stores it. 
                   8568:       If the original has been removed from the home server, then local copy 
                   8569:       is unlinked.
                   8570:   (ii) If local copy does not exist -
                   8571:       requests the file from the home server and stores it. 
                   8572:   
                   8573:   If $caller is 'uploadrep':  
                   8574:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8575:     for request for files originally uploaded via DOCS. 
                   8576:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8577:   
                   8578:   Otherwise:
                   8579:      This indicates a call from the content generation phase of the request.
                   8580:      -  returns the entire contents of the file or -1.
                   8581:      
                   8582: (b) files in /res
                   8583:    - returns the entire contents of a file or -1; 
                   8584:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8585: 
1.712     albertel 8586: 
                   8587: =item *
                   8588: 
                   8589: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8590:                   reference
                   8591: 
                   8592: returns either a stat() list of data about the file or an empty list
                   8593: if the file doesn't exist or couldn't find out about it (connection
                   8594: problems or user unknown)
                   8595: 
1.191     harris41 8596: =item *
                   8597: 
1.243     albertel 8598: filelocation($dir,$file) : returns file system location of a file
                   8599: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8600: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8601: and a file of ../bob will become /a/bob)
1.191     harris41 8602: 
                   8603: =item *
                   8604: 
                   8605: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8606: filelocation except for hrefs
                   8607: 
                   8608: =item *
                   8609: 
                   8610: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8611: 
1.243     albertel 8612: =back
                   8613: 
1.608     albertel 8614: =head2 Usererfile file routines (/uploaded*)
                   8615: 
                   8616: =over 4
                   8617: 
                   8618: =item *
                   8619: 
                   8620: userfileupload(): main rotine for putting a file in a user or course's
                   8621:                   filespace, arguments are,
                   8622: 
1.620     albertel 8623:  formname - required - this is the name of the element in $env where the
1.608     albertel 8624:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8625:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8626:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8627:  coursedoc - if true, store the file in the course of the active role
                   8628:              of the current user
                   8629:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8630:          if undefined, it will be placed in "unknown"
                   8631: 
                   8632:  (This routine calls clean_filename() to remove any dangerous
                   8633:  characters from the filename, and then calls finuserfileupload() to
                   8634:  complete the transaction)
                   8635: 
                   8636:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8637:  and /adm/notfound.html if unsuccessful
                   8638: 
                   8639: =item *
                   8640: 
                   8641: clean_filename(): routine for cleaing a filename up for storage in
                   8642:                  userfile space, argument is:
                   8643: 
                   8644:  filename - proposed filename
                   8645: 
                   8646: returns: the new clean filename
                   8647: 
                   8648: =item *
                   8649: 
                   8650: finishuserfileupload(): routine that creaes and sends the file to
                   8651: userspace, probably shouldn't be called directly
                   8652: 
                   8653:   docuname: username or courseid of destination for the file
                   8654:   docudom: domain of user/course of destination for the file
                   8655:   formname: same as for userfileupload()
                   8656:   fname: filename (inculding subdirectories) for the file
                   8657: 
                   8658:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8659:  and /adm/notfound.html if unsuccessful
                   8660: 
                   8661: =item *
                   8662: 
                   8663: renameuserfile(): renames an existing userfile to a new name
                   8664: 
                   8665:   Args:
                   8666:    docuname: username or courseid of destination for the file
                   8667:    docudom: domain of user/course of destination for the file
                   8668:    old: current file name (including any subdirs under userfiles)
                   8669:    new: desired file name (including any subdirs under userfiles)
                   8670: 
                   8671: =item *
                   8672: 
                   8673: mkdiruserfile(): creates a directory is a userfiles dir
                   8674: 
                   8675:   Args:
                   8676:    docuname: username or courseid of destination for the file
                   8677:    docudom: domain of user/course of destination for the file
                   8678:    dir: dir to create (including any subdirs under userfiles)
                   8679: 
                   8680: =item *
                   8681: 
                   8682: removeuserfile(): removes a file that exists in userfiles
                   8683: 
                   8684:   Args:
                   8685:    docuname: username or courseid of destination for the file
                   8686:    docudom: domain of user/course of destination for the file
                   8687:    fname: filname to delete (including any subdirs under userfiles)
                   8688: 
                   8689: =item *
                   8690: 
                   8691: removeuploadedurl(): convience function for removeuserfile()
                   8692: 
                   8693:   Args:
                   8694:    url:  a full /uploaded/... url to delete
                   8695: 
1.747     albertel 8696: =item * 
                   8697: 
                   8698: get_portfile_permissions():
                   8699:   Args:
                   8700:     domain: domain of user or course contain the portfolio files
                   8701:     user: name of user or num of course contain the portfolio files
                   8702:   Returns:
                   8703:     hashref of a dump of the proper file_permissions.db
                   8704:    
                   8705: 
                   8706: =item * 
                   8707: 
                   8708: get_access_controls():
                   8709: 
                   8710: Args:
                   8711:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8712:   group: (optional) the group you want the files associated with
                   8713:   file: (optional) the file you want access info on
                   8714: 
                   8715: Returns:
1.749     raeburn  8716:     a hash (keys are file names) of hashes containing
                   8717:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8718:         values are XML containing access control settings (see below) 
1.747     albertel 8719: 
                   8720: Internal notes:
                   8721: 
1.749     raeburn  8722:  access controls are stored in file_permissions.db as key=value pairs.
                   8723:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8724:         where scope -> public,guest,course,group,domains or users.
                   8725:               end -> UNIX time for end of access (0 -> no end date)
                   8726:               start -> UNIX time for start of access
                   8727: 
                   8728:     value -> XML description of access control
                   8729:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8730:             <start></start>
                   8731:             <end></end>
                   8732: 
                   8733:             <password></password>  for scope type = guest
                   8734: 
                   8735:             <domain></domain>     for scope type = course or group
                   8736:             <number></number>
                   8737:             <roles id="">
                   8738:              <role></role>
                   8739:              <access></access>
                   8740:              <section></section>
                   8741:              <group></group>
                   8742:             </roles>
                   8743: 
                   8744:             <dom></dom>         for scope type = domains
                   8745: 
                   8746:             <users>             for scope type = users
                   8747:              <user>
                   8748:               <uname></uname>
                   8749:               <udom></udom>
                   8750:              </user>
                   8751:             </users>
                   8752:            </scope> 
                   8753:               
                   8754:  Access data is also aggregated for each file in an additional key=value pair:
                   8755:  key -> path to file/file_name\0accesscontrol 
                   8756:  value -> reference to hash
                   8757:           hash contains key = value pairs
                   8758:           where key = uniqueID:scope_end_start
                   8759:                 value = UNIX time record was last updated
                   8760: 
                   8761:           Used to improve speed of look-ups of access controls for each file.  
                   8762:  
                   8763:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8764: 
                   8765: modify_access_controls():
                   8766: 
                   8767: Modifies access controls for a portfolio file
                   8768: Args
                   8769: 1. file name
                   8770: 2. reference to hash of required changes,
                   8771: 3. domain
                   8772: 4. username
                   8773:   where domain,username are the domain of the portfolio owner 
                   8774:   (either a user or a course) 
                   8775: 
                   8776: Returns:
                   8777: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8778: 2. result of deletions ('ok' or 'error', with error message).
                   8779: 3. reference to hash of any new or updated access controls.
                   8780: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8781:    key = integer (inbound ID)
                   8782:    value = uniqueID  
1.747     albertel 8783: 
1.608     albertel 8784: =back
                   8785: 
1.243     albertel 8786: =head2 HTTP Helper Routines
                   8787: 
                   8788: =over 4
                   8789: 
1.191     harris41 8790: =item *
                   8791: 
                   8792: escape() : unpack non-word characters into CGI-compatible hex codes
                   8793: 
                   8794: =item *
                   8795: 
                   8796: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8797: 
1.243     albertel 8798: =back
                   8799: 
                   8800: =head1 PRIVATE SUBROUTINES
                   8801: 
                   8802: =head2 Underlying communication routines (Shouldn't call)
                   8803: 
                   8804: =over 4
                   8805: 
                   8806: =item *
                   8807: 
                   8808: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8809: 
                   8810: =item *
                   8811: 
                   8812: reply() : uses subreply to send a message to remote machine, logs all failures
                   8813: 
                   8814: =item *
                   8815: 
                   8816: critical() : passes a critical message to another server; if cannot
                   8817: get through then place message in connection buffer directory and
                   8818: returns con_delayed, if incapable of saving message, returns
                   8819: con_failed
                   8820: 
                   8821: =item *
                   8822: 
                   8823: reconlonc() : tries to reconnect lonc client processes.
                   8824: 
                   8825: =back
                   8826: 
                   8827: =head2 Resource Access Logging
                   8828: 
                   8829: =over 4
                   8830: 
                   8831: =item *
                   8832: 
                   8833: flushcourselogs() : flush (save) buffer logs and access logs
                   8834: 
                   8835: =item *
                   8836: 
                   8837: courselog($what) : save message for course in hash
                   8838: 
                   8839: =item *
                   8840: 
                   8841: courseacclog($what) : save message for course using &courselog().  Perform
                   8842: special processing for specific resource types (problems, exams, quizzes, etc).
                   8843: 
1.191     harris41 8844: =item *
                   8845: 
                   8846: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8847: as a PerlChildExitHandler
1.243     albertel 8848: 
                   8849: =back
                   8850: 
                   8851: =head2 Other
                   8852: 
                   8853: =over 4
                   8854: 
                   8855: =item *
                   8856: 
                   8857: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8858: 
                   8859: =back
                   8860: 
                   8861: =cut

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