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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.850   ! albertel    4: # $Id: lonnet.pm,v 1.849 2007/03/17 04:11:51 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.847     albertel   38: qw(%perlvar %badServerCache %spareid 
1.845     albertel   39:    %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.685     raeburn    42:    $tmpdir $_64bit %env);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.637     raeburn    47: use HTML::Parser;
1.88      www        48: use Fcntl qw(:flock);
1.557     albertel   49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   50: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   51: use Cache::Memcached;
1.676     albertel   52: use Digest::MD5;
1.790     albertel   53: use Math::Random;
1.807     albertel   54: use LONCAPA qw(:DEFAULT :match);
1.740     www        55: use LONCAPA::Configuration;
1.676     albertel   56: 
1.195     www        57: my $readit;
1.550     foxr       58: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   59: 
1.619     albertel   60: require Exporter;
                     61: 
                     62: our @ISA = qw (Exporter);
                     63: our @EXPORT = qw(%env);
                     64: 
1.449     matthew    65: =pod
                     66: 
                     67: =head1 Package Variables
                     68: 
                     69: These are largely undocumented, so if you decipher one please note it here.
                     70: 
                     71: =over 4
                     72: 
                     73: =item $processmarker
                     74: 
                     75: Contains the time this process was started and this servers host id.
                     76: 
                     77: =item $dumpcount
                     78: 
                     79: Counts the number of times a message log flush has been attempted (regardless
                     80: of success) by this process.  Used as part of the filename when messages are
                     81: delayed.
                     82: 
                     83: =back
                     84: 
                     85: =cut
                     86: 
                     87: 
1.1       albertel   88: # --------------------------------------------------------------------- Logging
1.729     www        89: {
                     90:     my $logid;
                     91:     sub instructor_log {
                     92: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     93: 	$logid++;
                     94: 	my $id=time().'00000'.$$.'00000'.$logid;
                     95: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        96: 				    { $id => {
                     97: 					'exe_uname' => $env{'user.name'},
                     98: 					'exe_udom'  => $env{'user.domain'},
                     99: 					'exe_time'  => time(),
                    100: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    101: 					'delflag'   => $delflag,
                    102: 					'logentry'  => $storehash,
                    103: 					'uname'     => $uname,
                    104: 					'udom'      => $udom,
                    105: 				    }
                    106: 				  },
1.729     www       107: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    108: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    109: 				    );
                    110:     }
                    111: }
1.1       albertel  112: 
1.163     harris41  113: sub logtouch {
                    114:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  115:     unless (-e "$execdir/logs/lonnet.log") {	
                    116: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  117: 	close $fh;
                    118:     }
                    119:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    120:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    121: }
                    122: 
1.1       albertel  123: sub logthis {
                    124:     my $message=shift;
                    125:     my $execdir=$perlvar{'lonDaemons'};
                    126:     my $now=time;
                    127:     my $local=localtime($now);
1.448     albertel  128:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    129: 	print $fh "$local ($$): $message\n";
                    130: 	close($fh);
                    131:     }
1.1       albertel  132:     return 1;
                    133: }
                    134: 
                    135: sub logperm {
                    136:     my $message=shift;
                    137:     my $execdir=$perlvar{'lonDaemons'};
                    138:     my $now=time;
                    139:     my $local=localtime($now);
1.448     albertel  140:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    141: 	print $fh "$now:$message:$local\n";
                    142: 	close($fh);
                    143:     }
1.1       albertel  144:     return 1;
                    145: }
                    146: 
1.850   ! albertel  147: sub create_connection {
        !           148:     my ($server) = @_;
        !           149:     my $client=IO::Socket::UNIX->new(Peer    =>"/home/httpd/sockets/common",
        !           150: 				     Type    => SOCK_STREAM,
        !           151: 				     Timeout => 10);
        !           152:     return 0 if (!$client);
        !           153:     print $client ("$server\n");
        !           154:     my $result = <$client>;
        !           155:     chomp($result);
        !           156:     return 1 if ($result eq 'done');
        !           157:     return 0;
        !           158: }
        !           159: 
        !           160: 
1.1       albertel  161: # -------------------------------------------------- Non-critical communication
                    162: sub subreply {
                    163:     my ($cmd,$server)=@_;
1.838     albertel  164:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      165:     #
                    166:     #  With loncnew process trimming, there's a timing hole between lonc server
                    167:     #  process exit and the master server picking up the listen on the AF_UNIX
                    168:     #  socket.  In that time interval, a lock file will exist:
                    169: 
                    170:     my $lockfile=$peerfile.".lock";
                    171:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    172: 	sleep(1);
                    173:     }
                    174:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      175:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      176:     #
1.550     foxr      177:     #   We'll give the connection a few tries before abandoning it.  If
                    178:     #   connection is not possible, we'll con_lost back to the client.
                    179:     #   
                    180:     my $client;
                    181:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    182: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    183: 				      Type    => SOCK_STREAM,
                    184: 				      Timeout => 10);
                    185: 	if($client) {
                    186: 	    last;		# Connected!
1.850   ! albertel  187: 	} else {
        !           188: 	    &create_connection(&hostname($server));
1.550     foxr      189: 	}
1.850   ! albertel  190:         sleep(1);		# Try again later if failed connection.
1.550     foxr      191:     }
                    192:     my $answer;
                    193:     if ($client) {
1.704     albertel  194: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      195: 	$answer=<$client>;
                    196: 	if (!$answer) { $answer="con_lost"; }
                    197: 	chomp($answer);
                    198:     } else {
                    199: 	$answer = 'con_lost';	# Failed connection.
                    200:     }
1.1       albertel  201:     return $answer;
                    202: }
                    203: 
                    204: sub reply {
                    205:     my ($cmd,$server)=@_;
1.838     albertel  206:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  207:     my $answer=subreply($cmd,$server);
1.65      www       208:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  209:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       210:                 " $cmd to $server returned $answer</font>");
                    211:     }
1.1       albertel  212:     return $answer;
                    213: }
                    214: 
                    215: # ----------------------------------------------------------- Send USR1 to lonc
                    216: 
                    217: sub reconlonc {
1.836     www       218:     &logthis("Trying to reconnect lonc");
1.1       albertel  219:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  220:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  221: 	my $loncpid=<$fh>;
                    222:         chomp($loncpid);
                    223:         if (kill 0 => $loncpid) {
                    224: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    225:             kill USR1 => $loncpid;
                    226:             sleep 1;
1.836     www       227:          } else {
1.12      www       228: 	    &logthis(
1.672     albertel  229:                "<font color=\"blue\">WARNING:".
1.12      www       230:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  231:         }
                    232:     } else {
1.836     www       233: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  234:     }
                    235: }
                    236: 
                    237: # ------------------------------------------------------ Critical communication
1.12      www       238: 
1.1       albertel  239: sub critical {
                    240:     my ($cmd,$server)=@_;
1.838     albertel  241:     unless (&hostname($server)) {
1.672     albertel  242:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       243:                " Critical message to unknown server ($server)</font>");
                    244:         return 'no_such_host';
                    245:     }
1.1       albertel  246:     my $answer=reply($cmd,$server);
                    247:     if ($answer eq 'con_lost') {
                    248: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  249: 	my $answer=reply($cmd,$server);
1.1       albertel  250:         if ($answer eq 'con_lost') {
                    251:             my $now=time;
                    252:             my $middlename=$cmd;
1.5       www       253:             $middlename=substr($middlename,0,16);
1.1       albertel  254:             $middlename=~s/\W//g;
                    255:             my $dfilename=
1.305     www       256:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    257:             $dumpcount++;
1.1       albertel  258:             {
1.448     albertel  259: 		my $dfh;
                    260: 		if (open($dfh,">$dfilename")) {
                    261: 		    print $dfh "$cmd\n"; 
                    262: 		    close($dfh);
                    263: 		}
1.1       albertel  264:             }
                    265:             sleep 2;
                    266:             my $wcmd='';
                    267:             {
1.448     albertel  268: 		my $dfh;
                    269: 		if (open($dfh,"<$dfilename")) {
                    270: 		    $wcmd=<$dfh>; 
                    271: 		    close($dfh);
                    272: 		}
1.1       albertel  273:             }
                    274:             chomp($wcmd);
1.7       www       275:             if ($wcmd eq $cmd) {
1.672     albertel  276: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       277:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  278:                 &logperm("D:$server:$cmd");
                    279: 	        return 'con_delayed';
                    280:             } else {
1.672     albertel  281:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       282:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  283:                 &logperm("F:$server:$cmd");
                    284:                 return 'con_failed';
                    285:             }
                    286:         }
                    287:     }
                    288:     return $answer;
1.405     albertel  289: }
                    290: 
1.755     albertel  291: # ------------------------------------------- check if return value is an error
                    292: 
                    293: sub error {
                    294:     my ($result) = @_;
1.756     albertel  295:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  296: 	if ($2 == 2) { return undef; }
                    297: 	return $1;
                    298:     }
                    299:     return undef;
                    300: }
                    301: 
1.783     albertel  302: sub convert_and_load_session_env {
                    303:     my ($lonidsdir,$handle)=@_;
                    304:     my @profile;
                    305:     {
                    306: 	open(my $idf,"$lonidsdir/$handle.id");
                    307: 	flock($idf,LOCK_SH);
                    308: 	@profile=<$idf>;
                    309: 	close($idf);
                    310:     }
                    311:     my %temp_env;
                    312:     foreach my $line (@profile) {
1.786     albertel  313: 	if ($line !~ m/=/) {
                    314: 	    return 0;
                    315: 	}
1.783     albertel  316: 	chomp($line);
                    317: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    318: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    319:     }
                    320:     unlink("$lonidsdir/$handle.id");
                    321:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    322: 	    0640)) {
                    323: 	%disk_env = %temp_env;
                    324: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    325: 	untie(%disk_env);
                    326:     }
1.786     albertel  327:     return 1;
1.783     albertel  328: }
                    329: 
1.374     www       330: # ------------------------------------------- Transfer profile into environment
1.780     albertel  331: my $env_loaded;
                    332: sub transfer_profile_to_env {
1.788     albertel  333:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    334:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       335: 
1.720     albertel  336:     if (!defined($lonidsdir)) {
                    337: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    338:     }
                    339:     if (!defined($handle)) {
                    340:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    341:     }
                    342: 
1.786     albertel  343:     my $convert;
                    344:     {
                    345:     	open(my $idf,"$lonidsdir/$handle.id");
                    346: 	flock($idf,LOCK_SH);
                    347: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    348: 		&GDBM_READER(),0640)) {
                    349: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    350: 	    untie(%disk_env);
                    351: 	} else {
                    352: 	    $convert = 1;
                    353: 	}
                    354:     }
                    355:     if ($convert) {
                    356: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    357: 	    &logthis("Failed to load session, or convert session.");
                    358: 	}
1.374     www       359:     }
1.783     albertel  360: 
1.786     albertel  361:     my %remove;
1.783     albertel  362:     while ( my $envname = each(%env) ) {
1.433     matthew   363:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    364:             if ($time < time-300) {
1.783     albertel  365:                 $remove{$key}++;
1.433     matthew   366:             }
                    367:         }
                    368:     }
1.783     albertel  369: 
1.619     albertel  370:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  371:     $env_loaded=1;
1.783     albertel  372:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   373:         &delenv($expired_key);
1.374     www       374:     }
1.1       albertel  375: }
                    376: 
1.830     albertel  377: sub timed_flock {
                    378:     my ($file,$lock_type) = @_;
                    379:     my $failed=0;
                    380:     eval {
                    381: 	local $SIG{__DIE__}='DEFAULT';
                    382: 	local $SIG{ALRM}=sub {
                    383: 	    $failed=1;
                    384: 	    die("failed lock");
                    385: 	};
                    386: 	alarm(13);
                    387: 	flock($file,$lock_type);
                    388: 	alarm(0);
                    389:     };
                    390:     if ($failed) {
                    391: 	return undef;
                    392:     } else {
                    393: 	return 1;
                    394:     }
                    395: }
                    396: 
1.5       www       397: # ---------------------------------------------------------- Append Environment
                    398: 
                    399: sub appenv {
1.6       www       400:     my %newenv=@_;
1.692     albertel  401:     foreach my $key (keys(%newenv)) {
                    402: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  403:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  404:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       405:                 .'</font>');
1.692     albertel  406: 	    delete($newenv{$key});
1.35      www       407:         } else {
1.692     albertel  408:             $env{$key}=$newenv{$key};
1.35      www       409:         }
1.191     harris41  410:     }
1.830     albertel  411:     open(my $env_file,$env{'user.environment'});
                    412:     if (&timed_flock($env_file,LOCK_EX)
                    413: 	&&
                    414: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    415: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  416: 	while (my ($key,$value) = each(%newenv)) {
                    417: 	    $disk_env{$key} = $value;
1.448     albertel  418: 	}
1.783     albertel  419: 	untie(%disk_env);
1.56      www       420:     }
                    421:     return 'ok';
                    422: }
                    423: # ----------------------------------------------------- Delete from Environment
                    424: 
                    425: sub delenv {
                    426:     my $delthis=shift;
                    427:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  428:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       429:                 "Attempt to delete from environment ".$delthis);
                    430:         return 'error';
                    431:     }
1.830     albertel  432:     open(my $env_file,$env{'user.environment'});
                    433:     if (&timed_flock($env_file,LOCK_EX)
                    434: 	&&
                    435: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    436: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  437: 	foreach my $key (keys(%disk_env)) {
                    438: 	    if ($key=~/^$delthis/) { 
1.619     albertel  439:                 delete($env{$key});
1.783     albertel  440:                 delete($disk_env{$key});
1.473     matthew   441:             }
1.448     albertel  442: 	}
1.783     albertel  443: 	untie(%disk_env);
1.5       www       444:     }
                    445:     return 'ok';
1.369     albertel  446: }
                    447: 
1.790     albertel  448: sub get_env_multiple {
                    449:     my ($name) = @_;
                    450:     my @values;
                    451:     if (defined($env{$name})) {
                    452:         # exists is it an array
                    453:         if (ref($env{$name})) {
                    454:             @values=@{ $env{$name} };
                    455:         } else {
                    456:             $values[0]=$env{$name};
                    457:         }
                    458:     }
                    459:     return(@values);
                    460: }
                    461: 
1.369     albertel  462: # ------------------------------------------ Find out current server userload
                    463: # there is a copy in lond
                    464: sub userload {
                    465:     my $numusers=0;
                    466:     {
                    467: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    468: 	my $filename;
                    469: 	my $curtime=time;
                    470: 	while ($filename=readdir(LONIDS)) {
                    471: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  472: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  473: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  474: 	}
                    475: 	closedir(LONIDS);
                    476:     }
                    477:     my $userloadpercent=0;
                    478:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    479:     if ($maxuserload) {
1.371     albertel  480: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  481:     }
1.372     albertel  482:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  483:     return $userloadpercent;
1.283     www       484: }
                    485: 
                    486: # ------------------------------------------ Fight off request when overloaded
                    487: 
                    488: sub overloaderror {
                    489:     my ($r,$checkserver)=@_;
                    490:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    491:     my $loadavg;
                    492:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  493:        open(my $loadfile,'/proc/loadavg');
1.283     www       494:        $loadavg=<$loadfile>;
                    495:        $loadavg =~ s/\s.*//g;
1.285     matthew   496:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  497:        close($loadfile);
1.283     www       498:     } else {
                    499:        $loadavg=&reply('load',$checkserver);
                    500:     }
1.285     matthew   501:     my $overload=$loadavg-100;
1.283     www       502:     if ($overload>0) {
1.285     matthew   503: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       504:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       505:         return 413;
1.283     www       506:     }    
                    507:     return '';
1.5       www       508: }
1.1       albertel  509: 
                    510: # ------------------------------ Find server with least workload from spare.tab
1.11      www       511: 
1.1       albertel  512: sub spareserver {
1.670     albertel  513:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  514:     my $spare_server;
1.370     albertel  515:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  516:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    517:                                                      :  $userloadpercent;
                    518:     
                    519:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    520: 	($spare_server, $lowest_load) =
                    521: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    522:     }
                    523: 
                    524:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    525: 
                    526:     if (!$found_server) {
                    527: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    528: 	    ($spare_server, $lowest_load) =
                    529: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    530: 	}
                    531:     }
                    532: 
                    533:     if (!$want_server_name) {
1.838     albertel  534: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  535:     }
                    536:     return $spare_server;
                    537: }
                    538: 
                    539: sub compare_server_load {
                    540:     my ($try_server, $spare_server, $lowest_load) = @_;
                    541: 
                    542:     my $loadans     = &reply('load',    $try_server);
                    543:     my $userloadans = &reply('userload',$try_server);
                    544: 
                    545:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    546: 	next; #didn't get a number from the server
                    547:     }
                    548: 
                    549:     my $load;
                    550:     if ($loadans =~ /\d/) {
                    551: 	if ($userloadans =~ /\d/) {
                    552: 	    #both are numbers, pick the bigger one
                    553: 	    $load = ($loadans > $userloadans) ? $loadans 
                    554: 		                              : $userloadans;
1.411     albertel  555: 	} else {
1.784     albertel  556: 	    $load = $loadans;
1.411     albertel  557: 	}
1.784     albertel  558:     } else {
                    559: 	$load = $userloadans;
                    560:     }
                    561: 
                    562:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    563: 	$spare_server = $try_server;
                    564: 	$lowest_load  = $load;
1.370     albertel  565:     }
1.784     albertel  566:     return ($spare_server,$lowest_load);
1.202     matthew   567: }
                    568: # --------------------------------------------- Try to change a user's password
                    569: 
                    570: sub changepass {
1.799     raeburn   571:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   572:     $currentpass = &escape($currentpass);
                    573:     $newpass     = &escape($newpass);
1.799     raeburn   574:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   575: 		       $server);
                    576:     if (! $answer) {
                    577: 	&logthis("No reply on password change request to $server ".
                    578: 		 "by $uname in domain $udom.");
                    579:     } elsif ($answer =~ "^ok") {
                    580:         &logthis("$uname in $udom successfully changed their password ".
                    581: 		 "on $server.");
                    582:     } elsif ($answer =~ "^pwchange_failure") {
                    583: 	&logthis("$uname in $udom was unable to change their password ".
                    584: 		 "on $server.  The action was blocked by either lcpasswd ".
                    585: 		 "or pwchange");
                    586:     } elsif ($answer =~ "^non_authorized") {
                    587:         &logthis("$uname in $udom did not get their password correct when ".
                    588: 		 "attempting to change it on $server.");
                    589:     } elsif ($answer =~ "^auth_mode_error") {
                    590:         &logthis("$uname in $udom attempted to change their password despite ".
                    591: 		 "not being locally or internally authenticated on $server.");
                    592:     } elsif ($answer =~ "^unknown_user") {
                    593:         &logthis("$uname in $udom attempted to change their password ".
                    594: 		 "on $server but were unable to because $server is not ".
                    595: 		 "their home server.");
                    596:     } elsif ($answer =~ "^refused") {
                    597: 	&logthis("$server refused to change $uname in $udom password because ".
                    598: 		 "it was sent an unencrypted request to change the password.");
                    599:     }
                    600:     return $answer;
1.1       albertel  601: }
                    602: 
1.169     harris41  603: # ----------------------- Try to determine user's current authentication scheme
                    604: 
                    605: sub queryauthenticate {
                    606:     my ($uname,$udom)=@_;
1.456     albertel  607:     my $uhome=&homeserver($uname,$udom);
                    608:     if (!$uhome) {
                    609: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    610: 	return 'no_host';
                    611:     }
                    612:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    613:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    614: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  615:     }
1.456     albertel  616:     return $answer;
1.169     harris41  617: }
                    618: 
1.1       albertel  619: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       620: 
1.1       albertel  621: sub authenticate {
                    622:     my ($uname,$upass,$udom)=@_;
1.807     albertel  623:     $upass=&escape($upass);
                    624:     $uname= &LONCAPA::clean_username($uname);
1.836     www       625:     my $uhome=&homeserver($uname,$udom,1);
                    626:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    627: # Maybe the machine was offline and only re-appeared again recently?
                    628:         &reconlonc();
                    629: # One more
                    630: 	my $uhome=&homeserver($uname,$udom,1);
                    631: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    632: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    633: 	}
1.471     albertel  634: 	return 'no_host';
1.1       albertel  635:     }
1.471     albertel  636:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    637:     if ($answer eq 'authorized') {
                    638: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    639: 	return $uhome; 
                    640:     }
                    641:     if ($answer eq 'non_authorized') {
                    642: 	&logthis("User $uname at $udom rejected by $uhome");
                    643: 	return 'no_host'; 
1.9       www       644:     }
1.471     albertel  645:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  646:     return 'no_host';
                    647: }
                    648: 
                    649: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       650: 
1.599     albertel  651: my %homecache;
1.1       albertel  652: sub homeserver {
1.230     stredwic  653:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  654:     my $index="$uname:$udom";
1.426     albertel  655: 
1.599     albertel  656:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  657: 
                    658:     my %servers = &get_servers($udom,'library');
                    659:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  660:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  661: 		 exists($badServerCache{$tryserver}));
1.841     albertel  662: 
                    663: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    664: 	if ($answer eq 'found') {
                    665: 	    delete($badServerCache{$tryserver}); 
                    666: 	    return $homecache{$index}=$tryserver;
                    667: 	} elsif ($answer eq 'no_host') {
                    668: 	    $badServerCache{$tryserver}=1;
                    669: 	}
1.1       albertel  670:     }    
                    671:     return 'no_host';
1.70      www       672: }
                    673: 
                    674: # ------------------------------------- Find the usernames behind a list of IDs
                    675: 
                    676: sub idget {
                    677:     my ($udom,@ids)=@_;
                    678:     my %returnhash=();
                    679:     
1.841     albertel  680:     my %servers = &get_servers($udom,'library');
                    681:     foreach my $tryserver (keys(%servers)) {
                    682: 	my $idlist=join('&',@ids);
                    683: 	$idlist=~tr/A-Z/a-z/; 
                    684: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    685: 	my @answer=();
                    686: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    687: 	    @answer=split(/\&/,$reply);
                    688: 	}                    ;
                    689: 	my $i;
                    690: 	for ($i=0;$i<=$#ids;$i++) {
                    691: 	    if ($answer[$i]) {
                    692: 		$returnhash{$ids[$i]}=$answer[$i];
                    693: 	    } 
                    694: 	}
                    695:     } 
1.70      www       696:     return %returnhash;
                    697: }
                    698: 
                    699: # ------------------------------------- Find the IDs behind a list of usernames
                    700: 
                    701: sub idrget {
                    702:     my ($udom,@unames)=@_;
                    703:     my %returnhash=();
1.800     albertel  704:     foreach my $uname (@unames) {
                    705:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  706:     }
1.70      www       707:     return %returnhash;
                    708: }
                    709: 
                    710: # ------------------------------- Store away a list of names and associated IDs
                    711: 
                    712: sub idput {
                    713:     my ($udom,%ids)=@_;
                    714:     my %servers=();
1.800     albertel  715:     foreach my $uname (keys(%ids)) {
                    716: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    717:         my $uhom=&homeserver($uname,$udom);
1.70      www       718:         if ($uhom ne 'no_host') {
1.800     albertel  719:             my $id=&escape($ids{$uname});
1.70      www       720:             $id=~tr/A-Z/a-z/;
1.800     albertel  721:             my $esc_unam=&escape($uname);
1.70      www       722: 	    if ($servers{$uhom}) {
1.800     albertel  723: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       724:             } else {
1.800     albertel  725:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       726:             }
                    727:         }
1.191     harris41  728:     }
1.800     albertel  729:     foreach my $server (keys(%servers)) {
                    730:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  731:     }
1.344     www       732: }
                    733: 
1.806     raeburn   734: # ------------------------------------------- get items from domain db files   
                    735: 
                    736: sub get_dom {
                    737:     my ($namespace,$storearr,$udom)=@_;
                    738:     my $items='';
                    739:     foreach my $item (@$storearr) {
                    740:         $items.=&escape($item).'&';
                    741:     }
                    742:     $items=~s/\&$//;
                    743:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  744:     if (defined(&domain($udom,'primary'))) {
                    745:         my $uhome=&domain($udom,'primary');
1.806     raeburn   746:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    747:         my @pairs=split(/\&/,$rep);
                    748:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    749:             return @pairs;
                    750:         }
                    751:         my %returnhash=();
                    752:         my $i=0;
                    753:         foreach my $item (@$storearr) {
                    754:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    755:             $i++;
                    756:         }
                    757:         return %returnhash;
                    758:     } else {
                    759:         &logthis("get_dom failed - no primary domain server for $udom");
                    760:     }
                    761: }
                    762: 
                    763: # -------------------------------------------- put items in domain db files 
                    764: 
                    765: sub put_dom {
                    766:     my ($namespace,$storehash,$udom)=@_;
                    767:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  768:     if (defined(&domain($udom,'primary'))) {
                    769:         my $uhome=&domain($udom,'primary');
1.806     raeburn   770:         my $items='';
                    771:         foreach my $item (keys(%$storehash)) {
                    772:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    773:         }
                    774:         $items=~s/\&$//;
                    775:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    776:     } else {
                    777:         &logthis("put_dom failed - no primary domain server for $udom");
                    778:     }
                    779: }
                    780: 
1.837     raeburn   781: sub retrieve_inst_usertypes {
                    782:     my ($udom) = @_;
                    783:     my (%returnhash,@order);
1.846     albertel  784:     if (defined(&domain($udom,'primary'))) {
                    785:         my $uhome=&domain($udom,'primary');
1.837     raeburn   786:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    787:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    788:         my @pairs=split(/\&/,$hashitems);
                    789:         foreach my $item (@pairs) {
                    790:             my ($key,$value)=split(/=/,$item,2);
                    791:             $key = &unescape($key);
                    792:             next if ($key =~ /^error: 2 /);
                    793:             $returnhash{$key}=&thaw_unescape($value);
                    794:         }
                    795:         my @esc_order = split(/\&/,$orderitems);
                    796:         foreach my $item (@esc_order) {
                    797:             push(@order,&unescape($item));
                    798:         }
                    799:     } else {
                    800:         &logthis("get_dom failed - no primary domain server for $udom");
                    801:     }
                    802:     return (\%returnhash,\@order);
                    803: }
                    804: 
1.344     www       805: # --------------------------------------------------- Assign a key to a student
                    806: 
                    807: sub assign_access_key {
1.364     www       808: #
                    809: # a valid key looks like uname:udom#comments
                    810: # comments are being appended
                    811: #
1.498     www       812:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    813:     $kdom=
1.620     albertel  814:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       815:     $knum=
1.620     albertel  816:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       817:     $cdom=
1.620     albertel  818:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       819:     $cnum=
1.620     albertel  820:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    821:     $udom=$env{'user.name'} unless (defined($udom));
                    822:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       823:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       824:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  825:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       826:                                                   # assigned to this person
                    827:                                                   # - this should not happen,
1.345     www       828:                                                   # unless something went wrong
                    829:                                                   # the first time around
                    830: # ready to assign
1.364     www       831:         $logentry=$1.'; '.$logentry;
1.496     www       832:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       833:                                                  $kdom,$knum) eq 'ok') {
1.345     www       834: # key now belongs to user
1.346     www       835: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       836:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    837:                 &appenv('environment.'.$envkey => $ckey);
                    838:                 return 'ok';
                    839:             } else {
                    840:                 return 
                    841:   'error: Count not permanently assign key, will need to be re-entered later.';
                    842: 	    }
                    843:         } else {
                    844:             return 'error: Could not assign key, try again later.';
                    845:         }
1.364     www       846:     } elsif (!$existing{$ckey}) {
1.345     www       847: # the key does not exist
                    848: 	return 'error: The key does not exist';
                    849:     } else {
                    850: # the key is somebody else's
                    851: 	return 'error: The key is already in use';
                    852:     }
1.344     www       853: }
                    854: 
1.364     www       855: # ------------------------------------------ put an additional comment on a key
                    856: 
                    857: sub comment_access_key {
                    858: #
                    859: # a valid key looks like uname:udom#comments
                    860: # comments are being appended
                    861: #
                    862:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    863:     $cdom=
1.620     albertel  864:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       865:     $cnum=
1.620     albertel  866:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       867:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    868:     if ($existing{$ckey}) {
                    869:         $existing{$ckey}.='; '.$logentry;
                    870: # ready to assign
1.367     www       871:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       872:                                                  $cdom,$cnum) eq 'ok') {
                    873: 	    return 'ok';
                    874:         } else {
                    875: 	    return 'error: Count not store comment.';
                    876:         }
                    877:     } else {
                    878: # the key does not exist
                    879: 	return 'error: The key does not exist';
                    880:     }
                    881: }
                    882: 
1.344     www       883: # ------------------------------------------------------ Generate a set of keys
                    884: 
                    885: sub generate_access_keys {
1.364     www       886:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       887:     $cdom=
1.620     albertel  888:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       889:     $cnum=
1.620     albertel  890:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       891:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       892:     unless (($cdom) && ($cnum)) { return 0; }
                    893:     if ($number>10000) { return 0; }
                    894:     sleep(2); # make sure don't get same seed twice
                    895:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    896:     my $total=0;
                    897:     for (my $i=1;$i<=$number;$i++) {
                    898:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    899:                   sprintf("%lx",int(100000*rand)).'-'.
                    900:                   sprintf("%lx",int(100000*rand));
                    901:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    902:        $newkey=~s/0/h/g; # and also 0 and O
                    903:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    904:        if ($existing{$newkey}) {
                    905:            $i--;
                    906:        } else {
1.364     www       907: 	  if (&put('accesskeys',
                    908:               { $newkey => '# generated '.localtime().
1.620     albertel  909:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       910:                            '; '.$logentry },
                    911: 		   $cdom,$cnum) eq 'ok') {
1.344     www       912:               $total++;
                    913: 	  }
                    914:        }
                    915:     }
1.620     albertel  916:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       917:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    918:     return $total;
                    919: }
                    920: 
                    921: # ------------------------------------------------------- Validate an accesskey
                    922: 
                    923: sub validate_access_key {
                    924:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    925:     $cdom=
1.620     albertel  926:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       927:     $cnum=
1.620     albertel  928:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    929:     $udom=$env{'user.domain'} unless (defined($udom));
                    930:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       931:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  932:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       933: }
                    934: 
                    935: # ------------------------------------- Find the section of student in a course
1.652     albertel  936: sub devalidate_getsection_cache {
                    937:     my ($udom,$unam,$courseid)=@_;
                    938:     my $hashid="$udom:$unam:$courseid";
                    939:     &devalidate_cache_new('getsection',$hashid);
                    940: }
1.298     matthew   941: 
1.815     albertel  942: sub courseid_to_courseurl {
                    943:     my ($courseid) = @_;
                    944:     #already url style courseid
                    945:     return $courseid if ($courseid =~ m{^/});
                    946: 
                    947:     if (exists($env{'course.'.$courseid.'.num'})) {
                    948: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    949: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    950: 	return "/$cdom/$cnum";
                    951:     }
                    952: 
                    953:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    954:     if (exists($courseinfo{'num'})) {
                    955: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    956:     }
                    957: 
                    958:     return undef;
                    959: }
                    960: 
1.298     matthew   961: sub getsection {
                    962:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  963:     my $cachetime=1800;
1.551     albertel  964: 
                    965:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  966:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  967:     if (defined($cached)) { return $result; }
                    968: 
1.298     matthew   969:     my %Pending; 
                    970:     my %Expired;
                    971:     #
                    972:     # Each role can either have not started yet (pending), be active, 
                    973:     #    or have expired.
                    974:     #
                    975:     # If there is an active role, we are done.
                    976:     #
                    977:     # If there is more than one role which has not started yet, 
                    978:     #     choose the one which will start sooner
                    979:     # If there is one role which has not started yet, return it.
                    980:     #
                    981:     # If there is more than one expired role, choose the one which ended last.
                    982:     # If there is a role which has expired, return it.
                    983:     #
1.815     albertel  984:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   985:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    986:     foreach my $key (keys(%roleshash)) {
1.479     albertel  987:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   988:         my $section=$1;
                    989:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   990:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   991:         my $now=time;
1.548     albertel  992:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   993:             $Expired{$end}=$section;
                    994:             next;
                    995:         }
1.548     albertel  996:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   997:             $Pending{$start}=$section;
                    998:             next;
                    999:         }
1.599     albertel 1000:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1001:     }
                   1002:     #
                   1003:     # Presumedly there will be few matching roles from the above
                   1004:     # loop and the sorting time will be negligible.
                   1005:     if (scalar(keys(%Pending))) {
                   1006:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1007:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1008:     } 
                   1009:     if (scalar(keys(%Expired))) {
                   1010:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1011:         my $time = pop(@sorted);
1.599     albertel 1012:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1013:     }
1.599     albertel 1014:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1015: }
1.70      www      1016: 
1.599     albertel 1017: sub save_cache {
                   1018:     &purge_remembered();
1.722     albertel 1019:     #&Apache::loncommon::validate_page();
1.620     albertel 1020:     undef(%env);
1.780     albertel 1021:     undef($env_loaded);
1.599     albertel 1022: }
1.452     albertel 1023: 
1.599     albertel 1024: my $to_remember=-1;
                   1025: my %remembered;
                   1026: my %accessed;
                   1027: my $kicks=0;
                   1028: my $hits=0;
1.849     albertel 1029: sub make_key {
                   1030:     my ($name,$id) = @_;
                   1031:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
                   1032:     return &escape($name.':'.$id);
                   1033: }
                   1034: 
1.599     albertel 1035: sub devalidate_cache_new {
                   1036:     my ($name,$id,$debug) = @_;
                   1037:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1038:     $id=&make_key($name,$id);
1.599     albertel 1039:     $memcache->delete($id);
                   1040:     delete($remembered{$id});
                   1041:     delete($accessed{$id});
                   1042: }
                   1043: 
                   1044: sub is_cached_new {
                   1045:     my ($name,$id,$debug) = @_;
1.849     albertel 1046:     $id=&make_key($name,$id);
1.599     albertel 1047:     if (exists($remembered{$id})) {
                   1048: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1049: 	$accessed{$id}=[&gettimeofday()];
                   1050: 	$hits++;
                   1051: 	return ($remembered{$id},1);
                   1052:     }
                   1053:     my $value = $memcache->get($id);
                   1054:     if (!(defined($value))) {
                   1055: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1056: 	return (undef,undef);
1.416     albertel 1057:     }
1.599     albertel 1058:     if ($value eq '__undef__') {
                   1059: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1060: 	$value=undef;
                   1061:     }
                   1062:     &make_room($id,$value,$debug);
                   1063:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1064:     return ($value,1);
                   1065: }
                   1066: 
                   1067: sub do_cache_new {
                   1068:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1069:     $id=&make_key($name,$id);
1.599     albertel 1070:     my $setvalue=$value;
                   1071:     if (!defined($setvalue)) {
                   1072: 	$setvalue='__undef__';
                   1073:     }
1.623     albertel 1074:     if (!defined($time) ) {
                   1075: 	$time=600;
                   1076:     }
1.599     albertel 1077:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1078:     $memcache->set($id,$setvalue,$time);
                   1079:     # need to make a copy of $value
                   1080:     #&make_room($id,$value,$debug);
1.599     albertel 1081:     return $value;
                   1082: }
                   1083: 
                   1084: sub make_room {
                   1085:     my ($id,$value,$debug)=@_;
                   1086:     $remembered{$id}=$value;
                   1087:     if ($to_remember<0) { return; }
                   1088:     $accessed{$id}=[&gettimeofday()];
                   1089:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1090:     my $to_kick;
                   1091:     my $max_time=0;
                   1092:     foreach my $other (keys(%accessed)) {
                   1093: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1094: 	    $to_kick=$other;
                   1095: 	    $max_time=&tv_interval($accessed{$other});
                   1096: 	}
                   1097:     }
                   1098:     delete($remembered{$to_kick});
                   1099:     delete($accessed{$to_kick});
                   1100:     $kicks++;
                   1101:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1102:     return;
                   1103: }
                   1104: 
1.599     albertel 1105: sub purge_remembered {
1.604     albertel 1106:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1107:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1108:     undef(%remembered);
                   1109:     undef(%accessed);
1.428     albertel 1110: }
1.70      www      1111: # ------------------------------------- Read an entry from a user's environment
                   1112: 
                   1113: sub userenvironment {
                   1114:     my ($udom,$unam,@what)=@_;
                   1115:     my %returnhash=();
                   1116:     my @answer=split(/\&/,
                   1117:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1118:                       &homeserver($unam,$udom)));
                   1119:     my $i;
                   1120:     for ($i=0;$i<=$#what;$i++) {
                   1121: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1122:     }
                   1123:     return %returnhash;
1.1       albertel 1124: }
                   1125: 
1.617     albertel 1126: # ---------------------------------------------------------- Get a studentphoto
                   1127: sub studentphoto {
                   1128:     my ($udom,$unam,$ext) = @_;
                   1129:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1130:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1131:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1132:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1133:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1134:             } else {
                   1135:                 my ($result,$perm_reqd)=
1.707     albertel 1136: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1137:                 if ($result eq 'ok') {
                   1138:                     if (!($perm_reqd eq 'yes')) {
                   1139:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1140:                     }
                   1141:                 }
                   1142:             }
                   1143:         }
                   1144:     } else {
                   1145:         my ($result,$perm_reqd) = 
1.707     albertel 1146: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1147:         if ($result eq 'ok') {
                   1148:             if (!($perm_reqd eq 'yes')) {
                   1149:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1150:             }
                   1151:         }
                   1152:     }
                   1153:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1154: }
                   1155: 
                   1156: sub retrievestudentphoto {
                   1157:     my ($udom,$unam,$ext,$type) = @_;
                   1158:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1159:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1160:     if ($ret eq 'ok') {
                   1161:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1162:         if ($type eq 'thumbnail') {
                   1163:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1164:         }
                   1165:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1166:         return $tokenurl;
                   1167:     } else {
                   1168:         if ($type eq 'thumbnail') {
                   1169:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1170:         } else { 
                   1171:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1172:         }
1.617     albertel 1173:     }
                   1174: }
                   1175: 
1.263     www      1176: # -------------------------------------------------------------------- New chat
                   1177: 
                   1178: sub chatsend {
1.724     raeburn  1179:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1180:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1181:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1182:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1183:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1184: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1185: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1186: }
                   1187: 
                   1188: # ------------------------------------------ Find current version of a resource
                   1189: 
                   1190: sub getversion {
                   1191:     my $fname=&clutter(shift);
                   1192:     unless ($fname=~/^\/res\//) { return -1; }
                   1193:     return &currentversion(&filelocation('',$fname));
                   1194: }
                   1195: 
                   1196: sub currentversion {
                   1197:     my $fname=shift;
1.599     albertel 1198:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1199:     if (defined($cached)) { return $result; }
1.292     www      1200:     my $author=$fname;
                   1201:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1202:     my ($udom,$uname)=split(/\//,$author);
                   1203:     my $home=homeserver($uname,$udom);
                   1204:     if ($home eq 'no_host') { 
                   1205:         return -1; 
                   1206:     }
                   1207:     my $answer=reply("currentversion:$fname",$home);
                   1208:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1209: 	return -1;
                   1210:     }
1.599     albertel 1211:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1212: }
                   1213: 
1.1       albertel 1214: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1215: 
1.1       albertel 1216: sub subscribe {
                   1217:     my $fname=shift;
1.761     raeburn  1218:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1219:     $fname=~s/[\n\r]//g;
1.1       albertel 1220:     my $author=$fname;
                   1221:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1222:     my ($udom,$uname)=split(/\//,$author);
                   1223:     my $home=homeserver($uname,$udom);
1.335     albertel 1224:     if ($home eq 'no_host') {
                   1225:         return 'not_found';
1.1       albertel 1226:     }
                   1227:     my $answer=reply("sub:$fname",$home);
1.64      www      1228:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1229: 	$answer.=' by '.$home;
                   1230:     }
1.1       albertel 1231:     return $answer;
                   1232: }
                   1233:     
1.8       www      1234: # -------------------------------------------------------------- Replicate file
                   1235: 
                   1236: sub repcopy {
                   1237:     my $filename=shift;
1.23      www      1238:     $filename=~s/\/+/\//g;
1.607     raeburn  1239:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1240:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1241:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1242: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1243: 	return &repcopy_userfile($filename);
                   1244:     }
1.532     albertel 1245:     $filename=~s/[\n\r]//g;
1.8       www      1246:     my $transname="$filename.in.transfer";
1.828     www      1247: # FIXME: this should flock
1.607     raeburn  1248:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1249:     my $remoteurl=subscribe($filename);
1.64      www      1250:     if ($remoteurl =~ /^con_lost by/) {
                   1251: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1252:            return 'unavailable';
1.8       www      1253:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1254: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1255: 	   return 'not_found';
1.64      www      1256:     } elsif ($remoteurl =~ /^rejected by/) {
                   1257: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1258:            return 'forbidden';
1.20      www      1259:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1260:            return 'ok';
1.8       www      1261:     } else {
1.290     www      1262:         my $author=$filename;
                   1263:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1264:         my ($udom,$uname)=split(/\//,$author);
                   1265:         my $home=homeserver($uname,$udom);
                   1266:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1267:            my @parts=split(/\//,$filename);
                   1268:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1269:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1270:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1271: 	       return 'bad_request';
1.8       www      1272:            }
                   1273:            my $count;
                   1274:            for ($count=5;$count<$#parts;$count++) {
                   1275:                $path.="/$parts[$count]";
                   1276:                if ((-e $path)!=1) {
                   1277: 		   mkdir($path,0777);
                   1278:                }
                   1279:            }
                   1280:            my $ua=new LWP::UserAgent;
                   1281:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1282:            my $response=$ua->request($request,$transname);
                   1283:            if ($response->is_error()) {
                   1284: 	       unlink($transname);
                   1285:                my $message=$response->status_line;
1.672     albertel 1286:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1287:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1288:                return 'unavailable';
1.8       www      1289:            } else {
1.16      www      1290: 	       if ($remoteurl!~/\.meta$/) {
                   1291:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1292:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1293:                   if ($mresponse->is_error()) {
                   1294: 		      unlink($filename.'.meta');
                   1295:                       &logthis(
1.672     albertel 1296:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1297:                   }
                   1298: 	       }
1.8       www      1299:                rename($transname,$filename);
1.607     raeburn  1300:                return 'ok';
1.8       www      1301:            }
1.290     www      1302:        }
1.8       www      1303:     }
1.330     www      1304: }
                   1305: 
                   1306: # ------------------------------------------------ Get server side include body
                   1307: sub ssi_body {
1.381     albertel 1308:     my ($filelink,%form)=@_;
1.606     matthew  1309:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1310:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1311:     }
1.330     www      1312:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1313:                                      &ssi($filelink,%form));
1.778     albertel 1314:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1315:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1316:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1317:     return $output;
1.8       www      1318: }
                   1319: 
1.15      www      1320: # --------------------------------------------------------- Server Side Include
                   1321: 
1.782     albertel 1322: sub absolute_url {
                   1323:     my ($host_name) = @_;
                   1324:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1325:     if ($host_name eq '') {
                   1326: 	$host_name = $ENV{'SERVER_NAME'};
                   1327:     }
                   1328:     return $protocol.$host_name;
                   1329: }
                   1330: 
1.15      www      1331: sub ssi {
                   1332: 
1.23      www      1333:     my ($fn,%form)=@_;
1.15      www      1334: 
                   1335:     my $ua=new LWP::UserAgent;
1.23      www      1336:     
                   1337:     my $request;
1.711     albertel 1338: 
                   1339:     $form{'no_update_last_known'}=1;
                   1340: 
1.23      www      1341:     if (%form) {
1.782     albertel 1342:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1343:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1344:     } else {
1.782     albertel 1345:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1346:     }
                   1347: 
1.15      www      1348:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1349:     my $response=$ua->request($request);
                   1350: 
1.324     www      1351:     return $response->content;
                   1352: }
                   1353: 
                   1354: sub externalssi {
                   1355:     my ($url)=@_;
                   1356:     my $ua=new LWP::UserAgent;
                   1357:     my $request=new HTTP::Request('GET',$url);
                   1358:     my $response=$ua->request($request);
1.15      www      1359:     return $response->content;
                   1360: }
1.254     www      1361: 
1.492     albertel 1362: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1363: 
                   1364: sub allowuploaded {
                   1365:     my ($srcurl,$url)=@_;
                   1366:     $url=&clutter(&declutter($url));
                   1367:     my $dir=$url;
                   1368:     $dir=~s/\/[^\/]+$//;
                   1369:     my %httpref=();
                   1370:     my $httpurl=&hreflocation('',$url);
                   1371:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1372:     &Apache::lonnet::appenv(%httpref);
1.254     www      1373: }
1.477     raeburn  1374: 
1.478     albertel 1375: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1376: # input: action, courseID, current domain, intended
1.637     raeburn  1377: #        path to file, source of file, instruction to parse file for objects,
                   1378: #        ref to hash for embedded objects,
                   1379: #        ref to hash for codebase of java objects.
                   1380: #
1.485     raeburn  1381: # output: url to file (if action was uploaddoc), 
                   1382: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1383: #
1.478     albertel 1384: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1385: # course.
1.477     raeburn  1386: #
1.478     albertel 1387: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1388: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1389: #          course's home server.
1.477     raeburn  1390: #
1.478     albertel 1391: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1392: #          be copied from $source (current location) to 
                   1393: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1394: #         and will then be copied to
                   1395: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1396: #         course's home server.
1.485     raeburn  1397: #
1.481     raeburn  1398: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1399: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1400: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1401: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1402: #         in course's home server.
1.637     raeburn  1403: #
1.477     raeburn  1404: 
                   1405: sub process_coursefile {
1.638     albertel 1406:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1407:     my $fetchresult;
1.638     albertel 1408:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1409:     if ($action eq 'propagate') {
1.638     albertel 1410:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1411: 			     $home);
1.481     raeburn  1412:     } else {
1.477     raeburn  1413:         my $fpath = '';
                   1414:         my $fname = $file;
1.478     albertel 1415:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1416:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1417:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1418:         if ($action eq 'copy') {
                   1419:             if ($source eq '') {
                   1420:                 $fetchresult = 'no source file';
                   1421:                 return $fetchresult;
                   1422:             } else {
                   1423:                 my $destination = $filepath.'/'.$fname;
                   1424:                 rename($source,$destination);
                   1425:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1426:                                  $home);
1.481     raeburn  1427:             }
                   1428:         } elsif ($action eq 'uploaddoc') {
                   1429:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1430:             print $fh $env{'form.'.$source};
1.481     raeburn  1431:             close($fh);
1.637     raeburn  1432:             if ($parser eq 'parse') {
                   1433:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1434:                 unless ($parse_result eq 'ok') {
                   1435:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1436:                 }
                   1437:             }
1.477     raeburn  1438:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1439:                                  $home);
1.481     raeburn  1440:             if ($fetchresult eq 'ok') {
                   1441:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1442:             } else {
                   1443:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1444:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1445:                 return '/adm/notfound.html';
                   1446:             }
1.477     raeburn  1447:         }
                   1448:     }
1.485     raeburn  1449:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1450:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1451:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1452:     }
                   1453:     return $fetchresult;
                   1454: }
                   1455: 
1.637     raeburn  1456: sub build_filepath {
                   1457:     my ($fpath) = @_;
                   1458:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1459:     unless ($fpath eq '') {
                   1460:         my @parts=split('/',$fpath);
                   1461:         foreach my $part (@parts) {
                   1462:             $filepath.= '/'.$part;
                   1463:             if ((-e $filepath)!=1) {
                   1464:                 mkdir($filepath,0777);
                   1465:             }
                   1466:         }
                   1467:     }
                   1468:     return $filepath;
                   1469: }
                   1470: 
                   1471: sub store_edited_file {
1.638     albertel 1472:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1473:     my $file = $primary_url;
                   1474:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1475:     my $fpath = '';
                   1476:     my $fname = $file;
                   1477:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1478:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1479:     my $filepath = &build_filepath($fpath);
                   1480:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1481:     print $fh $content;
                   1482:     close($fh);
1.638     albertel 1483:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1484:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1485: 			  $home);
1.637     raeburn  1486:     if ($$fetchresult eq 'ok') {
                   1487:         return '/uploaded/'.$fpath.'/'.$fname;
                   1488:     } else {
1.638     albertel 1489:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1490: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1491:         return '/adm/notfound.html';
                   1492:     }
                   1493: }
                   1494: 
1.531     albertel 1495: sub clean_filename {
1.831     albertel 1496:     my ($fname,$args)=@_;
1.315     www      1497: # Replace Windows backslashes by forward slashes
1.257     www      1498:     $fname=~s/\\/\//g;
1.831     albertel 1499:     if (!$args->{'keep_path'}) {
                   1500:         # Get rid of everything but the actual filename
                   1501: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1502:     }
1.315     www      1503: # Replace spaces by underscores
                   1504:     $fname=~s/\s+/\_/g;
                   1505: # Replace all other weird characters by nothing
1.831     albertel 1506:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1507: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1508: # numbers
                   1509:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1510:     return $fname;
                   1511: }
                   1512: 
1.608     albertel 1513: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1514: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1515: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1516: #        $coursedoc - if true up to the current course
                   1517: #                     if false
                   1518: #        $subdir - directory in userfile to store the file into
                   1519: #        $parser, $allfiles, $codebase - unknown
                   1520: #
                   1521: # output: url of file in userspace, or error: <message> 
                   1522: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1523: 
                   1524: 
1.531     albertel 1525: sub userfileupload {
1.719     banghart 1526:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1527:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1528:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1529:     $fname=&clean_filename($fname);
1.315     www      1530: # See if there is anything left
1.257     www      1531:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1532:     chop($env{'form.'.$formname});
1.523     raeburn  1533:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1534:         my $now = time;
                   1535:         my $filepath = 'tmp/helprequests/'.$now;
                   1536:         my @parts=split(/\//,$filepath);
                   1537:         my $fullpath = $perlvar{'lonDaemons'};
                   1538:         for (my $i=0;$i<@parts;$i++) {
                   1539:             $fullpath .= '/'.$parts[$i];
                   1540:             if ((-e $fullpath)!=1) {
                   1541:                 mkdir($fullpath,0777);
                   1542:             }
                   1543:         }
                   1544:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1545:         print $fh $env{'form.'.$formname};
1.523     raeburn  1546:         close($fh);
1.741     raeburn  1547:         return $fullpath.'/'.$fname;
                   1548:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1549:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1550:                        '_'.$env{'user.domain'}.'/pending';
                   1551:         my @parts=split(/\//,$filepath);
                   1552:         my $fullpath = $perlvar{'lonDaemons'};
                   1553:         for (my $i=0;$i<@parts;$i++) {
                   1554:             $fullpath .= '/'.$parts[$i];
                   1555:             if ((-e $fullpath)!=1) {
                   1556:                 mkdir($fullpath,0777);
                   1557:             }
                   1558:         }
                   1559:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1560:         print $fh $env{'form.'.$formname};
                   1561:         close($fh);
                   1562:         return $fullpath.'/'.$fname;
1.523     raeburn  1563:     }
1.719     banghart 1564:     
1.258     www      1565: # Create the directory if not present
1.493     albertel 1566:     $fname="$subdir/$fname";
1.259     www      1567:     if ($coursedoc) {
1.638     albertel 1568: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1569: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1570:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1571:             return &finishuserfileupload($docuname,$docudom,
                   1572: 					 $formname,$fname,$parser,$allfiles,
                   1573: 					 $codebase);
1.481     raeburn  1574:         } else {
1.620     albertel 1575:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1576:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1577: 				       $fname,$formname,$parser,
                   1578: 				       $allfiles,$codebase);
1.481     raeburn  1579:         }
1.719     banghart 1580:     } elsif (defined($destuname)) {
                   1581:         my $docuname=$destuname;
                   1582:         my $docudom=$destudom;
                   1583: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1584: 				     $fname,$parser,$allfiles,$codebase);
                   1585:         
1.259     www      1586:     } else {
1.638     albertel 1587:         my $docuname=$env{'user.name'};
                   1588:         my $docudom=$env{'user.domain'};
1.714     raeburn  1589:         if (exists($env{'form.group'})) {
                   1590:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1591:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1592:         }
1.638     albertel 1593: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1594: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1595:     }
1.271     www      1596: }
                   1597: 
                   1598: sub finishuserfileupload {
1.638     albertel 1599:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1600:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1601:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1602:     my ($fnamepath,$file);
                   1603:     $file=$fname;
                   1604:     if ($fname=~m|/|) {
                   1605:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1606: 	$path.=$fnamepath.'/';
                   1607:     }
1.259     www      1608:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1609:     my $count;
                   1610:     for ($count=4;$count<=$#parts;$count++) {
                   1611:         $filepath.="/$parts[$count]";
                   1612:         if ((-e $filepath)!=1) {
                   1613: 	    mkdir($filepath,0777);
                   1614:         }
                   1615:     }
                   1616: # Save the file
                   1617:     {
1.701     albertel 1618: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1619: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1620: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1621: 	    return '/adm/notfound.html';
                   1622: 	}
                   1623: 	if (!print FH ($env{'form.'.$formname})) {
                   1624: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1625: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1626: 	    return '/adm/notfound.html';
                   1627: 	}
1.570     albertel 1628: 	close(FH);
1.258     www      1629:     }
1.637     raeburn  1630:     if ($parser eq 'parse') {
1.638     albertel 1631:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1632: 						   $codebase);
1.637     raeburn  1633:         unless ($parse_result eq 'ok') {
1.638     albertel 1634:             &logthis('Failed to parse '.$filepath.$file.
                   1635: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1636:         }
                   1637:     }
1.259     www      1638: # Notify homeserver to grep it
                   1639: #
1.638     albertel 1640:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1641:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1642:     if ($fetchresult eq 'ok') {
1.259     www      1643: #
1.258     www      1644: # Return the URL to it
1.494     albertel 1645:         return '/uploaded/'.$path.$file;
1.263     www      1646:     } else {
1.494     albertel 1647:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1648: 		 ': '.$fetchresult);
1.263     www      1649:         return '/adm/notfound.html';
                   1650:     }    
1.493     albertel 1651: }
                   1652: 
1.637     raeburn  1653: sub extract_embedded_items {
1.648     raeburn  1654:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1655:     my @state = ();
                   1656:     my %javafiles = (
                   1657:                       codebase => '',
                   1658:                       code => '',
                   1659:                       archive => ''
                   1660:                     );
                   1661:     my %mediafiles = (
                   1662:                       src => '',
                   1663:                       movie => '',
                   1664:                      );
1.648     raeburn  1665:     my $p;
                   1666:     if ($content) {
                   1667:         $p = HTML::LCParser->new($content);
                   1668:     } else {
                   1669:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1670:     }
1.641     albertel 1671:     while (my $t=$p->get_token()) {
1.640     albertel 1672: 	if ($t->[0] eq 'S') {
                   1673: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1674: 	    push (@state, $tagname);
1.648     raeburn  1675:             if (lc($tagname) eq 'allow') {
                   1676:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1677:             }
1.640     albertel 1678: 	    if (lc($tagname) eq 'img') {
                   1679: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1680: 	    }
1.645     raeburn  1681:             if (lc($tagname) eq 'script') {
                   1682:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1683:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1684:                 } else {
                   1685:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1686:                 }
                   1687:             }
                   1688:             if (lc($tagname) eq 'link') {
                   1689:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1690:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1691:                 }
                   1692:             }
1.640     albertel 1693: 	    if (lc($tagname) eq 'object' ||
                   1694: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1695: 		foreach my $item (keys(%javafiles)) {
                   1696: 		    $javafiles{$item} = '';
                   1697: 		}
                   1698: 	    }
                   1699: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1700: 		my $name = lc($attr->{'name'});
                   1701: 		foreach my $item (keys(%javafiles)) {
                   1702: 		    if ($name eq $item) {
                   1703: 			$javafiles{$item} = $attr->{'value'};
                   1704: 			last;
                   1705: 		    }
                   1706: 		}
                   1707: 		foreach my $item (keys(%mediafiles)) {
                   1708: 		    if ($name eq $item) {
                   1709: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1710: 			last;
                   1711: 		    }
                   1712: 		}
                   1713: 	    }
                   1714: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1715: 		foreach my $item (keys(%javafiles)) {
                   1716: 		    if ($attr->{$item}) {
                   1717: 			$javafiles{$item} = $attr->{$item};
                   1718: 			last;
                   1719: 		    }
                   1720: 		}
                   1721: 		foreach my $item (keys(%mediafiles)) {
                   1722: 		    if ($attr->{$item}) {
                   1723: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1724: 			last;
                   1725: 		    }
                   1726: 		}
                   1727: 	    }
                   1728: 	} elsif ($t->[0] eq 'E') {
                   1729: 	    my ($tagname) = ($t->[1]);
                   1730: 	    if ($javafiles{'codebase'} ne '') {
                   1731: 		$javafiles{'codebase'} .= '/';
                   1732: 	    }  
                   1733: 	    if (lc($tagname) eq 'applet' ||
                   1734: 		lc($tagname) eq 'object' ||
                   1735: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1736: 		) {
                   1737: 		foreach my $item (keys(%javafiles)) {
                   1738: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1739: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1740: 			&add_filetype($allfiles,$file,$item);
                   1741: 		    }
                   1742: 		}
                   1743: 	    } 
                   1744: 	    pop @state;
                   1745: 	}
                   1746:     }
1.637     raeburn  1747:     return 'ok';
                   1748: }
                   1749: 
1.639     albertel 1750: sub add_filetype {
                   1751:     my ($allfiles,$file,$type)=@_;
                   1752:     if (exists($allfiles->{$file})) {
                   1753: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1754: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1755: 	}
                   1756:     } else {
                   1757: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1758:     }
                   1759: }
                   1760: 
1.493     albertel 1761: sub removeuploadedurl {
                   1762:     my ($url)=@_;
                   1763:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1764:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1765: }
                   1766: 
                   1767: sub removeuserfile {
                   1768:     my ($docuname,$docudom,$fname)=@_;
                   1769:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1770:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1771:     if ($result eq 'ok') {
                   1772:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1773:             my $metafile = $fname.'.meta';
                   1774:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1775: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1776:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1777:             my $sqlresult = 
1.823     albertel 1778:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1779:                                         'portfolio_metadata',$group,
                   1780:                                         'delete');
1.798     raeburn  1781:         }
                   1782:     }
                   1783:     return $result;
1.257     www      1784: }
1.15      www      1785: 
1.530     albertel 1786: sub mkdiruserfile {
                   1787:     my ($docuname,$docudom,$dir)=@_;
                   1788:     my $home=&homeserver($docuname,$docudom);
                   1789:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1790: }
                   1791: 
1.531     albertel 1792: sub renameuserfile {
                   1793:     my ($docuname,$docudom,$old,$new)=@_;
                   1794:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1795:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1796:                         &escape("$old").':'.&escape("$new"),$home);
                   1797:     if ($result eq 'ok') {
                   1798:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1799:             my $oldmeta = $old.'.meta';
                   1800:             my $newmeta = $new.'.meta';
                   1801:             my $metaresult = 
                   1802:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1803: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1804:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1805:             my $sqlresult = 
1.823     albertel 1806:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1807:                                         'portfolio_metadata',$group,
                   1808:                                         'delete');
1.798     raeburn  1809:         }
                   1810:     }
                   1811:     return $result;
1.531     albertel 1812: }
                   1813: 
1.14      www      1814: # ------------------------------------------------------------------------- Log
                   1815: 
                   1816: sub log {
                   1817:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1818:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1819: }
                   1820: 
                   1821: # ------------------------------------------------------------------ Course Log
1.352     www      1822: #
                   1823: # This routine flushes several buffers of non-mission-critical nature
                   1824: #
1.157     www      1825: 
                   1826: sub flushcourselogs {
1.352     www      1827:     &logthis('Flushing log buffers');
                   1828: #
                   1829: # course logs
                   1830: # This is a log of all transactions in a course, which can be used
                   1831: # for data mining purposes
                   1832: #
                   1833: # It also collects the courseid database, which lists last transaction
                   1834: # times and course titles for all courseids
                   1835: #
                   1836:     my %courseidbuffer=();
1.800     albertel 1837:     foreach my $crsid (keys %courselogs) {
1.352     www      1838:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1839: 		          &escape($courselogs{$crsid}),
                   1840: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1841: 	    delete $courselogs{$crsid};
                   1842:         } else {
                   1843:             &logthis('Failed to flush log buffer for '.$crsid);
                   1844:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1845:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1846:                         " exceeded maximum size, deleting.</font>");
                   1847:                delete $courselogs{$crsid};
                   1848:             }
1.352     www      1849:         }
                   1850:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1851:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1852: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1853:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1854:         } else {
                   1855:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1856: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1857:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1858:         }
1.191     harris41 1859:     }
1.352     www      1860: #
                   1861: # Write course id database (reverse lookup) to homeserver of courses 
                   1862: # Is used in pickcourse
                   1863: #
1.840     albertel 1864:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1865:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1866: 		     $crs_home);
1.352     www      1867:     }
                   1868: #
                   1869: # File accesses
                   1870: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1871: #
1.449     matthew  1872:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1873:         if ($entry =~ /___count$/) {
                   1874:             my ($dom,$name);
1.807     albertel 1875:             ($dom,$name,undef)=
1.811     albertel 1876: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1877:             if (! defined($dom) || $dom eq '' || 
                   1878:                 ! defined($name) || $name eq '') {
1.620     albertel 1879:                 my $cid = $env{'request.course.id'};
                   1880:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1881:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1882:             }
1.450     matthew  1883:             my $value = $accesshash{$entry};
                   1884:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1885:             my %temphash=($url => $value);
1.449     matthew  1886:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1887:             if ($result eq 'ok') {
                   1888:                 delete $accesshash{$entry};
                   1889:             } elsif ($result eq 'unknown_cmd') {
                   1890:                 # Target server has old code running on it.
1.450     matthew  1891:                 my %temphash=($entry => $value);
1.449     matthew  1892:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1893:                     delete $accesshash{$entry};
                   1894:                 }
                   1895:             }
                   1896:         } else {
1.811     albertel 1897:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1898:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1899:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1900:                 delete $accesshash{$entry};
                   1901:             }
1.185     www      1902:         }
1.191     harris41 1903:     }
1.352     www      1904: #
                   1905: # Roles
                   1906: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1907: #
1.800     albertel 1908:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1909:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1910: 	    split(/\:/,$entry);
                   1911:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1912:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1913:                 $rudom,$runame) eq 'ok') {
                   1914: 	    delete $userrolehash{$entry};
                   1915:         }
                   1916:     }
1.662     raeburn  1917: #
                   1918: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1919: #
                   1920:     my %domrolebuffer = ();
                   1921:     foreach my $entry (keys %domainrolehash) {
                   1922:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1923:         if ($domrolebuffer{$rudom}) {
                   1924:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1925:                       '='.&escape($domainrolehash{$entry});
                   1926:         } else {
                   1927:             $domrolebuffer{$rudom}.=&escape($entry).
                   1928:                       '='.&escape($domainrolehash{$entry});
                   1929:         }
                   1930:         delete $domainrolehash{$entry};
                   1931:     }
                   1932:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 1933: 	my %servers = &get_servers($dom,'library');
                   1934: 	foreach my $tryserver (keys(%servers)) {
                   1935: 	    unless (&reply('domroleput:'.$dom.':'.
                   1936: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1937: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1938: 	    }
1.662     raeburn  1939:         }
                   1940:     }
1.186     www      1941:     $dumpcount++;
1.157     www      1942: }
                   1943: 
                   1944: sub courselog {
                   1945:     my $what=shift;
1.158     www      1946:     $what=time.':'.$what;
1.620     albertel 1947:     unless ($env{'request.course.id'}) { return ''; }
                   1948:     $coursedombuf{$env{'request.course.id'}}=
                   1949:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1950:     $coursenumbuf{$env{'request.course.id'}}=
                   1951:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1952:     $coursehombuf{$env{'request.course.id'}}=
                   1953:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1954:     $coursedescrbuf{$env{'request.course.id'}}=
                   1955:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1956:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1957:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1958:     $courseownerbuf{$env{'request.course.id'}}=
                   1959:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1960:     $coursetypebuf{$env{'request.course.id'}}=
                   1961:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1962:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1963: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1964:     } else {
1.620     albertel 1965: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1966:     }
1.620     albertel 1967:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1968: 	&flushcourselogs();
                   1969:     }
1.158     www      1970: }
                   1971: 
                   1972: sub courseacclog {
                   1973:     my $fnsymb=shift;
1.620     albertel 1974:     unless ($env{'request.course.id'}) { return ''; }
                   1975:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1976:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1977:         $what.=':POST';
1.583     matthew  1978:         # FIXME: Probably ought to escape things....
1.800     albertel 1979: 	foreach my $key (keys(%env)) {
                   1980:             if ($key=~/^form\.(.*)/) {
                   1981: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1982:             }
1.191     harris41 1983:         }
1.583     matthew  1984:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1985:         # FIXME: We should not be depending on a form parameter that someone
                   1986:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1987:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1988:             $what.= ':POST';
                   1989:             # FIXME: Probably ought to escape things....
                   1990:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1991:                                  'crsdiscuss') {
1.620     albertel 1992:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1993:             }
                   1994:         }
1.158     www      1995:     }
                   1996:     &courselog($what);
1.149     www      1997: }
                   1998: 
1.185     www      1999: sub countacc {
                   2000:     my $url=&declutter(shift);
1.458     matthew  2001:     return if (! defined($url) || $url eq '');
1.620     albertel 2002:     unless ($env{'request.course.id'}) { return ''; }
                   2003:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2004:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2005:     $accesshash{$key}++;
1.185     www      2006: }
1.349     www      2007: 
1.361     www      2008: sub linklog {
                   2009:     my ($from,$to)=@_;
                   2010:     $from=&declutter($from);
                   2011:     $to=&declutter($to);
                   2012:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2013:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2014: }
                   2015:   
1.349     www      2016: sub userrolelog {
                   2017:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2018:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2019:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2020:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2021:         ($trole=~/^ta/)) {
1.350     www      2022:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2023:        $userrolehash
                   2024:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2025:                     =$tend.':'.$tstart;
1.662     raeburn  2026:     }
                   2027:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2028:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2029:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2030:         ($trole=~/^sc/)) {
                   2031:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2032:        $domainrolehash
                   2033:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2034:                     = $tend.':'.$tstart;
                   2035:     }
1.351     www      2036: }
                   2037: 
                   2038: sub get_course_adv_roles {
                   2039:     my $cid=shift;
1.620     albertel 2040:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2041:     my %coursehash=&coursedescription($cid);
1.470     www      2042:     my %nothide=();
1.800     albertel 2043:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2044: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2045:     }
1.351     www      2046:     my %returnhash=();
                   2047:     my %dumphash=
                   2048:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2049:     my $now=time;
1.800     albertel 2050:     foreach my $entry (keys %dumphash) {
                   2051: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2052:         if (($tstart) && ($tstart<0)) { next; }
                   2053:         if (($tend) && ($tend<$now)) { next; }
                   2054:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2055:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2056: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2057: 	if ((&privileged($username,$domain)) && 
                   2058: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2059: 	if ($role eq 'cr') { next; }
1.351     www      2060:         my $key=&plaintext($role);
                   2061:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2062:         if ($returnhash{$key}) {
                   2063: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2064:         } else {
                   2065:             $returnhash{$key}=$username.':'.$domain;
                   2066:         }
1.400     www      2067:      }
                   2068:     return %returnhash;
                   2069: }
                   2070: 
                   2071: sub get_my_roles {
1.832     raeburn  2072:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
1.620     albertel 2073:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2074:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2075:     my %dumphash=
                   2076:             &dump('nohist_userroles',$udom,$uname);
                   2077:     my %returnhash=();
                   2078:     my $now=time;
1.800     albertel 2079:     foreach my $entry (keys(%dumphash)) {
                   2080: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2081:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2082:         my $status = 'active';
                   2083:         if (($tend) && ($tend<$now)) {
                   2084:             $status = 'previous';
                   2085:         } 
                   2086:         if (($tstart) && ($now<$tstart)) {
                   2087:             $status = 'future';
                   2088:         }
                   2089:         if (ref($types) eq 'ARRAY') {
                   2090:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2091:                 next;
                   2092:             } 
                   2093:         } else {
                   2094:             if ($status ne 'active') {
                   2095:                 next;
                   2096:             }
                   2097:         }
1.800     albertel 2098:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.832     raeburn  2099:         if (ref($roledoms) eq 'ARRAY') {
                   2100:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2101:                 next;
                   2102:             }
                   2103:         }
                   2104:         if (ref($roles) eq 'ARRAY') {
                   2105:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2106:                 next;
                   2107:             }
                   2108:         } 
1.400     www      2109: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2110:     }
1.373     www      2111:     return %returnhash;
1.399     www      2112: }
                   2113: 
                   2114: # ----------------------------------------------------- Frontpage Announcements
                   2115: #
                   2116: #
                   2117: 
                   2118: sub postannounce {
                   2119:     my ($server,$text)=@_;
1.844     albertel 2120:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2121:     unless ($text=~/\w/) { $text=''; }
                   2122:     return &reply('setannounce:'.&escape($text),$server);
                   2123: }
                   2124: 
                   2125: sub getannounce {
1.448     albertel 2126: 
                   2127:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2128: 	my $announcement='';
1.800     albertel 2129: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2130: 	close($fh);
1.399     www      2131: 	if ($announcement=~/\w/) { 
                   2132: 	    return 
                   2133:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2134:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2135: 	} else {
                   2136: 	    return '';
                   2137: 	}
                   2138:     } else {
                   2139: 	return '';
                   2140:     }
1.351     www      2141: }
1.353     www      2142: 
                   2143: # ---------------------------------------------------------- Course ID routines
                   2144: # Deal with domain's nohist_courseid.db files
                   2145: #
                   2146: 
                   2147: sub courseidput {
                   2148:     my ($domain,$what,$coursehome)=@_;
                   2149:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2150: }
                   2151: 
                   2152: sub courseiddump {
1.791     raeburn  2153:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2154:     my %returnhash=();
1.355     www      2155:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2156:     my %libserv = &all_library();
                   2157:     foreach my $tryserver (keys(%libserv)) {
                   2158:         if ( (  $hostidflag == 1 
                   2159: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2160: 	     || (!defined($hostidflag)) ) {
                   2161: 
                   2162: 	    if ($domfilter eq ''
                   2163: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2164: 	        foreach my $line (
1.844     albertel 2165:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2166: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2167:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2168:                                $tryserver))) {
1.800     albertel 2169: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2170:                     if (($key) && ($value)) {
1.516     raeburn  2171: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2172:                     }
1.353     www      2173:                 }
                   2174:             }
                   2175:         }
                   2176:     }
                   2177:     return %returnhash;
                   2178: }
                   2179: 
1.658     raeburn  2180: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2181: 
                   2182: sub dcmailput {
1.685     raeburn  2183:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2184:     my $status = &Apache::lonnet::critical(
1.740     www      2185:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2186:        &escape($message),$server);
1.662     raeburn  2187:     return $status;
                   2188: }
                   2189: 
1.658     raeburn  2190: sub dcmaildump {
                   2191:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2192:     my %returnhash=();
1.846     albertel 2193: 
                   2194:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2195:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2196:                                                          &escape($enddate).':';
                   2197: 	my @esc_senders=map { &escape($_)} @$senders;
                   2198: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2199: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2200:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2201:             if (($key) && ($value)) {
                   2202:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2203:             }
                   2204:         }
                   2205:     }
                   2206:     return %returnhash;
                   2207: }
1.662     raeburn  2208: # ---------------------------------------------------------- Domain roles
                   2209: 
                   2210: sub get_domain_roles {
                   2211:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2212:     if (undef($startdate) || $startdate eq '') {
                   2213:         $startdate = '.';
                   2214:     }
                   2215:     if (undef($enddate) || $enddate eq '') {
                   2216:         $enddate = '.';
                   2217:     }
                   2218:     my $rolelist = join(':',@{$roles});
                   2219:     my %personnel = ();
1.841     albertel 2220: 
                   2221:     my %servers = &get_servers($dom,'library');
                   2222:     foreach my $tryserver (keys(%servers)) {
                   2223: 	%{$personnel{$tryserver}}=();
                   2224: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2225: 					    &escape($startdate).':'.
                   2226: 					    &escape($enddate).':'.
                   2227: 					    &escape($rolelist), $tryserver))) {
                   2228: 	    my ($key,$value) = split(/\=/,$line,2);
                   2229: 	    if (($key) && ($value)) {
                   2230: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2231: 	    }
                   2232: 	}
1.662     raeburn  2233:     }
                   2234:     return %personnel;
                   2235: }
1.658     raeburn  2236: 
1.149     www      2237: # ----------------------------------------------------------- Check out an item
                   2238: 
1.504     albertel 2239: sub get_first_access {
                   2240:     my ($type,$argsymb)=@_;
1.790     albertel 2241:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2242:     if ($argsymb) { $symb=$argsymb; }
                   2243:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2244:     if ($type eq 'map') {
                   2245: 	$res=&symbread($map);
                   2246:     } else {
                   2247: 	$res=$symb;
                   2248:     }
                   2249:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2250:     return $times{"$courseid\0$res"};
1.504     albertel 2251: }
                   2252: 
                   2253: sub set_first_access {
                   2254:     my ($type)=@_;
1.790     albertel 2255:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2256:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2257:     if ($type eq 'map') {
                   2258: 	$res=&symbread($map);
                   2259:     } else {
                   2260: 	$res=$symb;
                   2261:     }
                   2262:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2263:     if (!$firstaccess) {
1.588     albertel 2264: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2265:     }
                   2266:     return 'already_set';
1.504     albertel 2267: }
                   2268: 
1.149     www      2269: sub checkout {
                   2270:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2271:     my $now=time;
                   2272:     my $lonhost=$perlvar{'lonHostID'};
                   2273:     my $infostr=&escape(
1.234     www      2274:                  'CHECKOUTTOKEN&'.
1.149     www      2275:                  $tuname.'&'.
                   2276:                  $tudom.'&'.
                   2277:                  $tcrsid.'&'.
                   2278:                  $symb.'&'.
                   2279: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2280:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2281:     if ($token=~/^error\:/) { 
1.672     albertel 2282:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2283:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2284:                  "</font>");
                   2285:         return ''; 
                   2286:     }
                   2287: 
1.149     www      2288:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2289:     $token=~tr/a-z/A-Z/;
                   2290: 
1.153     www      2291:     my %infohash=('resource.0.outtoken' => $token,
                   2292:                   'resource.0.checkouttime' => $now,
                   2293:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2294: 
                   2295:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2296:        return '';
1.151     www      2297:     } else {
1.672     albertel 2298:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2299:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2300:                  "</font>");
1.149     www      2301:     }    
                   2302: 
                   2303:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2304:                          &escape('Checkout '.$infostr.' - '.
                   2305:                                                  $token)) ne 'ok') {
                   2306: 	return '';
1.151     www      2307:     } else {
1.672     albertel 2308:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2309:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2310:                  "</font>");
1.149     www      2311:     }
1.151     www      2312:     return $token;
1.149     www      2313: }
                   2314: 
                   2315: # ------------------------------------------------------------ Check in an item
                   2316: 
                   2317: sub checkin {
                   2318:     my $token=shift;
1.150     www      2319:     my $now=time;
                   2320:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2321:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2322:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2323:     $dtoken=~s/\W/\_/g;
1.234     www      2324:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2325:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2326: 
1.154     www      2327:     unless (($tuname) && ($tudom)) {
                   2328:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2329:         return '';
                   2330:     }
                   2331:     
                   2332:     unless (&allowed('mgr',$tcrsid)) {
                   2333:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2334:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2335:         return '';
                   2336:     }
                   2337: 
1.153     www      2338:     my %infohash=('resource.0.intoken' => $token,
                   2339:                   'resource.0.checkintime' => $now,
                   2340:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2341: 
                   2342:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2343:        return '';
                   2344:     }    
                   2345: 
                   2346:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2347:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2348: 	return '';
                   2349:     }
                   2350: 
                   2351:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2352: }
                   2353: 
                   2354: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2355: 
                   2356: sub expirespread {
                   2357:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2358:     my $cid=$env{'request.course.id'}; 
1.110     www      2359:     if ($cid) {
                   2360:        my $now=time;
                   2361:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2362:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2363:                             $env{'course.'.$cid.'.num'}.
1.110     www      2364: 	        	    ':nohist_expirationdates:'.
                   2365:                             &escape($key).'='.$now,
1.620     albertel 2366:                             $env{'course.'.$cid.'.home'})
1.110     www      2367:     }
                   2368:     return 'ok';
1.14      www      2369: }
                   2370: 
1.109     www      2371: # ----------------------------------------------------- Devalidate Spreadsheets
                   2372: 
                   2373: sub devalidate {
1.325     www      2374:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2375:     my $cid=$env{'request.course.id'}; 
1.109     www      2376:     if ($cid) {
1.391     matthew  2377:         # delete the stored spreadsheets for
                   2378:         # - the student level sheet of this user in course's homespace
                   2379:         # - the assessment level sheet for this resource 
                   2380:         #   for this user in user's homespace
1.553     albertel 2381: 	# - current conditional state info
1.325     www      2382: 	my $key=$uname.':'.$udom.':';
1.109     www      2383:         my $status=
1.299     matthew  2384: 	    &del('nohist_calculatedsheets',
1.391     matthew  2385: 		 [$key.'studentcalc:'],
1.620     albertel 2386: 		 $env{'course.'.$cid.'.domain'},
                   2387: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2388: 		.' '.
                   2389: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2390: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2391:         unless ($status eq 'ok ok') {
                   2392:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2393:                     $uname.' at '.$udom.' for '.
1.109     www      2394: 		    $symb.': '.$status);
1.133     albertel 2395:         }
1.553     albertel 2396: 	&delenv('user.state.'.$cid);
1.109     www      2397:     }
                   2398: }
                   2399: 
1.265     albertel 2400: sub get_scalar {
                   2401:     my ($string,$end) = @_;
                   2402:     my $value;
                   2403:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2404: 	$value = $1;
                   2405:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2406: 	$value = $1;
                   2407:     }
                   2408:     return &unescape($value);
                   2409: }
                   2410: 
                   2411: sub array2str {
                   2412:   my (@array) = @_;
                   2413:   my $result=&arrayref2str(\@array);
                   2414:   $result=~s/^__ARRAY_REF__//;
                   2415:   $result=~s/__END_ARRAY_REF__$//;
                   2416:   return $result;
                   2417: }
                   2418: 
1.204     albertel 2419: sub arrayref2str {
                   2420:   my ($arrayref) = @_;
1.265     albertel 2421:   my $result='__ARRAY_REF__';
1.204     albertel 2422:   foreach my $elem (@$arrayref) {
1.265     albertel 2423:     if(ref($elem) eq 'ARRAY') {
                   2424:       $result.=&arrayref2str($elem).'&';
                   2425:     } elsif(ref($elem) eq 'HASH') {
                   2426:       $result.=&hashref2str($elem).'&';
                   2427:     } elsif(ref($elem)) {
                   2428:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2429:     } else {
                   2430:       $result.=&escape($elem).'&';
                   2431:     }
                   2432:   }
                   2433:   $result=~s/\&$//;
1.265     albertel 2434:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2435:   return $result;
                   2436: }
                   2437: 
1.168     albertel 2438: sub hash2str {
1.204     albertel 2439:   my (%hash) = @_;
                   2440:   my $result=&hashref2str(\%hash);
1.265     albertel 2441:   $result=~s/^__HASH_REF__//;
                   2442:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2443:   return $result;
                   2444: }
                   2445: 
                   2446: sub hashref2str {
                   2447:   my ($hashref)=@_;
1.265     albertel 2448:   my $result='__HASH_REF__';
1.800     albertel 2449:   foreach my $key (sort(keys(%$hashref))) {
                   2450:     if (ref($key) eq 'ARRAY') {
                   2451:       $result.=&arrayref2str($key).'=';
                   2452:     } elsif (ref($key) eq 'HASH') {
                   2453:       $result.=&hashref2str($key).'=';
                   2454:     } elsif (ref($key)) {
1.265     albertel 2455:       $result.='=';
1.800     albertel 2456:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2457:     } else {
1.800     albertel 2458: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2459:     }
                   2460: 
1.800     albertel 2461:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2462:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2463:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2464:       $result.=&hashref2str($hashref->{$key}).'&';
                   2465:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2466:        $result.='&';
1.800     albertel 2467:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2468:     } else {
1.800     albertel 2469:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2470:     }
                   2471:   }
1.168     albertel 2472:   $result=~s/\&$//;
1.265     albertel 2473:   $result .= '__END_HASH_REF__';
1.168     albertel 2474:   return $result;
                   2475: }
                   2476: 
                   2477: sub str2hash {
1.265     albertel 2478:     my ($string)=@_;
                   2479:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2480:     return %$hash;
                   2481: }
                   2482: 
                   2483: sub str2hashref {
1.168     albertel 2484:   my ($string) = @_;
1.265     albertel 2485: 
                   2486:   my %hash;
                   2487: 
                   2488:   if($string !~ /^__HASH_REF__/) {
                   2489:       if (! ($string eq '' || !defined($string))) {
                   2490: 	  $hash{'error'}='Not hash reference';
                   2491:       }
                   2492:       return (\%hash, $string);
                   2493:   }
                   2494: 
                   2495:   $string =~ s/^__HASH_REF__//;
                   2496: 
                   2497:   while($string !~ /^__END_HASH_REF__/) {
                   2498:       #key
                   2499:       my $key='';
                   2500:       if($string =~ /^__HASH_REF__/) {
                   2501:           ($key, $string)=&str2hashref($string);
                   2502:           if(defined($key->{'error'})) {
                   2503:               $hash{'error'}='Bad data';
                   2504:               return (\%hash, $string);
                   2505:           }
                   2506:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2507:           ($key, $string)=&str2arrayref($string);
                   2508:           if($key->[0] eq 'Array reference error') {
                   2509:               $hash{'error'}='Bad data';
                   2510:               return (\%hash, $string);
                   2511:           }
                   2512:       } else {
                   2513:           $string =~ s/^(.*?)=//;
1.267     albertel 2514: 	  $key=&unescape($1);
1.265     albertel 2515:       }
                   2516:       $string =~ s/^=//;
                   2517: 
                   2518:       #value
                   2519:       my $value='';
                   2520:       if($string =~ /^__HASH_REF__/) {
                   2521:           ($value, $string)=&str2hashref($string);
                   2522:           if(defined($value->{'error'})) {
                   2523:               $hash{'error'}='Bad data';
                   2524:               return (\%hash, $string);
                   2525:           }
                   2526:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2527:           ($value, $string)=&str2arrayref($string);
                   2528:           if($value->[0] eq 'Array reference error') {
                   2529:               $hash{'error'}='Bad data';
                   2530:               return (\%hash, $string);
                   2531:           }
                   2532:       } else {
                   2533: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2534:       }
                   2535:       $string =~ s/^&//;
                   2536: 
                   2537:       $hash{$key}=$value;
1.204     albertel 2538:   }
1.265     albertel 2539: 
                   2540:   $string =~ s/^__END_HASH_REF__//;
                   2541: 
                   2542:   return (\%hash, $string);
1.204     albertel 2543: }
                   2544: 
                   2545: sub str2array {
1.265     albertel 2546:     my ($string)=@_;
                   2547:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2548:     return @$array;
                   2549: }
                   2550: 
                   2551: sub str2arrayref {
1.204     albertel 2552:   my ($string) = @_;
1.265     albertel 2553:   my @array;
                   2554: 
                   2555:   if($string !~ /^__ARRAY_REF__/) {
                   2556:       if (! ($string eq '' || !defined($string))) {
                   2557: 	  $array[0]='Array reference error';
                   2558:       }
                   2559:       return (\@array, $string);
                   2560:   }
                   2561: 
                   2562:   $string =~ s/^__ARRAY_REF__//;
                   2563: 
                   2564:   while($string !~ /^__END_ARRAY_REF__/) {
                   2565:       my $value='';
                   2566:       if($string =~ /^__HASH_REF__/) {
                   2567:           ($value, $string)=&str2hashref($string);
                   2568:           if(defined($value->{'error'})) {
                   2569:               $array[0] ='Array reference error';
                   2570:               return (\@array, $string);
                   2571:           }
                   2572:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2573:           ($value, $string)=&str2arrayref($string);
                   2574:           if($value->[0] eq 'Array reference error') {
                   2575:               $array[0] ='Array reference error';
                   2576:               return (\@array, $string);
                   2577:           }
                   2578:       } else {
                   2579: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2580:       }
                   2581:       $string =~ s/^&//;
                   2582: 
                   2583:       push(@array, $value);
1.191     harris41 2584:   }
1.265     albertel 2585: 
                   2586:   $string =~ s/^__END_ARRAY_REF__//;
                   2587: 
                   2588:   return (\@array, $string);
1.168     albertel 2589: }
                   2590: 
1.167     albertel 2591: # -------------------------------------------------------------------Temp Store
                   2592: 
1.168     albertel 2593: sub tmpreset {
                   2594:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2595:   if (!$symb) {
                   2596:     $symb=&symbread();
1.620     albertel 2597:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2598:   }
                   2599:   $symb=escape($symb);
                   2600: 
1.620     albertel 2601:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2602:   $namespace=~s/\//\_/g;
                   2603:   $namespace=~s/\W//g;
                   2604: 
1.620     albertel 2605:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2606:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2607:   if ($domain eq 'public' && $stuname eq 'public') {
                   2608:       $stuname=$ENV{'REMOTE_ADDR'};
                   2609:   }
1.168     albertel 2610:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2611:   my %hash;
                   2612:   if (tie(%hash,'GDBM_File',
                   2613: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2614: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2615:     foreach my $key (keys %hash) {
1.180     albertel 2616:       if ($key=~ /:$symb/) {
1.168     albertel 2617: 	delete($hash{$key});
                   2618:       }
                   2619:     }
                   2620:   }
                   2621: }
                   2622: 
1.167     albertel 2623: sub tmpstore {
1.168     albertel 2624:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2625: 
                   2626:   if (!$symb) {
                   2627:     $symb=&symbread();
1.620     albertel 2628:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2629:   }
                   2630:   $symb=escape($symb);
                   2631: 
                   2632:   if (!$namespace) {
                   2633:     # I don't think we would ever want to store this for a course.
                   2634:     # it seems this will only be used if we don't have a course.
1.620     albertel 2635:     #$namespace=$env{'request.course.id'};
1.168     albertel 2636:     #if (!$namespace) {
1.620     albertel 2637:       $namespace=$env{'request.state'};
1.168     albertel 2638:     #}
                   2639:   }
                   2640:   $namespace=~s/\//\_/g;
                   2641:   $namespace=~s/\W//g;
1.620     albertel 2642:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2643:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2644:   if ($domain eq 'public' && $stuname eq 'public') {
                   2645:       $stuname=$ENV{'REMOTE_ADDR'};
                   2646:   }
1.168     albertel 2647:   my $now=time;
                   2648:   my %hash;
                   2649:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2650:   if (tie(%hash,'GDBM_File',
                   2651: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2652: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2653:     $hash{"version:$symb"}++;
                   2654:     my $version=$hash{"version:$symb"};
                   2655:     my $allkeys=''; 
                   2656:     foreach my $key (keys(%$storehash)) {
                   2657:       $allkeys.=$key.':';
1.591     albertel 2658:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2659:     }
                   2660:     $hash{"$version:$symb:timestamp"}=$now;
                   2661:     $allkeys.='timestamp';
                   2662:     $hash{"$version:keys:$symb"}=$allkeys;
                   2663:     if (untie(%hash)) {
                   2664:       return 'ok';
                   2665:     } else {
                   2666:       return "error:$!";
                   2667:     }
                   2668:   } else {
                   2669:     return "error:$!";
                   2670:   }
                   2671: }
1.167     albertel 2672: 
1.168     albertel 2673: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2674: 
1.168     albertel 2675: sub tmprestore {
                   2676:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2677: 
1.168     albertel 2678:   if (!$symb) {
                   2679:     $symb=&symbread();
1.620     albertel 2680:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2681:   }
                   2682:   $symb=escape($symb);
                   2683: 
1.620     albertel 2684:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2685: 
1.620     albertel 2686:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2687:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2688:   if ($domain eq 'public' && $stuname eq 'public') {
                   2689:       $stuname=$ENV{'REMOTE_ADDR'};
                   2690:   }
1.168     albertel 2691:   my %returnhash;
                   2692:   $namespace=~s/\//\_/g;
                   2693:   $namespace=~s/\W//g;
                   2694:   my %hash;
                   2695:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2696:   if (tie(%hash,'GDBM_File',
                   2697: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2698: 	  &GDBM_READER(),0640)) {
1.168     albertel 2699:     my $version=$hash{"version:$symb"};
                   2700:     $returnhash{'version'}=$version;
                   2701:     my $scope;
                   2702:     for ($scope=1;$scope<=$version;$scope++) {
                   2703:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2704:       my @keys=split(/:/,$vkeys);
                   2705:       my $key;
                   2706:       $returnhash{"$scope:keys"}=$vkeys;
                   2707:       foreach $key (@keys) {
1.591     albertel 2708: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2709: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2710:       }
                   2711:     }
1.168     albertel 2712:     if (!(untie(%hash))) {
                   2713:       return "error:$!";
                   2714:     }
                   2715:   } else {
                   2716:     return "error:$!";
                   2717:   }
                   2718:   return %returnhash;
1.167     albertel 2719: }
                   2720: 
1.9       www      2721: # ----------------------------------------------------------------------- Store
                   2722: 
                   2723: sub store {
1.124     www      2724:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2725:     my $home='';
                   2726: 
1.168     albertel 2727:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2728: 
1.213     www      2729:     $symb=&symbclean($symb);
1.122     albertel 2730:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2731: 
1.620     albertel 2732:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2733:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2734: 
                   2735:     &devalidate($symb,$stuname,$domain);
1.109     www      2736: 
                   2737:     $symb=escape($symb);
1.187     www      2738:     if (!$namespace) { 
1.620     albertel 2739:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2740:           return ''; 
                   2741:        } 
                   2742:     }
1.620     albertel 2743:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2744: 
                   2745:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2746:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2747: 
1.12      www      2748:     my $namevalue='';
1.800     albertel 2749:     foreach my $key (keys(%$storehash)) {
                   2750:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2751:     }
1.12      www      2752:     $namevalue=~s/\&$//;
1.187     www      2753:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2754:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2755: }
                   2756: 
1.47      www      2757: # -------------------------------------------------------------- Critical Store
                   2758: 
                   2759: sub cstore {
1.124     www      2760:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2761:     my $home='';
                   2762: 
1.168     albertel 2763:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2764: 
1.213     www      2765:     $symb=&symbclean($symb);
1.122     albertel 2766:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2767: 
1.620     albertel 2768:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2769:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2770: 
                   2771:     &devalidate($symb,$stuname,$domain);
1.109     www      2772: 
                   2773:     $symb=escape($symb);
1.187     www      2774:     if (!$namespace) { 
1.620     albertel 2775:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2776:           return ''; 
                   2777:        } 
                   2778:     }
1.620     albertel 2779:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2780: 
                   2781:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2782:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2783: 
1.47      www      2784:     my $namevalue='';
1.800     albertel 2785:     foreach my $key (keys(%$storehash)) {
                   2786:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2787:     }
1.47      www      2788:     $namevalue=~s/\&$//;
1.187     www      2789:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2790:     return critical
                   2791:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2792: }
                   2793: 
1.9       www      2794: # --------------------------------------------------------------------- Restore
                   2795: 
                   2796: sub restore {
1.124     www      2797:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2798:     my $home='';
                   2799: 
1.168     albertel 2800:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2801: 
1.122     albertel 2802:     if (!$symb) {
                   2803:       unless ($symb=escape(&symbread())) { return ''; }
                   2804:     } else {
1.213     www      2805:       $symb=&escape(&symbclean($symb));
1.122     albertel 2806:     }
1.188     www      2807:     if (!$namespace) { 
1.620     albertel 2808:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2809:           return ''; 
                   2810:        } 
                   2811:     }
1.620     albertel 2812:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2813:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2814:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2815:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2816: 
1.12      www      2817:     my %returnhash=();
1.800     albertel 2818:     foreach my $line (split(/\&/,$answer)) {
                   2819: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2820:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2821:     }
1.75      www      2822:     my $version;
                   2823:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2824:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2825:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2826:        }
1.75      www      2827:     }
1.13      www      2828:     return %returnhash;
1.34      www      2829: }
                   2830: 
                   2831: # ---------------------------------------------------------- Course Description
                   2832: 
                   2833: sub coursedescription {
1.731     albertel 2834:     my ($courseid,$args)=@_;
1.34      www      2835:     $courseid=~s/^\///;
1.49      www      2836:     $courseid=~s/\_/\//g;
1.34      www      2837:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2838:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2839:     my $normalid=$cdomain.'_'.$cnum;
                   2840:     # need to always cache even if we get errors otherwise we keep 
                   2841:     # trying and trying and trying to get the course description.
                   2842:     my %envhash=();
                   2843:     my %returnhash=();
1.731     albertel 2844:     
                   2845:     my $expiretime=600;
                   2846:     if ($env{'request.course.id'} eq $normalid) {
                   2847: 	$expiretime=120;
                   2848:     }
                   2849: 
                   2850:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2851:     if (!$args->{'freshen_cache'}
                   2852: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2853: 	foreach my $key (keys(%env)) {
                   2854: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2855: 	    my ($setting) = $1;
                   2856: 	    $returnhash{$setting} = $env{$key};
                   2857: 	}
                   2858: 	return %returnhash;
                   2859:     }
                   2860: 
                   2861:     # get the data agin
                   2862:     if (!$args->{'one_time'}) {
                   2863: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2864:     }
1.811     albertel 2865: 
1.34      www      2866:     if ($chome ne 'no_host') {
1.302     albertel 2867:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2868:        if (!exists($returnhash{'con_lost'})) {
                   2869:            $returnhash{'home'}= $chome;
                   2870: 	   $returnhash{'domain'} = $cdomain;
                   2871: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2872:            if (!defined($returnhash{'type'})) {
                   2873:                $returnhash{'type'} = 'Course';
                   2874:            }
1.130     albertel 2875:            while (my ($name,$value) = each %returnhash) {
1.53      www      2876:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2877:            }
1.270     www      2878:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2879:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2880: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2881:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2882:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2883:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2884:        }
                   2885:     }
1.731     albertel 2886:     if (!$args->{'one_time'}) {
                   2887: 	&appenv(%envhash);
                   2888:     }
1.302     albertel 2889:     return %returnhash;
1.461     www      2890: }
                   2891: 
                   2892: # -------------------------------------------------See if a user is privileged
                   2893: 
                   2894: sub privileged {
                   2895:     my ($username,$domain)=@_;
                   2896:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2897: 			&homeserver($username,$domain));
                   2898:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2899:     my $now=time;
                   2900:     if ($rolesdump ne '') {
1.800     albertel 2901:         foreach my $entry (split(/&/,$rolesdump)) {
                   2902: 	    if ($entry!~/^rolesdef_/) {
                   2903: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2904: 		$area=~s/\_\w\w$//;
                   2905: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2906: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2907: 		    my $active=1;
                   2908: 		    if ($tend) {
                   2909: 			if ($tend<$now) { $active=0; }
                   2910: 		    }
                   2911: 		    if ($tstart) {
                   2912: 			if ($tstart>$now) { $active=0; }
                   2913: 		    }
                   2914: 		    if ($active) { return 1; }
                   2915: 		}
                   2916: 	    }
                   2917: 	}
                   2918:     }
                   2919:     return 0;
1.9       www      2920: }
1.1       albertel 2921: 
1.103     harris41 2922: # -------------------------------------------------------- Get user privileges
1.11      www      2923: 
                   2924: sub rolesinit {
                   2925:     my ($domain,$username,$authhost)=@_;
                   2926:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2927:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2928:     my %allroles=();
1.678     raeburn  2929:     my %allgroups=();   
1.11      www      2930:     my $now=time;
1.743     albertel 2931:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2932:     my $group_privs;
1.11      www      2933: 
                   2934:     if ($rolesdump ne '') {
1.800     albertel 2935:         foreach my $entry (split(/&/,$rolesdump)) {
                   2936: 	  if ($entry!~/^rolesdef_/) {
                   2937:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2938: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2939:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2940: 	    if ($role=~/^cr/) { 
1.807     albertel 2941: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2942: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2943: 		    ($tend,$tstart)=split('_',$trest);
                   2944: 		} else {
                   2945: 		    $trole=$role;
                   2946: 		}
1.678     raeburn  2947:             } elsif ($role =~ m|^gr/|) {
                   2948:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2949:                 ($trole,$group_privs) = split(/\//,$trole);
                   2950:                 $group_privs = &unescape($group_privs);
1.587     albertel 2951: 	    } else {
                   2952: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2953: 	    }
1.743     albertel 2954: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2955: 					 $username);
                   2956: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2957:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2958:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2959:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2960: 		my $spec=$trole.'.'.$area;
                   2961: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2962: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2963:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2964:                 } elsif ($trole eq 'gr') {
                   2965:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2966: 		} else {
1.567     raeburn  2967:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2968: 		}
1.12      www      2969:             }
1.662     raeburn  2970:           }
1.191     harris41 2971:         }
1.743     albertel 2972:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2973:         $userroles{'user.adv'}    = $adv;
                   2974: 	$userroles{'user.author'} = $author;
1.620     albertel 2975:         $env{'user.adv'}=$adv;
1.11      www      2976:     }
1.743     albertel 2977:     return \%userroles;  
1.11      www      2978: }
                   2979: 
1.567     raeburn  2980: sub set_arearole {
                   2981:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2982: # log the associated role with the area
                   2983:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2984:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2985: }
                   2986: 
                   2987: sub custom_roleprivs {
                   2988:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2989:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2990:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 2991:     if (&hostname($homsvr) ne '') {
1.567     raeburn  2992:         my ($rdummy,$roledef)=
                   2993:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2994:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2995:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2996:             if (defined($syspriv)) {
                   2997:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2998:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2999:             }
                   3000:             if ($tdomain ne '') {
                   3001:                 if (defined($dompriv)) {
                   3002:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3003:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3004:                 }
                   3005:                 if (($trest ne '') && (defined($coursepriv))) {
                   3006:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3007:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3008:                 }
                   3009:             }
                   3010:         }
                   3011:     }
                   3012: }
                   3013: 
1.678     raeburn  3014: sub group_roleprivs {
                   3015:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3016:     my $access = 1;
                   3017:     my $now = time;
                   3018:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3019:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3020:     if ($access) {
1.811     albertel 3021:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3022:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3023:     }
                   3024: }
1.567     raeburn  3025: 
                   3026: sub standard_roleprivs {
                   3027:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3028:     if (defined($pr{$trole.':s'})) {
                   3029:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3030:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3031:     }
                   3032:     if ($tdomain ne '') {
                   3033:         if (defined($pr{$trole.':d'})) {
                   3034:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3035:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3036:         }
                   3037:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3038:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3039:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3040:         }
                   3041:     }
                   3042: }
                   3043: 
                   3044: sub set_userprivs {
1.678     raeburn  3045:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3046:     my $author=0;
                   3047:     my $adv=0;
1.678     raeburn  3048:     my %grouproles = ();
                   3049:     if (keys(%{$allgroups}) > 0) {
                   3050:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3051:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3052:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3053:                 $trole = $1;
                   3054:                 $area = $2;
1.681     raeburn  3055:                 $sec = $3;
                   3056:                 $extendedarea = $area.$sec;
                   3057:                 if (exists($$allgroups{$area})) {
                   3058:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3059:                         my $spec = $trole.'.'.$extendedarea;
                   3060:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3061:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3062:                     }
                   3063:                 }
                   3064:             }
                   3065:         }
                   3066:     }
1.800     albertel 3067:     foreach my $group (keys(%grouproles)) {
                   3068:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3069:     }
1.800     albertel 3070:     foreach my $role (keys(%{$allroles})) {
                   3071:         my %thesepriv;
                   3072:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3073:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3074:             if ($item ne '') {
                   3075:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3076:                 if ($restrictions eq '') {
                   3077:                     $thesepriv{$privilege}='F';
                   3078:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3079:                     $thesepriv{$privilege}.=$restrictions;
                   3080:                 }
                   3081:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3082:             }
                   3083:         }
                   3084:         my $thesestr='';
1.800     albertel 3085:         foreach my $priv (keys(%thesepriv)) {
                   3086: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3087: 	}
                   3088:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3089:     }
                   3090:     return ($author,$adv);
                   3091: }
                   3092: 
1.12      www      3093: # --------------------------------------------------------------- get interface
                   3094: 
                   3095: sub get {
1.131     albertel 3096:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3097:    my $items='';
1.800     albertel 3098:    foreach my $item (@$storearr) {
                   3099:        $items.=&escape($item).'&';
1.191     harris41 3100:    }
1.12      www      3101:    $items=~s/\&$//;
1.620     albertel 3102:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3103:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3104:    my $uhome=&homeserver($uname,$udomain);
                   3105: 
1.133     albertel 3106:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3107:    my @pairs=split(/\&/,$rep);
1.273     albertel 3108:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3109:      return @pairs;
                   3110:    }
1.15      www      3111:    my %returnhash=();
1.42      www      3112:    my $i=0;
1.800     albertel 3113:    foreach my $item (@$storearr) {
                   3114:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3115:       $i++;
1.191     harris41 3116:    }
1.15      www      3117:    return %returnhash;
1.27      www      3118: }
                   3119: 
                   3120: # --------------------------------------------------------------- del interface
                   3121: 
                   3122: sub del {
1.133     albertel 3123:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3124:    my $items='';
1.800     albertel 3125:    foreach my $item (@$storearr) {
                   3126:        $items.=&escape($item).'&';
1.191     harris41 3127:    }
1.27      www      3128:    $items=~s/\&$//;
1.620     albertel 3129:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3130:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3131:    my $uhome=&homeserver($uname,$udomain);
                   3132: 
                   3133:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3134: }
                   3135: 
                   3136: # -------------------------------------------------------------- dump interface
                   3137: 
                   3138: sub dump {
1.755     albertel 3139:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3140:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3141:     if (!$uname) { $uname=$env{'user.name'}; }
                   3142:     my $uhome=&homeserver($uname,$udomain);
                   3143:     if ($regexp) {
                   3144: 	$regexp=&escape($regexp);
                   3145:     } else {
                   3146: 	$regexp='.';
                   3147:     }
                   3148:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3149:     my @pairs=split(/\&/,$rep);
                   3150:     my %returnhash=();
                   3151:     foreach my $item (@pairs) {
                   3152: 	my ($key,$value)=split(/=/,$item,2);
                   3153: 	$key = &unescape($key);
                   3154: 	next if ($key =~ /^error: 2 /);
                   3155: 	$returnhash{$key}=&thaw_unescape($value);
                   3156:     }
                   3157:     return %returnhash;
1.407     www      3158: }
                   3159: 
1.717     albertel 3160: # --------------------------------------------------------- dumpstore interface
                   3161: 
                   3162: sub dumpstore {
                   3163:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3164:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3165:    if (!$uname) { $uname=$env{'user.name'}; }
                   3166:    my $uhome=&homeserver($uname,$udomain);
                   3167:    if ($regexp) {
                   3168:        $regexp=&escape($regexp);
                   3169:    } else {
                   3170:        $regexp='.';
                   3171:    }
                   3172:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3173:    my @pairs=split(/\&/,$rep);
                   3174:    my %returnhash=();
                   3175:    foreach my $item (@pairs) {
                   3176:        my ($key,$value)=split(/=/,$item,2);
                   3177:        next if ($key =~ /^error: 2 /);
                   3178:        $returnhash{$key}=&thaw_unescape($value);
                   3179:    }
                   3180:    return %returnhash;
1.717     albertel 3181: }
                   3182: 
1.407     www      3183: # -------------------------------------------------------------- keys interface
                   3184: 
                   3185: sub getkeys {
                   3186:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3187:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3188:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3189:    my $uhome=&homeserver($uname,$udomain);
                   3190:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3191:    my @keyarray=();
1.800     albertel 3192:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3193:       next if ($key =~ /^error: 2 /);
1.800     albertel 3194:       push(@keyarray,&unescape($key));
1.407     www      3195:    }
                   3196:    return @keyarray;
1.318     matthew  3197: }
                   3198: 
1.319     matthew  3199: # --------------------------------------------------------------- currentdump
                   3200: sub currentdump {
1.328     matthew  3201:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3202:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3203:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3204:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3205:    my $uhome = &homeserver($sname,$sdom);
                   3206:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3207:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3208:    #
1.318     matthew  3209:    my %returnhash=();
1.319     matthew  3210:    #
                   3211:    if ($rep eq "unknown_cmd") { 
                   3212:        # an old lond will not know currentdump
                   3213:        # Do a dump and make it look like a currentdump
1.822     albertel 3214:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3215:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3216:        my %hash = @tmp;
                   3217:        @tmp=();
1.424     matthew  3218:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3219:    } else {
                   3220:        my @pairs=split(/\&/,$rep);
1.800     albertel 3221:        foreach my $pair (@pairs) {
                   3222:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3223:            my ($symb,$param) = split(/:/,$key);
                   3224:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3225:                                                         &thaw_unescape($value);
1.319     matthew  3226:        }
1.191     harris41 3227:    }
1.12      www      3228:    return %returnhash;
1.424     matthew  3229: }
                   3230: 
                   3231: sub convert_dump_to_currentdump{
                   3232:     my %hash = %{shift()};
                   3233:     my %returnhash;
                   3234:     # Code ripped from lond, essentially.  The only difference
                   3235:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3236:     # we might run in to problems with parameter names =~ /^v\./
                   3237:     while (my ($key,$value) = each(%hash)) {
                   3238:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3239: 	$symb  = &unescape($symb);
                   3240: 	$param = &unescape($param);
1.424     matthew  3241:         next if ($v eq 'version' || $symb eq 'keys');
                   3242:         next if (exists($returnhash{$symb}) &&
                   3243:                  exists($returnhash{$symb}->{$param}) &&
                   3244:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3245:         $returnhash{$symb}->{$param}=$value;
                   3246:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3247:     }
                   3248:     #
                   3249:     # Remove all of the keys in the hashes which keep track of
                   3250:     # the version of the parameter.
                   3251:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3252:         # use a foreach because we are going to delete from the hash.
                   3253:         foreach my $key (keys(%$param_hash)) {
                   3254:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3255:         }
                   3256:     }
                   3257:     return \%returnhash;
1.12      www      3258: }
                   3259: 
1.627     albertel 3260: # ------------------------------------------------------ critical inc interface
                   3261: 
                   3262: sub cinc {
                   3263:     return &inc(@_,'critical');
                   3264: }
                   3265: 
1.449     matthew  3266: # --------------------------------------------------------------- inc interface
                   3267: 
                   3268: sub inc {
1.627     albertel 3269:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3270:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3271:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3272:     my $uhome=&homeserver($uname,$udomain);
                   3273:     my $items='';
                   3274:     if (! ref($store)) {
                   3275:         # got a single value, so use that instead
                   3276:         $items = &escape($store).'=&';
                   3277:     } elsif (ref($store) eq 'SCALAR') {
                   3278:         $items = &escape($$store).'=&';        
                   3279:     } elsif (ref($store) eq 'ARRAY') {
                   3280:         $items = join('=&',map {&escape($_);} @{$store});
                   3281:     } elsif (ref($store) eq 'HASH') {
                   3282:         while (my($key,$value) = each(%{$store})) {
                   3283:             $items.= &escape($key).'='.&escape($value).'&';
                   3284:         }
                   3285:     }
                   3286:     $items=~s/\&$//;
1.627     albertel 3287:     if ($critical) {
                   3288: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3289:     } else {
                   3290: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3291:     }
1.449     matthew  3292: }
                   3293: 
1.12      www      3294: # --------------------------------------------------------------- put interface
                   3295: 
                   3296: sub put {
1.134     albertel 3297:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3298:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3299:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3300:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3301:    my $items='';
1.800     albertel 3302:    foreach my $item (keys(%$storehash)) {
                   3303:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3304:    }
1.12      www      3305:    $items=~s/\&$//;
1.134     albertel 3306:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3307: }
                   3308: 
1.631     albertel 3309: # ------------------------------------------------------------ newput interface
                   3310: 
                   3311: sub newput {
                   3312:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3313:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3314:    if (!$uname) { $uname=$env{'user.name'}; }
                   3315:    my $uhome=&homeserver($uname,$udomain);
                   3316:    my $items='';
                   3317:    foreach my $key (keys(%$storehash)) {
                   3318:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3319:    }
                   3320:    $items=~s/\&$//;
                   3321:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3322: }
                   3323: 
                   3324: # ---------------------------------------------------------  putstore interface
                   3325: 
1.524     raeburn  3326: sub putstore {
1.715     albertel 3327:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3328:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3329:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3330:    my $uhome=&homeserver($uname,$udomain);
                   3331:    my $items='';
1.715     albertel 3332:    foreach my $key (keys(%$storehash)) {
                   3333:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3334:    }
1.715     albertel 3335:    $items=~s/\&$//;
1.716     albertel 3336:    my $esc_symb=&escape($symb);
                   3337:    my $esc_v=&escape($version);
1.715     albertel 3338:    my $reply =
1.716     albertel 3339:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3340: 	      $uhome);
                   3341:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3342:        # gfall back to way things use to be done
1.715     albertel 3343:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3344: 			    $uname);
1.524     raeburn  3345:    }
1.715     albertel 3346:    return $reply;
                   3347: }
                   3348: 
                   3349: sub old_putstore {
1.716     albertel 3350:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3351:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3352:     if (!$uname) { $uname=$env{'user.name'}; }
                   3353:     my $uhome=&homeserver($uname,$udomain);
                   3354:     my %newstorehash;
1.800     albertel 3355:     foreach my $item (keys(%$storehash)) {
                   3356: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3357: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3358:     }
                   3359:     my $items='';
                   3360:     my %allitems = ();
1.800     albertel 3361:     foreach my $item (keys(%newstorehash)) {
                   3362: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3363: 	    my $key = $1.':keys:'.$2;
                   3364: 	    $allitems{$key} .= $3.':';
                   3365: 	}
1.800     albertel 3366: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3367:     }
1.800     albertel 3368:     foreach my $item (keys(%allitems)) {
                   3369: 	$allitems{$item} =~ s/\:$//;
                   3370: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3371:     }
                   3372:     $items=~s/\&$//;
                   3373:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3374: }
                   3375: 
1.47      www      3376: # ------------------------------------------------------ critical put interface
                   3377: 
                   3378: sub cput {
1.134     albertel 3379:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3380:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3381:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3382:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3383:    my $items='';
1.800     albertel 3384:    foreach my $item (keys(%$storehash)) {
                   3385:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3386:    }
1.47      www      3387:    $items=~s/\&$//;
1.134     albertel 3388:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3389: }
                   3390: 
                   3391: # -------------------------------------------------------------- eget interface
                   3392: 
                   3393: sub eget {
1.133     albertel 3394:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3395:    my $items='';
1.800     albertel 3396:    foreach my $item (@$storearr) {
                   3397:        $items.=&escape($item).'&';
1.191     harris41 3398:    }
1.12      www      3399:    $items=~s/\&$//;
1.620     albertel 3400:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3401:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3402:    my $uhome=&homeserver($uname,$udomain);
                   3403:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3404:    my @pairs=split(/\&/,$rep);
                   3405:    my %returnhash=();
1.42      www      3406:    my $i=0;
1.800     albertel 3407:    foreach my $item (@$storearr) {
                   3408:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3409:       $i++;
1.191     harris41 3410:    }
1.12      www      3411:    return %returnhash;
                   3412: }
                   3413: 
1.667     albertel 3414: # ------------------------------------------------------------ tmpput interface
                   3415: sub tmpput {
1.802     raeburn  3416:     my ($storehash,$server,$context)=@_;
1.667     albertel 3417:     my $items='';
1.800     albertel 3418:     foreach my $item (keys(%$storehash)) {
                   3419: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3420:     }
                   3421:     $items=~s/\&$//;
1.802     raeburn  3422:     if (defined($context)) {
                   3423:         $items .= ':'.&escape($context);
                   3424:     }
1.667     albertel 3425:     return &reply("tmpput:$items",$server);
                   3426: }
                   3427: 
                   3428: # ------------------------------------------------------------ tmpget interface
                   3429: sub tmpget {
1.688     albertel 3430:     my ($token,$server)=@_;
                   3431:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3432:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3433:     my %returnhash;
                   3434:     foreach my $item (split(/\&/,$rep)) {
                   3435: 	my ($key,$value)=split(/=/,$item);
                   3436: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3437:     }
                   3438:     return %returnhash;
                   3439: }
                   3440: 
1.688     albertel 3441: # ------------------------------------------------------------ tmpget interface
                   3442: sub tmpdel {
                   3443:     my ($token,$server)=@_;
                   3444:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3445:     return &reply("tmpdel:$token",$server);
                   3446: }
                   3447: 
1.765     albertel 3448: # -------------------------------------------------- portfolio access checking
                   3449: 
                   3450: sub portfolio_access {
1.766     albertel 3451:     my ($requrl) = @_;
1.765     albertel 3452:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3453:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3454:     if ($result) {
                   3455:         my %setters;
                   3456:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3457:             my ($startblock,$endblock) =
                   3458:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3459:             if ($startblock && $endblock) {
                   3460:                 return 'B';
                   3461:             }
                   3462:         } else {
                   3463:             my ($startblock,$endblock) =
                   3464:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3465:             if ($startblock && $endblock) {
                   3466:                 return 'B';
                   3467:             }
                   3468:         }
                   3469:     }
1.765     albertel 3470:     if ($result eq 'ok') {
1.766     albertel 3471:        return 'F';
1.765     albertel 3472:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3473:        return 'A';
1.765     albertel 3474:     }
1.766     albertel 3475:     return '';
1.765     albertel 3476: }
                   3477: 
                   3478: sub get_portfolio_access {
1.767     albertel 3479:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3480: 
                   3481:     if (!ref($access_hash)) {
                   3482: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3483: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3484: 						   $file_name);
                   3485: 	$access_hash = $access_controls{$file_name};
                   3486:     }
                   3487: 
1.765     albertel 3488:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3489:     my $now = time;
                   3490:     if (ref($access_hash) eq 'HASH') {
                   3491:         foreach my $key (keys(%{$access_hash})) {
                   3492:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3493:             if ($start > $now) {
                   3494:                 next;
                   3495:             }
                   3496:             if ($end && $end<$now) {
                   3497:                 next;
                   3498:             }
                   3499:             if ($scope eq 'public') {
                   3500:                 $public = $key;
                   3501:                 last;
                   3502:             } elsif ($scope eq 'guest') {
                   3503:                 $guest = $key;
                   3504:             } elsif ($scope eq 'domains') {
                   3505:                 push(@domains,$key);
                   3506:             } elsif ($scope eq 'users') {
                   3507:                 push(@users,$key);
                   3508:             } elsif ($scope eq 'course') {
                   3509:                 push(@courses,$key);
                   3510:             } elsif ($scope eq 'group') {
                   3511:                 push(@groups,$key);
                   3512:             }
                   3513:         }
                   3514:         if ($public) {
                   3515:             return 'ok';
                   3516:         }
                   3517:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3518:             if ($guest) {
                   3519:                 return $guest;
                   3520:             }
                   3521:         } else {
                   3522:             if (@domains > 0) {
                   3523:                 foreach my $domkey (@domains) {
                   3524:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3525:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3526:                             return 'ok';
                   3527:                         }
                   3528:                     }
                   3529:                 }
                   3530:             }
                   3531:             if (@users > 0) {
                   3532:                 foreach my $userkey (@users) {
                   3533:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3534:                         return 'ok';
                   3535:                     }
                   3536:                 }
                   3537:             }
                   3538:             my %roleshash;
                   3539:             my @courses_and_groups = @courses;
                   3540:             push(@courses_and_groups,@groups); 
                   3541:             if (@courses_and_groups > 0) {
                   3542:                 my (%allgroups,%allroles); 
                   3543:                 my ($start,$end,$role,$sec,$group);
                   3544:                 foreach my $envkey (%env) {
1.811     albertel 3545:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3546:                         my $cid = $2.'_'.$3; 
                   3547:                         if ($1 eq 'gr') {
                   3548:                             $group = $4;
                   3549:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3550:                         } else {
                   3551:                             if ($4 eq '') {
                   3552:                                 $sec = 'none';
                   3553:                             } else {
                   3554:                                 $sec = $4;
                   3555:                             }
                   3556:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3557:                         }
1.811     albertel 3558:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3559:                         my $cid = $2.'_'.$3;
                   3560:                         if ($4 eq '') {
                   3561:                             $sec = 'none';
                   3562:                         } else {
                   3563:                             $sec = $4;
                   3564:                         }
                   3565:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3566:                     }
                   3567:                 }
                   3568:                 if (keys(%allroles) == 0) {
                   3569:                     return;
                   3570:                 }
                   3571:                 foreach my $key (@courses_and_groups) {
                   3572:                     my %content = %{$$access_hash{$key}};
                   3573:                     my $cnum = $content{'number'};
                   3574:                     my $cdom = $content{'domain'};
                   3575:                     my $cid = $cdom.'_'.$cnum;
                   3576:                     if (!exists($allroles{$cid})) {
                   3577:                         next;
                   3578:                     }    
                   3579:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3580:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3581:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3582:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3583:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3584:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3585:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3586:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3587:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3588:                                         if (grep/^all$/,@sections) {
                   3589:                                             return 'ok';
                   3590:                                         } else {
                   3591:                                             if (grep/^$sec$/,@sections) {
                   3592:                                                 return 'ok';
                   3593:                                             }
                   3594:                                         }
                   3595:                                     }
                   3596:                                 }
                   3597:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3598:                                     if (grep/^none$/,@groups) {
                   3599:                                         return 'ok';
                   3600:                                     }
                   3601:                                 } else {
                   3602:                                     if (grep/^all$/,@groups) {
                   3603:                                         return 'ok';
                   3604:                                     } 
                   3605:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3606:                                         if (grep/^$group$/,@groups) {
                   3607:                                             return 'ok';
                   3608:                                         }
                   3609:                                     }
                   3610:                                 } 
                   3611:                             }
                   3612:                         }
                   3613:                     }
                   3614:                 }
                   3615:             }
                   3616:             if ($guest) {
                   3617:                 return $guest;
                   3618:             }
                   3619:         }
                   3620:     }
                   3621:     return;
                   3622: }
                   3623: 
                   3624: sub course_group_datechecker {
                   3625:     my ($dates,$now,$status) = @_;
                   3626:     my ($start,$end) = split(/\./,$dates);
                   3627:     if (!$start && !$end) {
                   3628:         return 'ok';
                   3629:     }
                   3630:     if (grep/^active$/,@{$status}) {
                   3631:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3632:             return 'ok';
                   3633:         }
                   3634:     }
                   3635:     if (grep/^previous$/,@{$status}) {
                   3636:         if ($end > $now ) {
                   3637:             return 'ok';
                   3638:         }
                   3639:     }
                   3640:     if (grep/^future$/,@{$status}) {
                   3641:         if ($start > $now) {
                   3642:             return 'ok';
                   3643:         }
                   3644:     }
                   3645:     return; 
                   3646: }
                   3647: 
                   3648: sub parse_portfolio_url {
                   3649:     my ($url) = @_;
                   3650: 
                   3651:     my ($type,$udom,$unum,$group,$file_name);
                   3652:     
1.823     albertel 3653:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3654: 	$type = 1;
                   3655:         $udom = $1;
                   3656:         $unum = $2;
                   3657:         $file_name = $3;
1.823     albertel 3658:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3659: 	$type = 2;
                   3660:         $udom = $1;
                   3661:         $unum = $2;
                   3662:         $group = $3;
                   3663:         $file_name = $3.'/'.$4;
                   3664:     }
                   3665:     if (wantarray) {
                   3666: 	return ($type,$udom,$unum,$file_name,$group);
                   3667:     }
                   3668:     return $type;
                   3669: }
                   3670: 
                   3671: sub is_portfolio_url {
                   3672:     my ($url) = @_;
                   3673:     return scalar(&parse_portfolio_url($url));
                   3674: }
                   3675: 
1.798     raeburn  3676: sub is_portfolio_file {
                   3677:     my ($file) = @_;
1.820     raeburn  3678:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3679:         return 1;
                   3680:     }
                   3681:     return;
                   3682: }
                   3683: 
                   3684: 
1.341     www      3685: # ---------------------------------------------- Custom access rule evaluation
                   3686: 
                   3687: sub customaccess {
                   3688:     my ($priv,$uri)=@_;
1.807     albertel 3689:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3690:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3691:     $udom = &LONCAPA::clean_domain($udom);
                   3692:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3693:     my $access=0;
1.800     albertel 3694:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3695: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3696:         if ($role) {
                   3697: 	   if ($role ne $urole) { next; }
                   3698:         }
1.800     albertel 3699:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3700:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3701:             if ($tdom) {
                   3702: 		if ($tdom ne $udom) { next; }
                   3703:             }
                   3704:             if ($tcrs) {
                   3705: 		if ($tcrs ne $ucrs) { next; }
                   3706:             }
                   3707:             if ($tsec) {
                   3708: 		if ($tsec ne $usec) { next; }
                   3709:             }
                   3710:             $access=($effect eq 'allow');
                   3711:             last;
1.342     www      3712:         }
1.402     bowersj2 3713: 	if ($realm eq '' && $role eq '') {
                   3714:             $access=($effect eq 'allow');
                   3715: 	}
1.341     www      3716:     }
                   3717:     return $access;
                   3718: }
                   3719: 
1.103     harris41 3720: # ------------------------------------------------- Check for a user privilege
1.12      www      3721: 
                   3722: sub allowed {
1.810     raeburn  3723:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3724:     my $ver_orguri=$uri;
1.439     www      3725:     $uri=&deversion($uri);
1.152     www      3726:     my $orguri=$uri;
1.52      www      3727:     $uri=&declutter($uri);
1.809     raeburn  3728: 
1.810     raeburn  3729:     if ($priv eq 'evb') {
                   3730: # Evade communication block restrictions for specified role in a course
                   3731:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3732:             return $1;
                   3733:         } else {
                   3734:             return;
                   3735:         }
                   3736:     }
                   3737: 
1.620     albertel 3738:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3739: # Free bre access to adm and meta resources
1.775     albertel 3740:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3741: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3742: 	&& ($priv eq 'bre')) {
1.14      www      3743: 	return 'F';
1.159     www      3744:     }
                   3745: 
1.545     banghart 3746: # Free bre access to user's own portfolio contents
1.714     raeburn  3747:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3748:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3749: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3750:         my %setters;
                   3751:         my ($startblock,$endblock) = 
                   3752:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3753:         if ($startblock && $endblock) {
                   3754:             return 'B';
                   3755:         } else {
                   3756:             return 'F';
                   3757:         }
1.545     banghart 3758:     }
                   3759: 
1.762     raeburn  3760: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3761:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3762:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3763:         if (exists($env{'request.course.id'})) {
                   3764:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3765:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3766:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3767:                 my $courseprivid=$env{'request.course.id'};
                   3768:                 $courseprivid=~s/\_/\//;
                   3769:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3770:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3771:                     return $1; 
1.762     raeburn  3772:                 } else {
                   3773:                     if ($env{'request.course.sec'}) {
                   3774:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3775:                     }
                   3776:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3777:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3778:                         return $2;
                   3779:                     }
1.714     raeburn  3780:                 }
                   3781:             }
                   3782:         }
                   3783:     }
                   3784: 
1.159     www      3785: # Free bre to public access
                   3786: 
                   3787:     if ($priv eq 'bre') {
1.238     www      3788:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3789: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3790:            return 'F'; 
                   3791:         }
1.238     www      3792:         if ($copyright eq 'priv') {
                   3793:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3794: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3795: 		return '';
                   3796:             }
                   3797:         }
                   3798:         if ($copyright eq 'domain') {
                   3799:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3800: 	    unless (($env{'user.domain'} eq $1) ||
                   3801:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3802: 		return '';
                   3803:             }
1.262     matthew  3804:         }
1.620     albertel 3805:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3806:             # Library role, so allow browsing of resources in this domain.
                   3807:             return 'F';
1.238     www      3808:         }
1.341     www      3809:         if ($copyright eq 'custom') {
                   3810: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3811:         }
1.14      www      3812:     }
1.264     matthew  3813:     # Domain coordinator is trying to create a course
1.620     albertel 3814:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3815:         # uri is the requested domain in this case.
                   3816:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3817:         # a role of dc for the domain in question.
1.620     albertel 3818:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3819:     }
1.29      www      3820: 
1.52      www      3821:     my $thisallowed='';
                   3822:     my $statecond=0;
                   3823:     my $courseprivid='';
                   3824: 
                   3825: # Course
                   3826: 
1.620     albertel 3827:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3828:        $thisallowed.=$1;
                   3829:     }
1.29      www      3830: 
1.52      www      3831: # Domain
                   3832: 
1.620     albertel 3833:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3834:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3835:        $thisallowed.=$1;
                   3836:     }
1.52      www      3837: 
                   3838: # Course: uri itself is a course
1.66      www      3839:     my $courseuri=$uri;
                   3840:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3841:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3842: 
1.620     albertel 3843:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3844:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3845:        $thisallowed.=$1;
                   3846:     }
1.29      www      3847: 
1.665     albertel 3848: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3849: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3850:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3851: 	$thisallowed='';
1.671     raeburn  3852:         my ($match)=&is_on_map($uri);
                   3853:         if ($match) {
                   3854:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3855:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3856:                 $thisallowed.=$1;
                   3857:             }
                   3858:         } else {
1.705     albertel 3859:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3860:             if ($refuri) {
                   3861:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3862:                     $thisallowed='F';
1.671     raeburn  3863:                 } else {
                   3864:                     $refuri=&declutter($refuri);
                   3865:                     my ($match) = &is_on_map($refuri);
                   3866:                     if ($match) {
                   3867:                         $thisallowed='F';
                   3868:                     }
1.669     raeburn  3869:                 }
1.671     raeburn  3870:             }
                   3871:         }
1.314     www      3872:     }
1.492     albertel 3873: 
1.766     albertel 3874:     if ($priv eq 'bre'
                   3875: 	&& $thisallowed ne 'F' 
                   3876: 	&& $thisallowed ne '2'
                   3877: 	&& &is_portfolio_url($uri)) {
                   3878: 	$thisallowed = &portfolio_access($uri);
                   3879:     }
                   3880:     
1.52      www      3881: # Full access at system, domain or course-wide level? Exit.
1.29      www      3882: 
                   3883:     if ($thisallowed=~/F/) {
                   3884: 	return 'F';
                   3885:     }
                   3886: 
1.52      www      3887: # If this is generating or modifying users, exit with special codes
1.29      www      3888: 
1.643     www      3889:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3890: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3891: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3892: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3893: 	    unless ($auname) { return $thisallowed; }
                   3894: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3895: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3896: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3897: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3898: 	}
1.52      www      3899: 	return $thisallowed;
                   3900:     }
                   3901: #
1.103     harris41 3902: # Gathered so far: system, domain and course wide privileges
1.52      www      3903: #
                   3904: # Course: See if uri or referer is an individual resource that is part of 
                   3905: # the course
                   3906: 
1.620     albertel 3907:     if ($env{'request.course.id'}) {
1.232     www      3908: 
1.620     albertel 3909:        $courseprivid=$env{'request.course.id'};
                   3910:        if ($env{'request.course.sec'}) {
                   3911:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3912:        }
                   3913:        $courseprivid=~s/\_/\//;
                   3914:        my $checkreferer=1;
1.232     www      3915:        my ($match,$cond)=&is_on_map($uri);
                   3916:        if ($match) {
                   3917:            $statecond=$cond;
1.620     albertel 3918:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3919:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3920:                $thisallowed.=$1;
                   3921:                $checkreferer=0;
                   3922:            }
1.29      www      3923:        }
1.83      www      3924:        
1.148     www      3925:        if ($checkreferer) {
1.620     albertel 3926: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3927:             unless ($refuri) {
1.800     albertel 3928:                 foreach my $key (keys(%env)) {
                   3929: 		    if ($key=~/^httpref\..*\*/) {
                   3930: 			my $pattern=$key;
1.156     www      3931:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3932:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3933:                         $pattern=~s/\//\\\//g;
1.152     www      3934:                         if ($orguri=~/$pattern/) {
1.800     albertel 3935: 			    $refuri=$env{$key};
1.148     www      3936:                         }
                   3937:                     }
1.191     harris41 3938:                 }
1.148     www      3939:             }
1.232     www      3940: 
1.148     www      3941:          if ($refuri) { 
1.152     www      3942: 	  $refuri=&declutter($refuri);
1.232     www      3943:           my ($match,$cond)=&is_on_map($refuri);
                   3944:             if ($match) {
                   3945:               my $refstatecond=$cond;
1.620     albertel 3946:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3947:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3948:                   $thisallowed.=$1;
1.53      www      3949:                   $uri=$refuri;
                   3950:                   $statecond=$refstatecond;
1.52      www      3951:               }
                   3952:           }
1.148     www      3953:         }
1.29      www      3954:        }
1.52      www      3955:    }
1.29      www      3956: 
1.52      www      3957: #
1.103     harris41 3958: # Gathered now: all privileges that could apply, and condition number
1.52      www      3959: # 
                   3960: #
                   3961: # Full or no access?
                   3962: #
1.29      www      3963: 
1.52      www      3964:     if ($thisallowed=~/F/) {
                   3965: 	return 'F';
                   3966:     }
1.29      www      3967: 
1.52      www      3968:     unless ($thisallowed) {
                   3969:         return '';
                   3970:     }
1.29      www      3971: 
1.52      www      3972: # Restrictions exist, deal with them
                   3973: #
                   3974: #   C:according to course preferences
                   3975: #   R:according to resource settings
                   3976: #   L:unless locked
                   3977: #   X:according to user session state
                   3978: #
                   3979: 
                   3980: # Possibly locked functionality, check all courses
1.54      www      3981: # Locks might take effect only after 10 minutes cache expiration for other
                   3982: # courses, and 2 minutes for current course
1.52      www      3983: 
                   3984:     my $envkey;
                   3985:     if ($thisallowed=~/L/) {
1.620     albertel 3986:         foreach $envkey (keys %env) {
1.54      www      3987:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3988:                my $courseid=$2;
                   3989:                my $roleid=$1.'.'.$2;
1.92      www      3990:                $courseid=~s/^\///;
1.54      www      3991:                my $expiretime=600;
1.620     albertel 3992:                if ($env{'request.role'} eq $roleid) {
1.54      www      3993: 		  $expiretime=120;
                   3994:                }
                   3995: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3996:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3997:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3998: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3999:                }
1.620     albertel 4000:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4001:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4002: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4003:                        &log($env{'user.domain'},$env{'user.name'},
                   4004:                             $env{'user.home'},
1.57      www      4005:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4006:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4007:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4008: 		       return '';
                   4009:                    }
                   4010:                }
1.620     albertel 4011:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4012:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4013: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4014:                        &log($env{'user.domain'},$env{'user.name'},
                   4015:                             $env{'user.home'},
1.57      www      4016:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4017:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4018:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4019: 		       return '';
                   4020:                    }
                   4021:                }
                   4022: 	   }
1.29      www      4023:        }
1.52      www      4024:     }
                   4025:    
                   4026: #
                   4027: # Rest of the restrictions depend on selected course
                   4028: #
                   4029: 
1.620     albertel 4030:     unless ($env{'request.course.id'}) {
1.766     albertel 4031: 	if ($thisallowed eq 'A') {
                   4032: 	    return 'A';
1.814     raeburn  4033:         } elsif ($thisallowed eq 'B') {
                   4034:             return 'B';
1.766     albertel 4035: 	} else {
                   4036: 	    return '1';
                   4037: 	}
1.52      www      4038:     }
1.29      www      4039: 
1.52      www      4040: #
                   4041: # Now user is definitely in a course
                   4042: #
1.53      www      4043: 
                   4044: 
                   4045: # Course preferences
                   4046: 
                   4047:    if ($thisallowed=~/C/) {
1.620     albertel 4048:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4049:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4050:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4051: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4052: 	   if ($priv ne 'pch') { 
                   4053: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4054: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4055: 			$env{'request.course.id'});
                   4056: 	   }
1.237     www      4057:            return '';
                   4058:        }
                   4059: 
1.620     albertel 4060:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4061: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4062: 	   if ($priv ne 'pch') { 
                   4063: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4064: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4065: 			$env{'request.course.id'});
                   4066: 	   }
1.54      www      4067:            return '';
                   4068:        }
1.53      www      4069:    }
                   4070: 
                   4071: # Resource preferences
                   4072: 
                   4073:    if ($thisallowed=~/R/) {
1.620     albertel 4074:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4075:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4076: 	   if ($priv ne 'pch') { 
                   4077: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4078: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4079: 	   }
                   4080: 	   return '';
1.54      www      4081:        }
1.53      www      4082:    }
1.30      www      4083: 
1.246     www      4084: # Restricted by state or randomout?
1.30      www      4085: 
1.52      www      4086:    if ($thisallowed=~/X/) {
1.620     albertel 4087:       if ($env{'acc.randomout'}) {
1.579     albertel 4088: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4089:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4090:             return ''; 
                   4091:          }
1.247     www      4092:       }
                   4093:       if (&condval($statecond)) {
1.52      www      4094: 	 return '2';
                   4095:       } else {
                   4096:          return '';
                   4097:       }
                   4098:    }
1.30      www      4099: 
1.766     albertel 4100:     if ($thisallowed eq 'A') {
                   4101: 	return 'A';
1.814     raeburn  4102:     } elsif ($thisallowed eq 'B') {
                   4103:         return 'B';
1.766     albertel 4104:     }
1.52      www      4105:    return 'F';
1.232     www      4106: }
                   4107: 
1.710     albertel 4108: sub split_uri_for_cond {
                   4109:     my $uri=&deversion(&declutter(shift));
                   4110:     my @uriparts=split(/\//,$uri);
                   4111:     my $filename=pop(@uriparts);
                   4112:     my $pathname=join('/',@uriparts);
                   4113:     return ($pathname,$filename);
                   4114: }
1.232     www      4115: # --------------------------------------------------- Is a resource on the map?
                   4116: 
                   4117: sub is_on_map {
1.710     albertel 4118:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4119:     #Trying to find the conditional for the file
1.620     albertel 4120:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4121: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4122:     if ($match) {
1.289     bowersj2 4123: 	return (1,$1);
                   4124:     } else {
1.434     www      4125: 	return (0,0);
1.289     bowersj2 4126:     }
1.12      www      4127: }
                   4128: 
1.427     www      4129: # --------------------------------------------------------- Get symb from alias
                   4130: 
                   4131: sub get_symb_from_alias {
                   4132:     my $symb=shift;
                   4133:     my ($map,$resid,$url)=&decode_symb($symb);
                   4134: # Already is a symb
                   4135:     if ($url) { return $symb; }
                   4136: # Must be an alias
                   4137:     my $aliassymb='';
                   4138:     my %bighash;
1.620     albertel 4139:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4140:                             &GDBM_READER(),0640)) {
                   4141:         my $rid=$bighash{'mapalias_'.$symb};
                   4142: 	if ($rid) {
                   4143: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4144: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4145: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4146: 	}
                   4147:         untie %bighash;
                   4148:     }
                   4149:     return $aliassymb;
                   4150: }
                   4151: 
1.12      www      4152: # ----------------------------------------------------------------- Define Role
                   4153: 
                   4154: sub definerole {
                   4155:   if (allowed('mcr','/')) {
                   4156:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4157:     foreach my $role (split(':',$sysrole)) {
                   4158: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4159:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4160:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4161: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4162:                return "refused:s:$crole&$cqual"; 
                   4163:             }
                   4164:         }
1.191     harris41 4165:     }
1.800     albertel 4166:     foreach my $role (split(':',$domrole)) {
                   4167: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4168:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4169:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4170: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4171:                return "refused:d:$crole&$cqual"; 
                   4172:             }
                   4173:         }
1.191     harris41 4174:     }
1.800     albertel 4175:     foreach my $role (split(':',$courole)) {
                   4176: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4177:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4178:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4179: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4180:                return "refused:c:$crole&$cqual"; 
                   4181:             }
                   4182:         }
1.191     harris41 4183:     }
1.620     albertel 4184:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4185:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4186: 	        "rolesdef_$rolename=".
                   4187:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4188:     return reply($command,$env{'user.home'});
1.12      www      4189:   } else {
                   4190:     return 'refused';
                   4191:   }
1.105     harris41 4192: }
                   4193: 
                   4194: # ---------------- Make a metadata query against the network of library servers
                   4195: 
                   4196: sub metadata_query {
1.244     matthew  4197:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4198:     my %rhash;
1.845     albertel 4199:     my %libserv = &all_library();
1.244     matthew  4200:     my @server_list = (defined($server_array) ? @$server_array
                   4201:                                               : keys(%libserv) );
                   4202:     for my $server (@server_list) {
1.118     harris41 4203: 	unless ($custom or $customshow) {
                   4204: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4205: 	    $rhash{$server}=$reply;
                   4206: 	}
                   4207: 	else {
                   4208: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4209: 			     &escape($custom).':'.&escape($customshow),
                   4210: 			     $server);
                   4211: 	    $rhash{$server}=$reply;
                   4212: 	}
1.112     harris41 4213:     }
1.118     harris41 4214:     return \%rhash;
1.240     www      4215: }
                   4216: 
                   4217: # ----------------------------------------- Send log queries and wait for reply
                   4218: 
                   4219: sub log_query {
                   4220:     my ($uname,$udom,$query,%filters)=@_;
                   4221:     my $uhome=&homeserver($uname,$udom);
                   4222:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4223:     my $uhost=&hostname($uhome);
1.800     albertel 4224:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4225:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4226:                        $uhome);
1.479     albertel 4227:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4228:     return get_query_reply($queryid);
                   4229: }
                   4230: 
1.818     raeburn  4231: # -------------------------- Update MySQL table for portfolio file
                   4232: 
                   4233: sub update_portfolio_table {
1.821     raeburn  4234:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4235:     my $homeserver = &homeserver($uname,$udom);
                   4236:     my $queryid=
1.821     raeburn  4237:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4238:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4239:     my $reply = &get_query_reply($queryid);
                   4240:     return $reply;
                   4241: }
                   4242: 
1.508     raeburn  4243: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4244: 
                   4245: sub fetch_enrollment_query {
1.511     raeburn  4246:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4247:     my $homeserver;
1.547     raeburn  4248:     my $maxtries = 1;
1.508     raeburn  4249:     if ($context eq 'automated') {
                   4250:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4251:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4252:     } else {
                   4253:         $homeserver = &homeserver($cnum,$dom);
                   4254:     }
1.838     albertel 4255:     my $host=&hostname($homeserver);
1.506     raeburn  4256:     my $cmd = '';
1.800     albertel 4257:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4258:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4259:     }
                   4260:     $cmd =~ s/%%$//;
                   4261:     $cmd = &escape($cmd);
                   4262:     my $query = 'fetchenrollment';
1.620     albertel 4263:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4264:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4265:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4266:         return 'error: '.$queryid;
                   4267:     }
1.506     raeburn  4268:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4269:     my $tries = 1;
                   4270:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4271:         $reply = &get_query_reply($queryid);
                   4272:         $tries ++;
                   4273:     }
1.526     raeburn  4274:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4275:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4276:     } else {
1.515     raeburn  4277:         my @responses = split/:/,$reply;
                   4278:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4279:             foreach my $line (@responses) {
                   4280:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4281:                 $$replyref{$key} = $value;
                   4282:             }
                   4283:         } else {
1.506     raeburn  4284:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4285:             foreach my $line (@responses) {
                   4286:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4287:                 $$replyref{$key} = $value;
                   4288:                 if ($value > 0) {
1.800     albertel 4289:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4290:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4291:                         my $destname = $pathname.'/'.$filename;
                   4292:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4293:                         if ($xml_classlist =~ /^error/) {
                   4294:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4295:                         } else {
1.506     raeburn  4296:                             if ( open(FILE,">$destname") ) {
                   4297:                                 print FILE &unescape($xml_classlist);
                   4298:                                 close(FILE);
1.526     raeburn  4299:                             } else {
                   4300:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4301:                             }
                   4302:                         }
                   4303:                     }
                   4304:                 }
                   4305:             }
                   4306:         }
                   4307:         return 'ok';
                   4308:     }
                   4309:     return 'error';
                   4310: }
                   4311: 
1.242     www      4312: sub get_query_reply {
                   4313:     my $queryid=shift;
1.240     www      4314:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4315:     my $reply='';
                   4316:     for (1..100) {
                   4317: 	sleep 2;
                   4318:         if (-e $replyfile.'.end') {
1.448     albertel 4319: 	    if (open(my $fh,$replyfile)) {
1.240     www      4320:                $reply.=<$fh>;
1.448     albertel 4321:                close($fh);
1.240     www      4322: 	   } else { return 'error: reply_file_error'; }
1.242     www      4323:            return &unescape($reply);
                   4324: 	}
1.240     www      4325:     }
1.242     www      4326:     return 'timeout:'.$queryid;
1.240     www      4327: }
                   4328: 
                   4329: sub courselog_query {
1.241     www      4330: #
                   4331: # possible filters:
                   4332: # url: url or symb
                   4333: # username
                   4334: # domain
                   4335: # action: view, submit, grade
                   4336: # start: timestamp
                   4337: # end: timestamp
                   4338: #
1.240     www      4339:     my (%filters)=@_;
1.620     albertel 4340:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4341:     if ($filters{'url'}) {
                   4342: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4343:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4344:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4345:     }
1.620     albertel 4346:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4347:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4348:     return &log_query($cname,$cdom,'courselog',%filters);
                   4349: }
                   4350: 
                   4351: sub userlog_query {
                   4352:     my ($uname,$udom,%filters)=@_;
                   4353:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4354: }
                   4355: 
1.506     raeburn  4356: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4357: 
                   4358: sub auto_run {
1.508     raeburn  4359:     my ($cnum,$cdom) = @_;
                   4360:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4361:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4362:     return $response;
                   4363: }
1.776     albertel 4364: 
1.506     raeburn  4365: sub auto_get_sections {
1.508     raeburn  4366:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4367:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4368:     my @secs = ();
1.511     raeburn  4369:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4370:     unless ($response eq 'refused') {
                   4371:         @secs = split/:/,$response;
                   4372:     }
                   4373:     return @secs;
                   4374: }
1.776     albertel 4375: 
1.506     raeburn  4376: sub auto_new_course {
1.508     raeburn  4377:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4378:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4379:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4380:     return $response;
                   4381: }
1.776     albertel 4382: 
1.506     raeburn  4383: sub auto_validate_courseID {
1.508     raeburn  4384:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4385:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4386:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4387:     return $response;
                   4388: }
1.776     albertel 4389: 
1.506     raeburn  4390: sub auto_create_password {
1.508     raeburn  4391:     my ($cnum,$cdom,$authparam) = @_;
                   4392:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4393:     my $create_passwd = 0;
                   4394:     my $authchk = '';
1.511     raeburn  4395:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4396:     if ($response eq 'refused') {
                   4397:         $authchk = 'refused';
                   4398:     } else {
                   4399:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4400:     }
                   4401:     return ($authparam,$create_passwd,$authchk);
                   4402: }
                   4403: 
1.706     raeburn  4404: sub auto_photo_permission {
                   4405:     my ($cnum,$cdom,$students) = @_;
                   4406:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4407:     my ($outcome,$perm_reqd,$conditions) = 
                   4408: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4409:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4410: 	return (undef,undef);
                   4411:     }
1.706     raeburn  4412:     return ($outcome,$perm_reqd,$conditions);
                   4413: }
                   4414: 
                   4415: sub auto_checkphotos {
                   4416:     my ($uname,$udom,$pid) = @_;
                   4417:     my $homeserver = &homeserver($uname,$udom);
                   4418:     my ($result,$resulttype);
                   4419:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4420: 				   &escape($uname).':'.&escape($pid),
                   4421: 				   $homeserver));
1.709     albertel 4422:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4423: 	return (undef,undef);
                   4424:     }
1.706     raeburn  4425:     if ($outcome) {
                   4426:         ($result,$resulttype) = split(/:/,$outcome);
                   4427:     } 
                   4428:     return ($result,$resulttype);
                   4429: }
                   4430: 
                   4431: sub auto_photochoice {
                   4432:     my ($cnum,$cdom) = @_;
                   4433:     my $homeserver = &homeserver($cnum,$cdom);
                   4434:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4435: 						       &escape($cdom),
                   4436: 						       $homeserver)));
1.709     albertel 4437:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4438: 	return (undef,undef);
                   4439:     }
1.706     raeburn  4440:     return ($update,$comment);
                   4441: }
                   4442: 
                   4443: sub auto_photoupdate {
                   4444:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4445:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4446:     my $host=&hostname($homeserver);
1.706     raeburn  4447:     my $cmd = '';
                   4448:     my $maxtries = 1;
1.800     albertel 4449:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4450:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4451:     }
                   4452:     $cmd =~ s/%%$//;
                   4453:     $cmd = &escape($cmd);
                   4454:     my $query = 'institutionalphotos';
                   4455:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4456:     unless ($queryid=~/^\Q$host\E\_/) {
                   4457:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4458:         return 'error: '.$queryid;
                   4459:     }
                   4460:     my $reply = &get_query_reply($queryid);
                   4461:     my $tries = 1;
                   4462:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4463:         $reply = &get_query_reply($queryid);
                   4464:         $tries ++;
                   4465:     }
                   4466:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4467:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4468:     } else {
                   4469:         my @responses = split(/:/,$reply);
                   4470:         my $outcome = shift(@responses); 
                   4471:         foreach my $item (@responses) {
                   4472:             my ($key,$value) = split(/=/,$item);
                   4473:             $$photo{$key} = $value;
                   4474:         }
                   4475:         return $outcome;
                   4476:     }
                   4477:     return 'error';
                   4478: }
                   4479: 
1.521     raeburn  4480: sub auto_instcode_format {
1.793     albertel 4481:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4482: 	$cat_order) = @_;
1.521     raeburn  4483:     my $courses = '';
1.772     raeburn  4484:     my @homeservers;
1.521     raeburn  4485:     if ($caller eq 'global') {
1.841     albertel 4486: 	my %servers = &get_servers($codedom,'library');
                   4487: 	foreach my $tryserver (keys(%servers)) {
                   4488: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4489: 		push(@homeservers,$tryserver);
                   4490: 	    }
1.584     raeburn  4491:         }
1.521     raeburn  4492:     } else {
1.772     raeburn  4493:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4494:     }
1.793     albertel 4495:     foreach my $code (keys(%{$instcodes})) {
                   4496:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4497:     }
                   4498:     chop($courses);
1.772     raeburn  4499:     my $ok_response = 0;
                   4500:     my $response;
                   4501:     while (@homeservers > 0 && $ok_response == 0) {
                   4502:         my $server = shift(@homeservers); 
                   4503:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4504:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4505:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4506: 		split/:/,$response;
1.772     raeburn  4507:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4508:             push(@{$codetitles},&str2array($codetitles_str));
                   4509:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4510:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4511:             $ok_response = 1;
                   4512:         }
                   4513:     }
                   4514:     if ($ok_response) {
1.521     raeburn  4515:         return 'ok';
1.772     raeburn  4516:     } else {
                   4517:         return $response;
1.521     raeburn  4518:     }
                   4519: }
                   4520: 
1.792     raeburn  4521: sub auto_instcode_defaults {
                   4522:     my ($domain,$returnhash,$code_order) = @_;
                   4523:     my @homeservers;
1.841     albertel 4524: 
                   4525:     my %servers = &get_servers($domain,'library');
                   4526:     foreach my $tryserver (keys(%servers)) {
                   4527: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4528: 	    push(@homeservers,$tryserver);
                   4529: 	}
1.792     raeburn  4530:     }
1.841     albertel 4531: 
1.792     raeburn  4532:     my $response;
1.841     albertel 4533:     foreach my $server (@homeservers) {
1.792     raeburn  4534:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4535:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4536: 	
                   4537: 	foreach my $pair (split(/\&/,$response)) {
                   4538: 	    my ($name,$value)=split(/\=/,$pair);
                   4539: 	    if ($name eq 'code_order') {
                   4540: 		@{$code_order} = split(/\&/,&unescape($value));
                   4541: 	    } else {
                   4542: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4543: 	    }
                   4544: 	}
                   4545: 	return 'ok';
1.792     raeburn  4546:     }
1.841     albertel 4547: 
                   4548:     return $response;
1.792     raeburn  4549: } 
                   4550: 
1.777     albertel 4551: sub auto_validate_class_sec {
1.773     raeburn  4552:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4553:     my $homeserver = &homeserver($cnum,$cdom);
                   4554:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4555:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4556:     return $response;
                   4557: }
                   4558: 
1.679     raeburn  4559: # ------------------------------------------------------- Course Group routines
                   4560: 
                   4561: sub get_coursegroups {
1.809     raeburn  4562:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4563:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4564: }
                   4565: 
1.679     raeburn  4566: sub modify_coursegroup {
                   4567:     my ($cdom,$cnum,$groupsettings) = @_;
                   4568:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4569: }
                   4570: 
1.809     raeburn  4571: sub toggle_coursegroup_status {
                   4572:     my ($cdom,$cnum,$group,$action) = @_;
                   4573:     my ($from_namespace,$to_namespace);
                   4574:     if ($action eq 'delete') {
                   4575:         $from_namespace = 'coursegroups';
                   4576:         $to_namespace = 'deleted_groups';
                   4577:     } else {
                   4578:         $from_namespace = 'deleted_groups';
                   4579:         $to_namespace = 'coursegroups';
                   4580:     }
                   4581:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4582:     if (my $tmp = &error(%curr_group)) {
                   4583:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4584:         return ('read error',$tmp);
                   4585:     } else {
                   4586:         my %savedsettings = %curr_group; 
1.809     raeburn  4587:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4588:         my $deloutcome;
                   4589:         if ($result eq 'ok') {
1.809     raeburn  4590:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4591:         } else {
                   4592:             return ('write error',$result);
                   4593:         }
                   4594:         if ($deloutcome eq 'ok') {
                   4595:             return 'ok';
                   4596:         } else {
                   4597:             return ('delete error',$deloutcome);
                   4598:         }
                   4599:     }
                   4600: }
                   4601: 
1.679     raeburn  4602: sub modify_group_roles {
                   4603:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4604:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4605:     my $role = 'gr/'.&escape($userprivs);
                   4606:     my ($uname,$udom) = split(/:/,$user);
                   4607:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4608:     if ($result eq 'ok') {
                   4609:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4610:     }
1.679     raeburn  4611:     return $result;
                   4612: }
                   4613: 
                   4614: sub modify_coursegroup_membership {
                   4615:     my ($cdom,$cnum,$membership) = @_;
                   4616:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4617:     return $result;
                   4618: }
                   4619: 
1.682     raeburn  4620: sub get_active_groups {
                   4621:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4622:     my $now = time;
                   4623:     my %groups = ();
                   4624:     foreach my $key (keys(%env)) {
1.811     albertel 4625:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4626:             my ($start,$end) = split(/\./,$env{$key});
                   4627:             if (($end!=0) && ($end<$now)) { next; }
                   4628:             if (($start!=0) && ($start>$now)) { next; }
                   4629:             if ($1 eq $cdom && $2 eq $cnum) {
                   4630:                 $groups{$3} = $env{$key} ;
                   4631:             }
                   4632:         }
                   4633:     }
                   4634:     return %groups;
                   4635: }
                   4636: 
1.683     raeburn  4637: sub get_group_membership {
                   4638:     my ($cdom,$cnum,$group) = @_;
                   4639:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4640: }
                   4641: 
                   4642: sub get_users_groups {
                   4643:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4644:     my @usersgroups;
1.683     raeburn  4645:     my $cachetime=1800;
                   4646: 
                   4647:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4648:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4649:     if (defined($cached)) {
1.734     albertel 4650:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4651:     } else {  
                   4652:         $grouplist = '';
1.816     raeburn  4653:         my $courseurl = &courseid_to_courseurl($courseid);
                   4654:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4655:         my $access_end = $env{'course.'.$courseid.
                   4656:                               '.default_enrollment_end_date'};
                   4657:         my $now = time;
                   4658:         foreach my $key (keys(%roleshash)) {
                   4659:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4660:                 my $group = $1;
                   4661:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4662:                     my $start = $2;
                   4663:                     my $end = $1;
                   4664:                     if ($start == -1) { next; } # deleted from group
                   4665:                     if (($start!=0) && ($start>$now)) { next; }
                   4666:                     if (($end!=0) && ($end<$now)) {
                   4667:                         if ($access_end && $access_end < $now) {
                   4668:                             if ($access_end - $end < 86400) {
                   4669:                                 push(@usersgroups,$group);
1.733     raeburn  4670:                             }
                   4671:                         }
1.817     raeburn  4672:                         next;
1.733     raeburn  4673:                     }
1.817     raeburn  4674:                     push(@usersgroups,$group);
1.683     raeburn  4675:                 }
                   4676:             }
                   4677:         }
1.817     raeburn  4678:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4679:         $grouplist = join(':',@usersgroups);
                   4680:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4681:     }
1.733     raeburn  4682:     return @usersgroups;
1.683     raeburn  4683: }
                   4684: 
                   4685: sub devalidate_getgroups_cache {
                   4686:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4687:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4688: 
1.683     raeburn  4689:     my $hashid="$udom:$uname:$courseid";
                   4690:     &devalidate_cache_new('getgroups',$hashid);
                   4691: }
                   4692: 
1.12      www      4693: # ------------------------------------------------------------------ Plain Text
                   4694: 
                   4695: sub plaintext {
1.742     raeburn  4696:     my ($short,$type,$cid) = @_;
1.758     albertel 4697:     if ($short =~ /^cr/) {
                   4698: 	return (split('/',$short))[-1];
                   4699:     }
1.742     raeburn  4700:     if (!defined($cid)) {
                   4701:         $cid = $env{'request.course.id'};
                   4702:     }
                   4703:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4704:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4705:                                           '.plaintext'});
                   4706:     }
                   4707:     my %rolenames = (
                   4708:                       Course => 'std',
                   4709:                       Group => 'alt1',
                   4710:                     );
                   4711:     if (defined($type) && 
                   4712:          defined($rolenames{$type}) && 
                   4713:          defined($prp{$short}{$rolenames{$type}})) {
                   4714:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4715:     } else {
                   4716:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4717:     }
1.12      www      4718: }
                   4719: 
                   4720: # ----------------------------------------------------------------- Assign Role
                   4721: 
                   4722: sub assignrole {
1.357     www      4723:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4724:     my $mrole;
                   4725:     if ($role =~ /^cr\//) {
1.393     www      4726:         my $cwosec=$url;
1.811     albertel 4727:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4728: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4729:            &logthis('Refused custom assignrole: '.
                   4730:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4731: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4732:            return 'refused'; 
                   4733:         }
1.21      www      4734:         $mrole='cr';
1.678     raeburn  4735:     } elsif ($role =~ /^gr\//) {
                   4736:         my $cwogrp=$url;
1.811     albertel 4737:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4738:         unless (&allowed('mdg',$cwogrp)) {
                   4739:             &logthis('Refused group assignrole: '.
                   4740:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4741:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4742:             return 'refused';
                   4743:         }
                   4744:         $mrole='gr';
1.21      www      4745:     } else {
1.82      www      4746:         my $cwosec=$url;
1.811     albertel 4747:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4748:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4749:            &logthis('Refused assignrole: '.
                   4750:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4751: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4752:            return 'refused'; 
                   4753:         }
1.21      www      4754:         $mrole=$role;
                   4755:     }
1.620     albertel 4756:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4757:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4758:     if ($end) { $command.='_'.$end; }
1.21      www      4759:     if ($start) {
                   4760: 	if ($end) { 
1.81      www      4761:            $command.='_'.$start; 
1.21      www      4762:         } else {
1.81      www      4763:            $command.='_0_'.$start;
1.21      www      4764:         }
                   4765:     }
1.739     raeburn  4766:     my $origstart = $start;
                   4767:     my $origend = $end;
1.357     www      4768: # actually delete
                   4769:     if ($deleteflag) {
1.373     www      4770: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4771: # modify command to delete the role
1.620     albertel 4772:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4773:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4774: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4775: # set start and finish to negative values for userrolelog
                   4776:            $start=-1;
                   4777:            $end=-1;
                   4778:         }
                   4779:     }
                   4780: # send command
1.349     www      4781:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4782: # log new user role if status is ok
1.349     www      4783:     if ($answer eq 'ok') {
1.663     raeburn  4784: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4785: # for course roles, perform group memberships changes triggered by role change.
                   4786:         unless ($role =~ /^gr/) {
                   4787:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4788:                                              $origstart);
                   4789:         }
1.349     www      4790:     }
                   4791:     return $answer;
1.169     harris41 4792: }
                   4793: 
                   4794: # -------------------------------------------------- Modify user authentication
1.197     www      4795: # Overrides without validation
                   4796: 
1.169     harris41 4797: sub modifyuserauth {
                   4798:     my ($udom,$uname,$umode,$upass)=@_;
                   4799:     my $uhome=&homeserver($uname,$udom);
1.197     www      4800:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4801:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4802:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4803:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4804:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4805: 		     &escape($upass),$uhome);
1.620     albertel 4806:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4807:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4808:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4809:     &log($udom,,$uname,$uhome,
1.620     albertel 4810:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4811:                                      $env{'user.name'}.', '.$umode.
1.197     www      4812:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4813:     unless ($reply eq 'ok') {
1.197     www      4814:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4815: 	return 'error: '.$reply;
                   4816:     }   
1.170     harris41 4817:     return 'ok';
1.80      www      4818: }
                   4819: 
1.81      www      4820: # --------------------------------------------------------------- Modify a user
1.80      www      4821: 
1.81      www      4822: sub modifyuser {
1.206     matthew  4823:     my ($udom,    $uname, $uid,
                   4824:         $umode,   $upass, $first,
                   4825:         $middle,  $last,  $gene,
1.387     www      4826:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4827:     $udom= &LONCAPA::clean_domain($udom);
                   4828:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4829:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4830:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4831: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4832:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4833:                                      ' desiredhome not specified'). 
1.620     albertel 4834:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4835:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4836:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4837: # ----------------------------------------------------------------- Create User
1.406     albertel 4838:     if (($uhome eq 'no_host') && 
                   4839: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4840:         my $unhome='';
1.844     albertel 4841:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4842:             $unhome = $desiredhome;
1.620     albertel 4843: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4844: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4845:         } else { # load balancing routine for determining $unhome
1.81      www      4846:             my $loadm=10000000;
1.841     albertel 4847: 	    my %servers = &get_servers($udom,'library');
                   4848: 	    foreach my $tryserver (keys(%servers)) {
                   4849: 		my $answer=reply('load',$tryserver);
                   4850: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4851: 		    $loadm=$answer;
                   4852: 		    $unhome=$tryserver;
                   4853: 		}
1.80      www      4854: 	    }
                   4855:         }
                   4856:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4857: 	    return 'error: unable to find a home server for '.$uname.
                   4858:                    ' in domain '.$udom;
1.80      www      4859:         }
                   4860:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4861:                          &escape($upass),$unhome);
                   4862: 	unless ($reply eq 'ok') {
                   4863:             return 'error: '.$reply;
                   4864:         }   
1.230     stredwic 4865:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4866:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4867: 	    return 'error: unable verify users home machine.';
1.80      www      4868:         }
1.209     matthew  4869:     }   # End of creation of new user
1.80      www      4870: # ---------------------------------------------------------------------- Add ID
                   4871:     if ($uid) {
                   4872:        $uid=~tr/A-Z/a-z/;
                   4873:        my %uidhash=&idrget($udom,$uname);
1.196     www      4874:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4875:          && (!$forceid)) {
1.80      www      4876: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4877: 	      return 'error: user id "'.$uid.'" does not match '.
                   4878:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4879:           }
                   4880:        } else {
                   4881: 	  &idput($udom,($uname => $uid));
                   4882:        }
                   4883:     }
                   4884: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4885:     my @tmp=&get('environment',
1.134     albertel 4886: 		   ['firstname','middlename','lastname','generation'],
                   4887: 		   $udom,$uname);
1.313     matthew  4888:     my %names;
                   4889:     if ($tmp[0] =~ m/^error:.*/) { 
                   4890:         %names=(); 
                   4891:     } else {
                   4892:         %names = @tmp;
                   4893:     }
1.388     www      4894: #
                   4895: # Make sure to not trash student environment if instructor does not bother
                   4896: # to supply name and email information
                   4897: #
                   4898:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4899:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4900:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4901:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4902:     if ($email) {
                   4903:        $email=~s/[^\w\@\.\-\,]//gs;
                   4904:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4905: 			   $names{'critnotification'} = $email;
                   4906: 			   $names{'permanentemail'} = $email; }
                   4907:     }
1.134     albertel 4908:     my $reply = &put('environment', \%names, $udom,$uname);
                   4909:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4910:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4911:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4912:              $umode.', '.$first.', '.$middle.', '.
                   4913: 	     $last.', '.$gene.' by '.
1.620     albertel 4914:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4915:     return 'ok';
1.80      www      4916: }
                   4917: 
1.81      www      4918: # -------------------------------------------------------------- Modify student
1.80      www      4919: 
1.81      www      4920: sub modifystudent {
                   4921:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4922:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4923:     if (!$cid) {
1.620     albertel 4924: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4925: 	    return 'not_in_class';
                   4926: 	}
1.80      www      4927:     }
                   4928: # --------------------------------------------------------------- Make the user
1.81      www      4929:     my $reply=&modifyuser
1.209     matthew  4930: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4931:          $desiredhome,$email);
1.80      www      4932:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4933:     # This will cause &modify_student_enrollment to get the uid from the
                   4934:     # students environment
                   4935:     $uid = undef if (!$forceid);
1.455     albertel 4936:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4937: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4938:     return $reply;
                   4939: }
                   4940: 
                   4941: sub modify_student_enrollment {
1.515     raeburn  4942:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4943:     my ($cdom,$cnum,$chome);
                   4944:     if (!$cid) {
1.620     albertel 4945: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4946: 	    return 'not_in_class';
                   4947: 	}
1.620     albertel 4948: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4949: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4950:     } else {
                   4951: 	($cdom,$cnum)=split(/_/,$cid);
                   4952:     }
1.620     albertel 4953:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4954:     if (!$chome) {
1.457     raeburn  4955: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4956:     }
1.455     albertel 4957:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4958:     # Make sure the user exists
1.81      www      4959:     my $uhome=&homeserver($uname,$udom);
                   4960:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4961: 	return 'error: no such user';
                   4962:     }
1.297     matthew  4963:     # Get student data if we were not given enough information
                   4964:     if (!defined($first)  || $first  eq '' || 
                   4965:         !defined($last)   || $last   eq '' || 
                   4966:         !defined($uid)    || $uid    eq '' || 
                   4967:         !defined($middle) || $middle eq '' || 
                   4968:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4969:         # They did not supply us with enough data to enroll the student, so
                   4970:         # we need to pick up more information.
1.297     matthew  4971:         my %tmp = &get('environment',
1.294     matthew  4972:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4973:                        ,$udom,$uname);
                   4974: 
1.800     albertel 4975:         #foreach my $key (keys(%tmp)) {
                   4976:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4977:         #}
1.294     matthew  4978:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4979:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4980:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4981:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4982:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4983:     }
1.556     albertel 4984:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4985:     my $reply=cput('classlist',
                   4986: 		   {"$uname:$udom" => 
1.515     raeburn  4987: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4988: 		   $cdom,$cnum);
1.81      www      4989:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4990: 	return 'error: '.$reply;
1.652     albertel 4991:     } else {
                   4992: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4993:     }
1.297     matthew  4994:     # Add student role to user
1.83      www      4995:     my $uurl='/'.$cid;
1.81      www      4996:     $uurl=~s/\_/\//g;
                   4997:     if ($usec) {
                   4998: 	$uurl.='/'.$usec;
                   4999:     }
                   5000:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5001: }
                   5002: 
1.556     albertel 5003: sub format_name {
                   5004:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5005:     my $name;
                   5006:     if ($first ne 'lastname') {
                   5007: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5008:     } else {
                   5009: 	if ($lastname=~/\S/) {
                   5010: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5011: 	    $name=~s/\s+,/,/;
                   5012: 	} else {
                   5013: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5014: 	}
                   5015:     }
                   5016:     $name=~s/^\s+//;
                   5017:     $name=~s/\s+$//;
                   5018:     $name=~s/\s+/ /g;
                   5019:     return $name;
                   5020: }
                   5021: 
1.84      www      5022: # ------------------------------------------------- Write to course preferences
                   5023: 
                   5024: sub writecoursepref {
                   5025:     my ($courseid,%prefs)=@_;
                   5026:     $courseid=~s/^\///;
                   5027:     $courseid=~s/\_/\//g;
                   5028:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5029:     my $chome=homeserver($cnum,$cdomain);
                   5030:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5031: 	return 'error: no such course';
                   5032:     }
                   5033:     my $cstring='';
1.800     albertel 5034:     foreach my $pref (keys(%prefs)) {
                   5035: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5036:     }
1.84      www      5037:     $cstring=~s/\&$//;
                   5038:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5039: }
                   5040: 
                   5041: # ---------------------------------------------------------- Make/modify course
                   5042: 
                   5043: sub createcourse {
1.741     raeburn  5044:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5045:         $course_owner,$crstype)=@_;
1.84      www      5046:     $url=&declutter($url);
                   5047:     my $cid='';
1.264     matthew  5048:     unless (&allowed('ccc',$udom)) {
1.84      www      5049:         return 'refused';
                   5050:     }
                   5051: # ------------------------------------------------------------------- Create ID
1.674     www      5052:    my $uname=int(1+rand(9)).
                   5053:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5054:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5055:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5056: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5057:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5058:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5059:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5060:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5061:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5062:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5063:            return 'error: unable to generate unique course-ID';
                   5064:        } 
                   5065:    }
1.264     matthew  5066: # ------------------------------------------------ Check supplied server name
1.620     albertel 5067:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5068:     if (! &is_library($course_server)) {
1.264     matthew  5069:         return 'error:bad server name '.$course_server;
                   5070:     }
1.84      www      5071: # ------------------------------------------------------------- Make the course
                   5072:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5073:                       $course_server);
1.84      www      5074:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5075:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5076:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5077: 	return 'error: no such course';
                   5078:     }
1.271     www      5079: # ----------------------------------------------------------------- Course made
1.516     raeburn  5080: # log existence
                   5081:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5082:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5083:                   &escape($crstype),$uhome);
1.358     www      5084:     &flushcourselogs();
                   5085: # set toplevel url
1.271     www      5086:     my $topurl=$url;
                   5087:     unless ($nonstandard) {
                   5088: # ------------------------------------------ For standard courses, make top url
                   5089:         my $mapurl=&clutter($url);
1.278     www      5090:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5091:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5092: <map>
                   5093: <resource id="1" type="start"></resource>
                   5094: <resource id="2" src="$mapurl"></resource>
                   5095: <resource id="3" type="finish"></resource>
                   5096: <link index="1" from="1" to="2"></link>
                   5097: <link index="2" from="2" to="3"></link>
                   5098: </map>
                   5099: ENDINITMAP
                   5100:         $topurl=&declutter(
1.638     albertel 5101:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5102:                           );
                   5103:     }
                   5104: # ----------------------------------------------------------- Write preferences
1.84      www      5105:     &writecoursepref($udom.'_'.$uname,
                   5106:                      ('description' => $description,
1.271     www      5107:                       'url'         => $topurl));
1.84      www      5108:     return '/'.$udom.'/'.$uname;
                   5109: }
                   5110: 
1.813     albertel 5111: sub is_course {
                   5112:     my ($cdom,$cnum) = @_;
                   5113:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5114: 				undef,'.');
                   5115:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5116:         return 1;
                   5117:     }
                   5118:     return 0;
                   5119: }
                   5120: 
1.21      www      5121: # ---------------------------------------------------------- Assign Custom Role
                   5122: 
                   5123: sub assigncustomrole {
1.357     www      5124:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5125:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5126:                        $end,$start,$deleteflag);
1.21      www      5127: }
                   5128: 
                   5129: # ----------------------------------------------------------------- Revoke Role
                   5130: 
                   5131: sub revokerole {
1.357     www      5132:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5133:     my $now=time;
1.357     www      5134:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5135: }
                   5136: 
                   5137: # ---------------------------------------------------------- Revoke Custom Role
                   5138: 
                   5139: sub revokecustomrole {
1.357     www      5140:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5141:     my $now=time;
1.357     www      5142:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5143:            $deleteflag);
1.17      www      5144: }
                   5145: 
1.533     banghart 5146: # ------------------------------------------------------------ Disk usage
1.535     albertel 5147: sub diskusage {
1.533     banghart 5148:     my ($udom,$uname,$directoryRoot)=@_;
                   5149:     $directoryRoot =~ s/\/$//;
1.535     albertel 5150:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5151:     return $listing;
1.512     banghart 5152: }
                   5153: 
1.566     banghart 5154: sub is_locked {
                   5155:     my ($file_name, $domain, $user) = @_;
                   5156:     my @check;
                   5157:     my $is_locked;
                   5158:     push @check, $file_name;
1.613     albertel 5159:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5160: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5161:     my ($tmp)=keys(%locked);
                   5162:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5163:     
1.566     banghart 5164:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5165:         $is_locked = 'false';
                   5166:         foreach my $entry (@{$locked{$file_name}}) {
                   5167:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5168:                $is_locked = 'true';
                   5169:                last;
1.745     raeburn  5170:            }
                   5171:        }
1.566     banghart 5172:     } else {
                   5173:         $is_locked = 'false';
                   5174:     }
                   5175: }
                   5176: 
1.759     albertel 5177: sub declutter_portfile {
                   5178:     my ($file) = @_;
1.833     albertel 5179:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5180:     return $file;
                   5181: }
                   5182: 
1.559     banghart 5183: # ------------------------------------------------------------- Mark as Read Only
                   5184: 
                   5185: sub mark_as_readonly {
                   5186:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5187:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5188:     my ($tmp)=keys(%current_permissions);
                   5189:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5190:     foreach my $file (@{$files}) {
1.759     albertel 5191: 	$file = &declutter_portfile($file);
1.561     banghart 5192:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5193:     }
1.613     albertel 5194:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5195:     return;
                   5196: }
                   5197: 
1.572     banghart 5198: # ------------------------------------------------------------Save Selected Files
                   5199: 
                   5200: sub save_selected_files {
                   5201:     my ($user, $path, @files) = @_;
                   5202:     my $filename = $user."savedfiles";
1.573     banghart 5203:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5204:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5205:     foreach my $file (@files) {
1.620     albertel 5206:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5207:     }
                   5208:     foreach my $file (@other_files) {
1.574     banghart 5209:         print (OUT $file."\n");
1.572     banghart 5210:     }
1.574     banghart 5211:     close (OUT);
1.572     banghart 5212:     return 'ok';
                   5213: }
                   5214: 
1.574     banghart 5215: sub clear_selected_files {
                   5216:     my ($user) = @_;
                   5217:     my $filename = $user."savedfiles";
                   5218:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5219:     print (OUT undef);
                   5220:     close (OUT);
                   5221:     return ("ok");    
                   5222: }
                   5223: 
1.572     banghart 5224: sub files_in_path {
                   5225:     my ($user, $path) = @_;
                   5226:     my $filename = $user."savedfiles";
                   5227:     my %return_files;
1.574     banghart 5228:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5229:     while (my $line_in = <IN>) {
1.574     banghart 5230:         chomp ($line_in);
                   5231:         my @paths_and_file = split (m!/!, $line_in);
                   5232:         my $file_part = pop (@paths_and_file);
                   5233:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5234:         $path_part.='/';
                   5235:         my $path_and_file = $path_part.$file_part;
                   5236:         if ($path_part eq $path) {
                   5237:             $return_files{$file_part}= 'selected';
                   5238:         }
                   5239:     }
1.574     banghart 5240:     close (IN);
                   5241:     return (\%return_files);
1.572     banghart 5242: }
                   5243: 
                   5244: # called in portfolio select mode, to show files selected NOT in current directory
                   5245: sub files_not_in_path {
                   5246:     my ($user, $path) = @_;
                   5247:     my $filename = $user."savedfiles";
                   5248:     my @return_files;
                   5249:     my $path_part;
1.800     albertel 5250:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5251:     while (my $line = <IN>) {
1.572     banghart 5252:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5253:         my @paths_and_file = split(m|/|, $line);
                   5254:         my $file_part = pop(@paths_and_file);
                   5255:         chomp($file_part);
                   5256:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5257:         $path_part .= '/';
                   5258:         my $path_and_file = $path_part.$file_part;
                   5259:         if ($path_part ne $path) {
1.800     albertel 5260:             push(@return_files, ($path_and_file));
1.572     banghart 5261:         }
                   5262:     }
1.800     albertel 5263:     close(OUT);
1.574     banghart 5264:     return (@return_files);
1.572     banghart 5265: }
                   5266: 
1.745     raeburn  5267: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5268: 
1.745     raeburn  5269: sub get_portfile_permissions {
                   5270:     my ($domain,$user) = @_;
1.613     albertel 5271:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5272:     my ($tmp)=keys(%current_permissions);
                   5273:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5274:     return \%current_permissions;
                   5275: }
                   5276: 
                   5277: #---------------------------------------------Get portfolio file access controls
                   5278: 
1.749     raeburn  5279: sub get_access_controls {
1.745     raeburn  5280:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5281:     my %access;
                   5282:     my $real_file = $file;
                   5283:     $file =~ s/\.meta$//;
1.745     raeburn  5284:     if (defined($file)) {
1.749     raeburn  5285:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5286:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5287:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5288:             }
                   5289:         }
1.745     raeburn  5290:     } else {
1.749     raeburn  5291:         foreach my $key (keys(%{$current_permissions})) {
                   5292:             if ($key =~ /\0accesscontrol$/) {
                   5293:                 if (defined($group)) {
                   5294:                     if ($key !~ m-^\Q$group\E/-) {
                   5295:                         next;
                   5296:                     }
                   5297:                 }
                   5298:                 my ($fullpath) = split(/\0/,$key);
                   5299:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5300:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5301:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5302:                     }
                   5303:                 }
                   5304:             }
                   5305:         }
                   5306:     }
                   5307:     return %access;
                   5308: }
                   5309: 
                   5310: sub modify_access_controls {
                   5311:     my ($file_name,$changes,$domain,$user)=@_;
                   5312:     my ($outcome,$deloutcome);
                   5313:     my %store_permissions;
                   5314:     my %new_values;
                   5315:     my %new_control;
                   5316:     my %translation;
                   5317:     my @deletions = ();
                   5318:     my $now = time;
                   5319:     if (exists($$changes{'activate'})) {
                   5320:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5321:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5322:             my $numnew = scalar(@newitems);
                   5323:             for (my $i=0; $i<$numnew; $i++) {
                   5324:                 my $newkey = $newitems[$i];
                   5325:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5326:                 if ($newkey =~ /^\d+:/) { 
                   5327:                     $newkey =~ s/^(\d+)/$newid/;
                   5328:                     $translation{$1} = $newid;
                   5329:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5330:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5331:                     $translation{$1} = $newid;
                   5332:                 }
1.749     raeburn  5333:                 $new_values{$file_name."\0".$newkey} = 
                   5334:                                           $$changes{'activate'}{$newitems[$i]};
                   5335:                 $new_control{$newkey} = $now;
                   5336:             }
                   5337:         }
                   5338:     }
                   5339:     my %todelete;
                   5340:     my %changed_items;
                   5341:     foreach my $action ('delete','update') {
                   5342:         if (exists($$changes{$action})) {
                   5343:             if (ref($$changes{$action}) eq 'HASH') {
                   5344:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5345:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5346:                     if ($action eq 'delete') { 
                   5347:                         $todelete{$itemnum} = 1;
                   5348:                     } else {
                   5349:                         $changed_items{$itemnum} = $key;
                   5350:                     }
                   5351:                 }
1.745     raeburn  5352:             }
                   5353:         }
1.749     raeburn  5354:     }
                   5355:     # get lock on access controls for file.
                   5356:     my $lockhash = {
                   5357:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5358:                                                        ':'.$env{'user.domain'},
                   5359:                    }; 
                   5360:     my $tries = 0;
                   5361:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5362:    
                   5363:     while (($gotlock ne 'ok') && $tries <3) {
                   5364:         $tries ++;
                   5365:         sleep 1;
                   5366:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5367:     }
                   5368:     if ($gotlock eq 'ok') {
                   5369:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5370:         my ($tmp)=keys(%curr_permissions);
                   5371:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5372:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5373:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5374:             if (ref($curr_controls) eq 'HASH') {
                   5375:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5376:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5377:                     if (defined($todelete{$itemnum})) {
                   5378:                         push(@deletions,$file_name."\0".$control_item);
                   5379:                     } else {
                   5380:                         if (defined($changed_items{$itemnum})) {
                   5381:                             $new_control{$changed_items{$itemnum}} = $now;
                   5382:                             push(@deletions,$file_name."\0".$control_item);
                   5383:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5384:                         } else {
                   5385:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5386:                         }
                   5387:                     }
1.745     raeburn  5388:                 }
                   5389:             }
                   5390:         }
1.749     raeburn  5391:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5392:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5393:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5394:         #  remove lock
                   5395:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5396:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5397:         my ($file,$group);
                   5398:         if (&is_course($domain,$user)) {
                   5399:             ($group,$file) = split(/\//,$file_name,2);
                   5400:         } else {
                   5401:             $file = $file_name;
                   5402:         }
                   5403:         my $sqlresult =
                   5404:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5405:                                     $group);
1.749     raeburn  5406:     } else {
                   5407:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5408:     }
1.749     raeburn  5409:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5410: }
                   5411: 
1.827     raeburn  5412: sub make_public_indefinitely {
                   5413:     my ($requrl) = @_;
                   5414:     my $now = time;
                   5415:     my $action = 'activate';
                   5416:     my $aclnum = 0;
                   5417:     if (&is_portfolio_url($requrl)) {
                   5418:         my (undef,$udom,$unum,$file_name,$group) =
                   5419:             &parse_portfolio_url($requrl);
                   5420:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5421:         my %access_controls = &get_access_controls($current_perms,
                   5422:                                                    $group,$file_name);
                   5423:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5424:             my ($num,$scope,$end,$start) = 
                   5425:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5426:             if ($scope eq 'public') {
                   5427:                 if ($start <= $now && $end == 0) {
                   5428:                     $action = 'none';
                   5429:                 } else {
                   5430:                     $action = 'update';
                   5431:                     $aclnum = $num;
                   5432:                 }
                   5433:                 last;
                   5434:             }
                   5435:         }
                   5436:         if ($action eq 'none') {
                   5437:              return 'ok';
                   5438:         } else {
                   5439:             my %changes;
                   5440:             my $newend = 0;
                   5441:             my $newstart = $now;
                   5442:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5443:             $changes{$action}{$newkey} = {
                   5444:                 type => 'public',
                   5445:                 time => {
                   5446:                     start => $newstart,
                   5447:                     end   => $newend,
                   5448:                 },
                   5449:             };
                   5450:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5451:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5452:             return $outcome;
                   5453:         }
                   5454:     } else {
                   5455:         return 'invalid';
                   5456:     }
                   5457: }
                   5458: 
1.745     raeburn  5459: #------------------------------------------------------Get Marked as Read Only
                   5460: 
                   5461: sub get_marked_as_readonly {
                   5462:     my ($domain,$user,$what,$group) = @_;
                   5463:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5464:     my @readonly_files;
1.629     banghart 5465:     my $cmp1=$what;
                   5466:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5467:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5468:         if (defined($group)) {
                   5469:             if ($file_name !~ m-^\Q$group\E/-) {
                   5470:                 next;
                   5471:             }
                   5472:         }
1.561     banghart 5473:         if (ref($value) eq "ARRAY"){
                   5474:             foreach my $stored_what (@{$value}) {
1.629     banghart 5475:                 my $cmp2=$stored_what;
1.759     albertel 5476:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5477:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5478:                 }
1.629     banghart 5479:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5480:                     push(@readonly_files, $file_name);
1.745     raeburn  5481:                     last;
1.563     banghart 5482:                 } elsif (!defined($what)) {
                   5483:                     push(@readonly_files, $file_name);
1.745     raeburn  5484:                     last;
1.561     banghart 5485:                 }
                   5486:             }
1.745     raeburn  5487:         }
1.561     banghart 5488:     }
                   5489:     return @readonly_files;
                   5490: }
1.577     banghart 5491: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5492: 
1.577     banghart 5493: sub get_marked_as_readonly_hash {
1.745     raeburn  5494:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5495:     my %readonly_files;
1.745     raeburn  5496:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5497:         if (defined($group)) {
                   5498:             if ($file_name !~ m-^\Q$group\E/-) {
                   5499:                 next;
                   5500:             }
                   5501:         }
1.577     banghart 5502:         if (ref($value) eq "ARRAY"){
                   5503:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5504:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5505:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5506:                         if ($lock_descriptor eq 'graded') {
                   5507:                             $readonly_files{$file_name} = 'graded';
                   5508:                         } elsif ($lock_descriptor eq 'handback') {
                   5509:                             $readonly_files{$file_name} = 'handback';
                   5510:                         } else {
                   5511:                             if (!exists($readonly_files{$file_name})) {
                   5512:                                 $readonly_files{$file_name} = 'locked';
                   5513:                             }
                   5514:                         }
1.745     raeburn  5515:                     }
1.750     banghart 5516:                 } 
1.577     banghart 5517:             }
                   5518:         } 
                   5519:     }
                   5520:     return %readonly_files;
                   5521: }
1.559     banghart 5522: # ------------------------------------------------------------ Unmark as Read Only
                   5523: 
                   5524: sub unmark_as_readonly {
1.629     banghart 5525:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5526:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5527:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5528:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5529:     my $symb_crs = $what;
                   5530:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5531:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5532:     my ($tmp)=keys(%current_permissions);
                   5533:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5534:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5535:     foreach my $file (@readonly_files) {
1.759     albertel 5536: 	my $clean_file = &declutter_portfile($file);
                   5537: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5538: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5539:         my @new_locks;
                   5540:         my @del_keys;
                   5541:         if (ref($current_locks) eq "ARRAY"){
                   5542:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5543:                 my $compare=$locker;
1.749     raeburn  5544:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5545:                     $compare=join('',@{$locker});
1.746     raeburn  5546:                     if ($compare ne $symb_crs) {
                   5547:                         push(@new_locks, $locker);
                   5548:                     }
1.563     banghart 5549:                 }
                   5550:             }
1.650     albertel 5551:             if (scalar(@new_locks) > 0) {
1.563     banghart 5552:                 $current_permissions{$file} = \@new_locks;
                   5553:             } else {
                   5554:                 push(@del_keys, $file);
1.613     albertel 5555:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5556:                 delete($current_permissions{$file});
1.563     banghart 5557:             }
                   5558:         }
1.561     banghart 5559:     }
1.613     albertel 5560:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5561:     return;
                   5562: }
1.512     banghart 5563: 
1.17      www      5564: # ------------------------------------------------------------ Directory lister
                   5565: 
                   5566: sub dirlist {
1.253     stredwic 5567:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5568: 
1.18      www      5569:     $uri=~s/^\///;
                   5570:     $uri=~s/\/$//;
1.253     stredwic 5571:     my ($udom, $uname);
                   5572:     (undef,$udom,$uname)=split(/\//,$uri);
                   5573:     if(defined($userdomain)) {
                   5574:         $udom = $userdomain;
                   5575:     }
                   5576:     if(defined($username)) {
                   5577:         $uname = $username;
                   5578:     }
                   5579: 
                   5580:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5581:     if(defined($alternateDirectoryRoot)) {
                   5582:         $dirRoot = $alternateDirectoryRoot;
                   5583:         $dirRoot =~ s/\/$//;
1.751     banghart 5584:     }
1.253     stredwic 5585: 
                   5586:     if($udom) {
                   5587:         if($uname) {
1.800     albertel 5588:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5589: 				 &homeserver($uname,$udom));
1.605     matthew  5590:             my @listing_results;
                   5591:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5592:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5593: 				  &homeserver($uname,$udom));
1.605     matthew  5594:                 @listing_results = split(/:/,$listing);
                   5595:             } else {
                   5596:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5597:             }
                   5598:             return @listing_results;
1.253     stredwic 5599:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5600:             my %allusers;
1.841     albertel 5601: 	    my %servers = &get_servers($udom,'library');
                   5602: 	    foreach my $tryserver (keys(%servers)) {
                   5603: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5604: 				     $udom, $tryserver);
                   5605: 		my @listing_results;
                   5606: 		if ($listing eq 'unknown_cmd') {
                   5607: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5608: 				      $udom, $tryserver);
                   5609: 		    @listing_results = split(/:/,$listing);
                   5610: 		} else {
                   5611: 		    @listing_results =
                   5612: 			map { &unescape($_); } split(/:/,$listing);
                   5613: 		}
                   5614: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5615: 		    $listing_results[0] ne 'empty'       &&
                   5616: 		    $listing_results[0] ne 'con_lost') {
                   5617: 		    foreach my $line (@listing_results) {
                   5618: 			my ($entry) = split(/&/,$line,2);
                   5619: 			$allusers{$entry} = 1;
                   5620: 		    }
                   5621: 		}
1.253     stredwic 5622:             }
                   5623:             my $alluserstr='';
1.800     albertel 5624:             foreach my $user (sort(keys(%allusers))) {
                   5625:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5626:             }
                   5627:             $alluserstr=~s/:$//;
                   5628:             return split(/:/,$alluserstr);
                   5629:         } else {
1.800     albertel 5630:             return ('missing user name');
1.253     stredwic 5631:         }
                   5632:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5633:         my @all_domains = sort(&all_domains());
                   5634:          foreach my $domain (@all_domains) {
                   5635:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5636:          }
                   5637:          return @all_domains;
                   5638:      } else {
1.800     albertel 5639:         return ('missing domain');
1.275     stredwic 5640:     }
                   5641: }
                   5642: 
                   5643: # --------------------------------------------- GetFileTimestamp
                   5644: # This function utilizes dirlist and returns the date stamp for
                   5645: # when it was last modified.  It will also return an error of -1
                   5646: # if an error occurs
                   5647: 
1.410     matthew  5648: ##
                   5649: ## FIXME: This subroutine assumes its caller knows something about the
                   5650: ## directory structure of the home server for the student ($root).
                   5651: ## Not a good assumption to make.  Since this is for looking up files
                   5652: ## in user directories, the full path should be constructed by lond, not
                   5653: ## whatever machine we request data from.
                   5654: ##
1.275     stredwic 5655: sub GetFileTimestamp {
                   5656:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5657:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5658:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5659:     my $subdir=$studentName.'__';
                   5660:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5661:     my $proname="$studentDomain/$subdir/$studentName";
                   5662:     $proname .= '/'.$filename;
1.375     matthew  5663:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5664:                                               $studentName, $root);
1.275     stredwic 5665:     my @stats = split('&', $fileStat);
                   5666:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5667:         # @stats contains first the filename, then the stat output
                   5668:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5669:     } else {
                   5670:         return -1;
1.253     stredwic 5671:     }
1.26      www      5672: }
                   5673: 
1.712     albertel 5674: sub stat_file {
                   5675:     my ($uri) = @_;
1.787     albertel 5676:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5677: 
1.712     albertel 5678:     my ($udom,$uname,$file,$dir);
                   5679:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5680: 	($udom,$uname,$file) =
1.811     albertel 5681: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5682: 	$file = 'userfiles/'.$file;
1.740     www      5683: 	$dir = &propath($udom,$uname);
1.712     albertel 5684:     }
                   5685:     if ($uri =~ m-^/res/-) {
                   5686: 	($udom,$uname) = 
1.807     albertel 5687: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5688: 	$file = $uri;
                   5689:     }
                   5690: 
                   5691:     if (!$udom || !$uname || !$file) {
                   5692: 	# unable to handle the uri
                   5693: 	return ();
                   5694:     }
                   5695: 
                   5696:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5697:     my @stats = split('&', $result);
1.721     banghart 5698:     
1.712     albertel 5699:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5700: 	shift(@stats); #filename is first
                   5701: 	return @stats;
                   5702:     }
                   5703:     return ();
                   5704: }
                   5705: 
1.26      www      5706: # -------------------------------------------------------- Value of a Condition
                   5707: 
1.713     albertel 5708: # gets the value of a specific preevaluated condition
                   5709: #    stored in the string  $env{user.state.<cid>}
                   5710: # or looks up a condition reference in the bighash and if if hasn't
                   5711: # already been evaluated recurses into docondval to get the value of
                   5712: # the condition, then memoizing it to 
                   5713: #   $env{user.state.<cid>.<condition>}
1.40      www      5714: sub directcondval {
                   5715:     my $number=shift;
1.620     albertel 5716:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5717: 	&Apache::lonuserstate::evalstate();
                   5718:     }
1.713     albertel 5719:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5720: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5721:     } elsif ($number =~ /^_/) {
                   5722: 	my $sub_condition;
                   5723: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5724: 		&GDBM_READER(),0640)) {
                   5725: 	    $sub_condition=$bighash{'conditions'.$number};
                   5726: 	    untie(%bighash);
                   5727: 	}
                   5728: 	my $value = &docondval($sub_condition);
                   5729: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5730: 	return $value;
                   5731:     }
1.620     albertel 5732:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5733:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5734:     } else {
                   5735:        return 2;
                   5736:     }
                   5737: }
                   5738: 
1.713     albertel 5739: # get the collection of conditions for this resource
1.26      www      5740: sub condval {
                   5741:     my $condidx=shift;
1.54      www      5742:     my $allpathcond='';
1.713     albertel 5743:     foreach my $cond (split(/\|/,$condidx)) {
                   5744: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5745: 	    $allpathcond.=
                   5746: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5747: 	}
1.191     harris41 5748:     }
1.54      www      5749:     $allpathcond=~s/\|$//;
1.713     albertel 5750:     return &docondval($allpathcond);
                   5751: }
                   5752: 
                   5753: #evaluates an expression of conditions
                   5754: sub docondval {
                   5755:     my ($allpathcond) = @_;
                   5756:     my $result=0;
                   5757:     if ($env{'request.course.id'}
                   5758: 	&& defined($allpathcond)) {
                   5759: 	my $operand='|';
                   5760: 	my @stack;
                   5761: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5762: 	    if ($chunk eq '(') {
                   5763: 		push @stack,($operand,$result);
                   5764: 	    } elsif ($chunk eq ')') {
                   5765: 		my $before=pop @stack;
                   5766: 		if (pop @stack eq '&') {
                   5767: 		    $result=$result>$before?$before:$result;
                   5768: 		} else {
                   5769: 		    $result=$result>$before?$result:$before;
                   5770: 		}
                   5771: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5772: 		$operand=$chunk;
                   5773: 	    } else {
                   5774: 		my $new=directcondval($chunk);
                   5775: 		if ($operand eq '&') {
                   5776: 		    $result=$result>$new?$new:$result;
                   5777: 		} else {
                   5778: 		    $result=$result>$new?$result:$new;
                   5779: 		}
                   5780: 	    }
                   5781: 	}
1.26      www      5782:     }
                   5783:     return $result;
1.421     albertel 5784: }
                   5785: 
                   5786: # ---------------------------------------------------- Devalidate courseresdata
                   5787: 
                   5788: sub devalidatecourseresdata {
                   5789:     my ($coursenum,$coursedomain)=@_;
                   5790:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5791:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5792: }
                   5793: 
1.763     www      5794: 
1.200     www      5795: # --------------------------------------------------- Course Resourcedata Query
                   5796: 
1.624     albertel 5797: sub get_courseresdata {
                   5798:     my ($coursenum,$coursedomain)=@_;
1.200     www      5799:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5800:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5801:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5802:     my %dumpreply;
1.417     albertel 5803:     unless (defined($cached)) {
1.624     albertel 5804: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5805: 	$result=\%dumpreply;
1.251     albertel 5806: 	my ($tmp) = keys(%dumpreply);
                   5807: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5808: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5809: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5810: 	    return $tmp;
1.416     albertel 5811: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5812: 	    $result=undef;
1.599     albertel 5813: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5814: 	}
                   5815:     }
1.624     albertel 5816:     return $result;
                   5817: }
                   5818: 
1.633     albertel 5819: sub devalidateuserresdata {
                   5820:     my ($uname,$udom)=@_;
                   5821:     my $hashid="$udom:$uname";
                   5822:     &devalidate_cache_new('userres',$hashid);
                   5823: }
                   5824: 
1.624     albertel 5825: sub get_userresdata {
                   5826:     my ($uname,$udom)=@_;
                   5827:     #most student don\'t have any data set, check if there is some data
                   5828:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5829: 
                   5830:     my $hashid="$udom:$uname";
                   5831:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5832:     if (!defined($cached)) {
                   5833: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5834: 	$result=\%resourcedata;
                   5835: 	&do_cache_new('userres',$hashid,$result,600);
                   5836:     }
                   5837:     my ($tmp)=keys(%$result);
                   5838:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5839: 	return $result;
                   5840:     }
                   5841:     #error 2 occurs when the .db doesn't exist
                   5842:     if ($tmp!~/error: 2 /) {
1.672     albertel 5843: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5844: 		 " Trying to get resource data for ".
                   5845: 		 $uname." at ".$udom.": ".
                   5846: 		 $tmp."</font>");
                   5847:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5848: 	#&EXT_cache_set($udom,$uname);
                   5849: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5850: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5851:     }
                   5852:     return $tmp;
                   5853: }
                   5854: 
                   5855: sub resdata {
                   5856:     my ($name,$domain,$type,@which)=@_;
                   5857:     my $result;
                   5858:     if ($type eq 'course') {
                   5859: 	$result=&get_courseresdata($name,$domain);
                   5860:     } elsif ($type eq 'user') {
                   5861: 	$result=&get_userresdata($name,$domain);
                   5862:     }
                   5863:     if (!ref($result)) { return $result; }    
1.251     albertel 5864:     foreach my $item (@which) {
1.417     albertel 5865: 	if (defined($result->{$item})) {
                   5866: 	    return $result->{$item};
1.251     albertel 5867: 	}
1.250     albertel 5868:     }
1.291     albertel 5869:     return undef;
1.200     www      5870: }
                   5871: 
1.379     matthew  5872: #
                   5873: # EXT resource caching routines
                   5874: #
                   5875: 
                   5876: sub clear_EXT_cache_status {
1.383     albertel 5877:     &delenv('cache.EXT.');
1.379     matthew  5878: }
                   5879: 
                   5880: sub EXT_cache_status {
                   5881:     my ($target_domain,$target_user) = @_;
1.383     albertel 5882:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5883:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5884:         # We know already the user has no data
                   5885:         return 1;
                   5886:     } else {
                   5887:         return 0;
                   5888:     }
                   5889: }
                   5890: 
                   5891: sub EXT_cache_set {
                   5892:     my ($target_domain,$target_user) = @_;
1.383     albertel 5893:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5894:     #&appenv($cachename => time);
1.379     matthew  5895: }
                   5896: 
1.28      www      5897: # --------------------------------------------------------- Value of a Variable
1.58      www      5898: sub EXT {
1.715     albertel 5899: 
1.395     albertel 5900:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5901:     unless ($varname) { return ''; }
1.218     albertel 5902:     #get real user name/domain, courseid and symb
                   5903:     my $courseid;
1.359     albertel 5904:     my $publicuser;
1.427     www      5905:     if ($symbparm) {
                   5906: 	$symbparm=&get_symb_from_alias($symbparm);
                   5907:     }
1.218     albertel 5908:     if (!($uname && $udom)) {
1.790     albertel 5909:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5910:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5911:     } else {
1.620     albertel 5912: 	$courseid=$env{'request.course.id'};
1.218     albertel 5913:     }
1.48      www      5914:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5915:     my $rest;
1.320     albertel 5916:     if (defined($therest[0])) {
1.48      www      5917:        $rest=join('.',@therest);
                   5918:     } else {
                   5919:        $rest='';
                   5920:     }
1.320     albertel 5921: 
1.57      www      5922:     my $qualifierrest=$qualifier;
                   5923:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5924:     my $spacequalifierrest=$space;
                   5925:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5926:     if ($realm eq 'user') {
1.48      www      5927: # --------------------------------------------------------------- user.resource
                   5928: 	if ($space eq 'resource') {
1.651     albertel 5929: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5930: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5931: 		 &&
1.744     albertel 5932: 		 ($symbparm eq &symbread()) ) {	
                   5933: 		# if we are in the middle of processing the resource the
                   5934: 		# get the value we are planning on committing
                   5935:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5936:                     return $Apache::lonhomework::results{$qualifierrest};
                   5937:                 } else {
                   5938:                     return $Apache::lonhomework::history{$qualifierrest};
                   5939:                 }
1.335     albertel 5940: 	    } else {
1.359     albertel 5941: 		my %restored;
1.620     albertel 5942: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5943: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5944: 		} else {
                   5945: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5946: 		}
1.335     albertel 5947: 		return $restored{$qualifierrest};
                   5948: 	    }
1.48      www      5949: # ----------------------------------------------------------------- user.access
                   5950:         } elsif ($space eq 'access') {
1.218     albertel 5951: 	    # FIXME - not supporting calls for a specific user
1.48      www      5952:             return &allowed($qualifier,$rest);
                   5953: # ------------------------------------------ user.preferences, user.environment
                   5954:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5955: 	    if (($uname eq $env{'user.name'}) &&
                   5956: 		($udom eq $env{'user.domain'})) {
                   5957: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5958: 	    } else {
1.359     albertel 5959: 		my %returnhash;
                   5960: 		if (!$publicuser) {
                   5961: 		    %returnhash=&userenvironment($udom,$uname,
                   5962: 						 $qualifierrest);
                   5963: 		}
1.218     albertel 5964: 		return $returnhash{$qualifierrest};
                   5965: 	    }
1.48      www      5966: # ----------------------------------------------------------------- user.course
                   5967:         } elsif ($space eq 'course') {
1.218     albertel 5968: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5969:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5970: # ------------------------------------------------------------------- user.role
                   5971:         } elsif ($space eq 'role') {
1.218     albertel 5972: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5973:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5974:             if ($qualifier eq 'value') {
                   5975: 		return $role;
                   5976:             } elsif ($qualifier eq 'extent') {
                   5977:                 return $where;
                   5978:             }
                   5979: # ----------------------------------------------------------------- user.domain
                   5980:         } elsif ($space eq 'domain') {
1.218     albertel 5981:             return $udom;
1.48      www      5982: # ------------------------------------------------------------------- user.name
                   5983:         } elsif ($space eq 'name') {
1.218     albertel 5984:             return $uname;
1.48      www      5985: # ---------------------------------------------------- Any other user namespace
1.29      www      5986:         } else {
1.359     albertel 5987: 	    my %reply;
                   5988: 	    if (!$publicuser) {
                   5989: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5990: 	    }
                   5991: 	    return $reply{$qualifierrest};
1.48      www      5992:         }
1.236     www      5993:     } elsif ($realm eq 'query') {
                   5994: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5995:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5996: 						[$spacequalifierrest]);
1.620     albertel 5997: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5998:    } elsif ($realm eq 'request') {
1.48      www      5999: # ------------------------------------------------------------- request.browser
                   6000:         if ($space eq 'browser') {
1.430     www      6001: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6002: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6003: 		    return 1;
                   6004: 		} else {
                   6005: 		    return 0;
                   6006: 		}
                   6007: 	    } else {
1.620     albertel 6008: 		return $env{'browser.'.$qualifier};
1.430     www      6009: 	    }
1.57      www      6010: # ------------------------------------------------------------ request.filename
                   6011:         } else {
1.620     albertel 6012:             return $env{'request.'.$spacequalifierrest};
1.29      www      6013:         }
1.28      www      6014:     } elsif ($realm eq 'course') {
1.48      www      6015: # ---------------------------------------------------------- course.description
1.620     albertel 6016:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6017:     } elsif ($realm eq 'resource') {
1.165     www      6018: 
1.620     albertel 6019: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6020: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6021: 	}
1.693     albertel 6022: 
                   6023: 	if ($space eq 'title') {
                   6024: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6025: 	    return &gettitle($symbparm);
                   6026: 	}
                   6027: 	
                   6028: 	if ($space eq 'map') {
                   6029: 	    my ($map) = &decode_symb($symbparm);
                   6030: 	    return &symbread($map);
                   6031: 	}
                   6032: 
                   6033: 	my ($section, $group, @groups);
1.593     albertel 6034: 	my ($courselevelm,$courselevel);
1.539     albertel 6035: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6036: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6037: 
1.218     albertel 6038: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6039: 
1.60      www      6040: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6041: 	    my $symbp=$symbparm;
1.735     albertel 6042: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6043: 
                   6044: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6045: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6046: 
1.620     albertel 6047: 	    if (($env{'user.name'} eq $uname) &&
                   6048: 		($env{'user.domain'} eq $udom)) {
                   6049: 		$section=$env{'request.course.sec'};
1.733     raeburn  6050:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6051:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6052: 	    } else {
1.539     albertel 6053: 		if (! defined($usection)) {
1.551     albertel 6054: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6055: 		} else {
                   6056: 		    $section = $usection;
                   6057: 		}
1.733     raeburn  6058:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6059: 	    }
                   6060: 
                   6061: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6062: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6063: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6064: 
1.593     albertel 6065: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6066: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6067: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6068: 
1.60      www      6069: # ----------------------------------------------------------- first, check user
1.624     albertel 6070: 
                   6071: 	    my $userreply=&resdata($uname,$udom,'user',
                   6072: 				       ($courselevelr,$courselevelm,
                   6073: 					$courselevel));
                   6074: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6075: 
1.594     albertel 6076: # ------------------------------------------------ second, check some of course
1.684     raeburn  6077:             my $coursereply;
1.691     raeburn  6078:             if (@groups > 0) {
                   6079:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6080:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6081:                 if (defined($coursereply)) { return $coursereply; }
                   6082:             }
1.96      www      6083: 
1.684     raeburn  6084: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6085: 				     $env{'course.'.$courseid.'.domain'},
                   6086: 				     'course',
                   6087: 				     ($seclevelr,$seclevelm,$seclevel,
                   6088: 				      $courselevelr));
1.287     albertel 6089: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6090: 
1.60      www      6091: # ------------------------------------------------------ third, check map parms
1.218     albertel 6092: 	    my %parmhash=();
                   6093: 	    my $thisparm='';
                   6094: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6095: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6096: 		    &GDBM_READER(),0640)) {
1.218     albertel 6097: 		$thisparm=$parmhash{$symbparm};
                   6098: 		untie(%parmhash);
                   6099: 	    }
                   6100: 	    if ($thisparm) { return $thisparm; }
                   6101: 	}
1.594     albertel 6102: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6103: 
1.218     albertel 6104: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6105: 	my $filename;
                   6106: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6107: 	if ($symbparm) {
1.409     www      6108: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6109: 	} else {
1.620     albertel 6110: 	    $filename=$env{'request.filename'};
1.282     albertel 6111: 	}
                   6112: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6113: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6114: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6115: 	if (defined($metadata)) { return $metadata; }
1.142     www      6116: 
1.594     albertel 6117: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6118: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6119: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6120: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6121: 				     $env{'course.'.$courseid.'.domain'},
                   6122: 				     'course',
                   6123: 				     ($courselevelm,$courselevel));
1.593     albertel 6124: 	    if (defined($coursereply)) { return $coursereply; }
                   6125: 	}
1.145     www      6126: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6127: 	unless ($space eq '0') {
1.336     albertel 6128: 	    my @parts=split(/_/,$space);
                   6129: 	    my $id=pop(@parts);
                   6130: 	    my $part=join('_',@parts);
                   6131: 	    if ($part eq '') { $part='0'; }
                   6132: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6133: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6134: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6135: 	}
1.395     albertel 6136: 	if ($recurse) { return undef; }
                   6137: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6138: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6139: 
1.48      www      6140: # ---------------------------------------------------- Any other user namespace
                   6141:     } elsif ($realm eq 'environment') {
                   6142: # ----------------------------------------------------------------- environment
1.620     albertel 6143: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6144: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6145: 	} else {
1.770     albertel 6146: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6147: 		return '';
                   6148: 	    }
1.219     albertel 6149: 	    my %returnhash=&userenvironment($udom,$uname,
                   6150: 					    $spacequalifierrest);
                   6151: 	    return $returnhash{$spacequalifierrest};
                   6152: 	}
1.28      www      6153:     } elsif ($realm eq 'system') {
1.48      www      6154: # ----------------------------------------------------------------- system.time
                   6155: 	if ($space eq 'time') {
                   6156: 	    return time;
                   6157:         }
1.696     albertel 6158:     } elsif ($realm eq 'server') {
                   6159: # ----------------------------------------------------------------- system.time
                   6160: 	if ($space eq 'name') {
                   6161: 	    return $ENV{'SERVER_NAME'};
                   6162:         }
1.28      www      6163:     }
1.48      www      6164:     return '';
1.61      www      6165: }
                   6166: 
1.691     raeburn  6167: sub check_group_parms {
                   6168:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6169:     my @groupitems = ();
                   6170:     my $resultitem;
                   6171:     my @levels = ($symbparm,$mapparm,$what);
                   6172:     foreach my $group (@{$groups}) {
                   6173:         foreach my $level (@levels) {
                   6174:              my $item = $courseid.'.['.$group.'].'.$level;
                   6175:              push(@groupitems,$item);
                   6176:         }
                   6177:     }
                   6178:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6179:                             $env{'course.'.$courseid.'.domain'},
                   6180:                                      'course',@groupitems);
                   6181:     return $coursereply;
                   6182: }
                   6183: 
                   6184: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6185:     my ($courseid,@groups) = @_;
                   6186:     @groups = sort(@groups);
1.691     raeburn  6187:     return @groups;
                   6188: }
                   6189: 
1.395     albertel 6190: sub packages_tab_default {
                   6191:     my ($uri,$varname)=@_;
                   6192:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6193: 
                   6194:     my (@extension,@specifics,$do_default);
                   6195:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6196: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6197: 	if ($pack_type eq 'default') {
                   6198: 	    $do_default=1;
                   6199: 	} elsif ($pack_type eq 'extension') {
                   6200: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.848     albertel 6201: 	} elsif ($pack_part eq $part) {
                   6202: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6203: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6204: 	}
                   6205:     }
                   6206:     # first look for a package that matches the requested part id
                   6207:     foreach my $package (@specifics) {
                   6208: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6209: 	next if ($pack_part ne $part);
                   6210: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6211: 	    return $packagetab{"$pack_type&$name&default"};
                   6212: 	}
                   6213:     }
                   6214:     # look for any possible matching non extension_ package
                   6215:     foreach my $package (@specifics) {
                   6216: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6217: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6218: 	    return $packagetab{"$pack_type&$name&default"};
                   6219: 	}
1.585     albertel 6220: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6221: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6222: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6223: 	}
                   6224:     }
1.738     albertel 6225:     # look for any posible extension_ match
                   6226:     foreach my $package (@extension) {
                   6227: 	my ($package,$pack_type)=@{$package};
                   6228: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6229: 	    return $packagetab{"$pack_type&$name&default"};
                   6230: 	}
                   6231: 	if (defined($packagetab{$package."&$name&default"})) {
                   6232: 	    return $packagetab{$package."&$name&default"};
                   6233: 	}
                   6234:     }
                   6235:     # look for a global default setting
                   6236:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6237: 	return $packagetab{"default&$name&default"};
                   6238:     }
1.395     albertel 6239:     return undef;
                   6240: }
                   6241: 
1.334     albertel 6242: sub add_prefix_and_part {
                   6243:     my ($prefix,$part)=@_;
                   6244:     my $keyroot;
                   6245:     if (defined($prefix) && $prefix !~ /^__/) {
                   6246: 	# prefix that has a part already
                   6247: 	$keyroot=$prefix;
                   6248:     } elsif (defined($prefix)) {
                   6249: 	# prefix that is missing a part
                   6250: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6251:     } else {
                   6252: 	# no prefix at all
                   6253: 	if (defined($part)) { $keyroot='_'.$part; }
                   6254:     }
                   6255:     return $keyroot;
                   6256: }
                   6257: 
1.71      www      6258: # ---------------------------------------------------------------- Get metadata
                   6259: 
1.599     albertel 6260: my %metaentry;
1.71      www      6261: sub metadata {
1.176     www      6262:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6263:     $uri=&declutter($uri);
1.288     albertel 6264:     # if it is a non metadata possible uri return quickly
1.529     albertel 6265:     if (($uri eq '') || 
                   6266: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6267: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6268:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6269: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6270: 	return undef;
1.288     albertel 6271:     }
1.73      www      6272:     my $filename=$uri;
                   6273:     $uri=~s/\.meta$//;
1.172     www      6274: #
                   6275: # Is the metadata already cached?
1.177     www      6276: # Look at timestamp of caching
1.172     www      6277: # Everything is cached by the main uri, libraries are never directly cached
                   6278: #
1.428     albertel 6279:     if (!defined($liburi)) {
1.599     albertel 6280: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6281: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6282:     }
                   6283:     {
1.172     www      6284: #
                   6285: # Is this a recursive call for a library?
                   6286: #
1.599     albertel 6287: #	if (! exists($metacache{$uri})) {
                   6288: #	    $metacache{$uri}={};
                   6289: #	}
1.171     www      6290:         if ($liburi) {
                   6291: 	    $liburi=&declutter($liburi);
                   6292:             $filename=$liburi;
1.401     bowersj2 6293:         } else {
1.599     albertel 6294: 	    &devalidate_cache_new('meta',$uri);
                   6295: 	    undef(%metaentry);
1.401     bowersj2 6296: 	}
1.140     www      6297:         my %metathesekeys=();
1.73      www      6298:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6299: 	my $metastring;
1.768     albertel 6300: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6301: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6302: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6303: 	    $metastring=&getfile($file);
1.489     albertel 6304: 	}
1.208     albertel 6305:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6306:         my $token;
1.140     www      6307:         undef %metathesekeys;
1.71      www      6308:         while ($token=$parser->get_token) {
1.339     albertel 6309: 	    if ($token->[0] eq 'S') {
                   6310: 		if (defined($token->[2]->{'package'})) {
1.172     www      6311: #
                   6312: # This is a package - get package info
                   6313: #
1.339     albertel 6314: 		    my $package=$token->[2]->{'package'};
                   6315: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6316: 		    if (defined($token->[2]->{'id'})) { 
                   6317: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6318: 		    }
1.599     albertel 6319: 		    if ($metaentry{':packages'}) {
                   6320: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6321: 		    } else {
1.599     albertel 6322: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6323: 		    }
1.736     albertel 6324: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6325: 			my $part=$keyroot;
                   6326: 			$part=~s/^\_//;
1.736     albertel 6327: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6328: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6329: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6330: 			    # ignore package.tab specified default values
                   6331:                             # here &package_tab_default() will fetch those
                   6332: 			    if ($subp eq 'default') { next; }
1.736     albertel 6333: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6334: 			    my $unikey;
                   6335: 			    if ($pack =~ /_0$/) {
                   6336: 				$unikey='parameter_0_'.$name;
                   6337: 				$part=0;
                   6338: 			    } else {
                   6339: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6340: 			    }
1.339     albertel 6341: 			    if ($subp eq 'display') {
                   6342: 				$value.=' [Part: '.$part.']';
                   6343: 			    }
1.599     albertel 6344: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6345: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6346: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6347: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6348: 			    }
1.599     albertel 6349: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6350: 				$metaentry{':'.$unikey}=
                   6351: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6352: 			    }
1.339     albertel 6353: 			}
                   6354: 		    }
                   6355: 		} else {
1.172     www      6356: #
                   6357: # This is not a package - some other kind of start tag
1.339     albertel 6358: #
                   6359: 		    my $entry=$token->[1];
                   6360: 		    my $unikey;
                   6361: 		    if ($entry eq 'import') {
                   6362: 			$unikey='';
                   6363: 		    } else {
                   6364: 			$unikey=$entry;
                   6365: 		    }
                   6366: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6367: 
                   6368: 		    if (defined($token->[2]->{'id'})) { 
                   6369: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6370: 		    }
1.175     www      6371: 
1.339     albertel 6372: 		    if ($entry eq 'import') {
1.175     www      6373: #
                   6374: # Importing a library here
1.339     albertel 6375: #
                   6376: 			if ($depthcount<20) {
                   6377: 			    my $location=$parser->get_text('/import');
                   6378: 			    my $dir=$filename;
                   6379: 			    $dir=~s|[^/]*$||;
                   6380: 			    $location=&filelocation($dir,$location);
1.736     albertel 6381: 			    my $metadata = 
                   6382: 				&metadata($uri,'keys', $location,$unikey,
                   6383: 					  $depthcount+1);
                   6384: 			    foreach my $meta (split(',',$metadata)) {
                   6385: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6386: 				$metathesekeys{$meta}=1;
1.339     albertel 6387: 			    }
                   6388: 			}
                   6389: 		    } else { 
                   6390: 			
                   6391: 			if (defined($token->[2]->{'name'})) { 
                   6392: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6393: 			}
                   6394: 			$metathesekeys{$unikey}=1;
1.736     albertel 6395: 			foreach my $param (@{$token->[3]}) {
                   6396: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6397: 				$token->[2]->{$param};
1.339     albertel 6398: 			}
                   6399: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6400: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6401: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6402: 		 # only ws inside the tag, and not in default, so use default
                   6403: 		 # as value
1.599     albertel 6404: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6405: 			} else {
1.321     albertel 6406: 		  # either something interesting inside the tag or default
                   6407:                   # uninteresting
1.599     albertel 6408: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6409: 			}
1.172     www      6410: # end of not-a-package not-a-library import
1.339     albertel 6411: 		    }
1.172     www      6412: # end of not-a-package start tag
1.339     albertel 6413: 		}
1.172     www      6414: # the next is the end of "start tag"
1.339     albertel 6415: 	    }
                   6416: 	}
1.483     albertel 6417: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6418: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6419: 	    #no specific packages #how's our extension
                   6420: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6421: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6422: 					 \%metathesekeys);
                   6423: 	}
1.599     albertel 6424: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6425: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6426: 		#no specific packages well let's get default then
                   6427: 		if ($key!~/^default&/) { next; }
1.488     albertel 6428: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6429: 					     \%metathesekeys);
                   6430: 	    }
                   6431: 	}
1.338     www      6432: # are there custom rights to evaluate
1.599     albertel 6433: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6434: 
1.338     www      6435:     #
                   6436:     # Importing a rights file here
1.339     albertel 6437:     #
                   6438: 	    unless ($depthcount) {
1.599     albertel 6439: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6440: 		my $dir=$filename;
                   6441: 		$dir=~s|[^/]*$||;
                   6442: 		$location=&filelocation($dir,$location);
1.736     albertel 6443: 		my $rights_metadata =
                   6444: 		    &metadata($uri,'keys',$location,'_rights',
                   6445: 			      $depthcount+1);
                   6446: 		foreach my $rights (split(',',$rights_metadata)) {
                   6447: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6448: 		    $metathesekeys{$rights}=1;
1.339     albertel 6449: 		}
                   6450: 	    }
                   6451: 	}
1.737     albertel 6452: 	# uniqifiy package listing
                   6453: 	my %seen;
                   6454: 	my @uniq_packages =
                   6455: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6456: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6457: 
                   6458: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6459: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6460: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6461: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6462: # this is the end of "was not already recently cached
1.71      www      6463:     }
1.599     albertel 6464:     return $metaentry{':'.$what};
1.261     albertel 6465: }
                   6466: 
1.488     albertel 6467: sub metadata_create_package_def {
1.483     albertel 6468:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6469:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6470:     if ($subp eq 'default') { next; }
                   6471:     
1.599     albertel 6472:     if (defined($metaentry{':packages'})) {
                   6473: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6474:     } else {
1.599     albertel 6475: 	$metaentry{':packages'}=$package;
1.483     albertel 6476:     }
                   6477:     my $value=$packagetab{$key};
                   6478:     my $unikey;
                   6479:     $unikey='parameter_0_'.$name;
1.599     albertel 6480:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6481:     $$metathesekeys{$unikey}=1;
1.599     albertel 6482:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6483: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6484:     }
1.599     albertel 6485:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6486: 	$metaentry{':'.$unikey}=
                   6487: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6488:     }
                   6489: }
                   6490: 
1.261     albertel 6491: sub metadata_generate_part0 {
                   6492:     my ($metadata,$metacache,$uri) = @_;
                   6493:     my %allnames;
1.737     albertel 6494:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6495: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6496: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6497: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6498: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6499: 	    $allnames{$name}=$part;
                   6500: 	  }
                   6501: 	}
                   6502:     }
                   6503:     foreach my $name (keys(%allnames)) {
                   6504:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6505:       my $key=":parameter_0_$name";
1.261     albertel 6506:       $$metacache{"$key.part"}='0';
                   6507:       $$metacache{"$key.name"}=$name;
1.428     albertel 6508:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6509: 					   $allnames{$name}.'_'.$name.
                   6510: 					   '.type'};
1.428     albertel 6511:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6512: 			     '.display'};
1.644     www      6513:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6514:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6515:       $$metacache{"$key.display"}=$olddis;
                   6516:     }
1.71      www      6517: }
                   6518: 
1.764     albertel 6519: # ------------------------------------------------------ Devalidate title cache
                   6520: 
                   6521: sub devalidate_title_cache {
                   6522:     my ($url)=@_;
                   6523:     if (!$env{'request.course.id'}) { return; }
                   6524:     my $symb=&symbread($url);
                   6525:     if (!$symb) { return; }
                   6526:     my $key=$env{'request.course.id'}."\0".$symb;
                   6527:     &devalidate_cache_new('title',$key);
                   6528: }
                   6529: 
1.301     www      6530: # ------------------------------------------------- Get the title of a resource
                   6531: 
                   6532: sub gettitle {
                   6533:     my $urlsymb=shift;
                   6534:     my $symb=&symbread($urlsymb);
1.534     albertel 6535:     if ($symb) {
1.620     albertel 6536: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6537: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6538: 	if (defined($cached)) { 
                   6539: 	    return $result;
                   6540: 	}
1.534     albertel 6541: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6542: 	my $title='';
                   6543: 	my %bighash;
1.620     albertel 6544: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6545: 		&GDBM_READER(),0640)) {
                   6546: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6547: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6548: 	    untie %bighash;
                   6549: 	}
                   6550: 	$title=~s/\&colon\;/\:/gs;
                   6551: 	if ($title) {
1.599     albertel 6552: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6553: 	}
                   6554: 	$urlsymb=$url;
                   6555:     }
                   6556:     my $title=&metadata($urlsymb,'title');
                   6557:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6558:     return $title;
1.301     www      6559: }
1.613     albertel 6560: 
1.614     albertel 6561: sub get_slot {
                   6562:     my ($which,$cnum,$cdom)=@_;
                   6563:     if (!$cnum || !$cdom) {
1.790     albertel 6564: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6565: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6566: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6567:     }
1.703     albertel 6568:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6569:     my %slotinfo;
                   6570:     if (exists($remembered{$key})) {
                   6571: 	$slotinfo{$which} = $remembered{$key};
                   6572:     } else {
                   6573: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6574: 	&Apache::lonhomework::showhash(%slotinfo);
                   6575: 	my ($tmp)=keys(%slotinfo);
                   6576: 	if ($tmp=~/^error:/) { return (); }
                   6577: 	$remembered{$key} = $slotinfo{$which};
                   6578:     }
1.616     albertel 6579:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6580: 	return %{$slotinfo{$which}};
                   6581:     }
                   6582:     return $slotinfo{$which};
1.614     albertel 6583: }
1.31      www      6584: # ------------------------------------------------- Update symbolic store links
                   6585: 
                   6586: sub symblist {
                   6587:     my ($mapname,%newhash)=@_;
1.438     www      6588:     $mapname=&deversion(&declutter($mapname));
1.31      www      6589:     my %hash;
1.620     albertel 6590:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6591:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6592:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6593: 	    foreach my $url (keys %newhash) {
                   6594: 		next if ($url eq 'last_known'
                   6595: 			 && $env{'form.no_update_last_known'});
                   6596: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6597: 						    $newhash{$url}->[1],
                   6598: 						    $newhash{$url}->[0]);
1.191     harris41 6599:             }
1.31      www      6600:             if (untie(%hash)) {
                   6601: 		return 'ok';
                   6602:             }
                   6603:         }
                   6604:     }
                   6605:     return 'error';
1.212     www      6606: }
                   6607: 
                   6608: # --------------------------------------------------------------- Verify a symb
                   6609: 
                   6610: sub symbverify {
1.510     www      6611:     my ($symb,$thisurl)=@_;
                   6612:     my $thisfn=$thisurl;
1.439     www      6613:     $thisfn=&declutter($thisfn);
1.215     www      6614: # direct jump to resource in page or to a sequence - will construct own symbs
                   6615:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6616: # check URL part
1.409     www      6617:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6618: 
1.431     www      6619:     unless ($url eq $thisfn) { return 0; }
1.213     www      6620: 
1.216     www      6621:     $symb=&symbclean($symb);
1.510     www      6622:     $thisurl=&deversion($thisurl);
1.439     www      6623:     $thisfn=&deversion($thisfn);
1.213     www      6624: 
                   6625:     my %bighash;
                   6626:     my $okay=0;
1.431     www      6627: 
1.620     albertel 6628:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6629:                             &GDBM_READER(),0640)) {
1.510     www      6630:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6631:         unless ($ids) { 
1.510     www      6632:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6633:         }
                   6634:         if ($ids) {
                   6635: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6636: 	    foreach my $id (split(/\,/,$ids)) {
                   6637: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6638:                if (
                   6639:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6640:    eq $symb) { 
1.620     albertel 6641: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6642: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6643: 		       $okay=1; 
                   6644: 		   }
                   6645: 	       }
1.216     www      6646: 	   }
                   6647:         }
1.213     www      6648: 	untie(%bighash);
                   6649:     }
                   6650:     return $okay;
1.31      www      6651: }
                   6652: 
1.210     www      6653: # --------------------------------------------------------------- Clean-up symb
                   6654: 
                   6655: sub symbclean {
                   6656:     my $symb=shift;
1.568     albertel 6657:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6658: # remove version from map
                   6659:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6660: 
1.210     www      6661: # remove version from URL
                   6662:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6663: 
1.507     www      6664: # remove wrapper
                   6665: 
1.510     www      6666:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6667:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6668:     return $symb;
1.409     www      6669: }
                   6670: 
                   6671: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6672: 
                   6673: sub encode_symb {
                   6674:     my ($map,$resid,$url)=@_;
                   6675:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6676: }
1.409     www      6677: 
                   6678: sub decode_symb {
1.568     albertel 6679:     my $symb=shift;
                   6680:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6681:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6682:     return (&fixversion($map),$resid,&fixversion($url));
                   6683: }
                   6684: 
                   6685: sub fixversion {
                   6686:     my $fn=shift;
1.609     banghart 6687:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6688:     my %bighash;
                   6689:     my $uri=&clutter($fn);
1.620     albertel 6690:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6691: # is this cached?
1.599     albertel 6692:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6693:     if (defined($cached)) { return $result; }
                   6694: # unfortunately not cached, or expired
1.620     albertel 6695:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6696: 	    &GDBM_READER(),0640)) {
                   6697:  	if ($bighash{'version_'.$uri}) {
                   6698:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6699:  	    unless (($version eq 'mostrecent') || 
                   6700: 		    ($version==&getversion($uri))) {
1.440     www      6701:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6702:  	    }
                   6703:  	}
                   6704:  	untie %bighash;
1.413     www      6705:     }
1.599     albertel 6706:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6707: }
                   6708: 
                   6709: sub deversion {
                   6710:     my $url=shift;
                   6711:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6712:     return $url;
1.210     www      6713: }
                   6714: 
1.31      www      6715: # ------------------------------------------------------ Return symb list entry
                   6716: 
                   6717: sub symbread {
1.249     www      6718:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6719:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6720:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6721: # no filename provided? try from environment
1.44      www      6722:     unless ($thisfn) {
1.620     albertel 6723:         if ($env{'request.symb'}) {
                   6724: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6725: 	}
1.620     albertel 6726: 	$thisfn=$env{'request.filename'};
1.44      www      6727:     }
1.569     albertel 6728:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6729: # is that filename actually a symb? Verify, clean, and return
                   6730:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6731: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6732: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6733: 	}
1.242     www      6734:     }
1.44      www      6735:     $thisfn=declutter($thisfn);
1.31      www      6736:     my %hash;
1.37      www      6737:     my %bighash;
                   6738:     my $syval='';
1.620     albertel 6739:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6740:         my $targetfn = $thisfn;
1.609     banghart 6741:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6742:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6743:         }
1.687     albertel 6744: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6745: 	    $targetfn=$1;
                   6746: 	}
1.620     albertel 6747:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6748:                       &GDBM_READER(),0640)) {
1.481     raeburn  6749: 	    $syval=$hash{$targetfn};
1.37      www      6750:             untie(%hash);
                   6751:         }
                   6752: # ---------------------------------------------------------- There was an entry
                   6753:         if ($syval) {
1.601     albertel 6754: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6755: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6756: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6757: 		    #return $env{$cache_str}='';
1.601     albertel 6758: 		#}    
                   6759: 		#$syval.=$1;
                   6760: 	    #}
1.37      www      6761:         } else {
                   6762: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6763:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6764:                             &GDBM_READER(),0640)) {
1.37      www      6765: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6766:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6767:               unless ($ids) { 
                   6768:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6769:               }
                   6770:               unless ($ids) {
                   6771: # alias?
                   6772: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6773:               }
1.37      www      6774:               if ($ids) {
                   6775: # ------------------------------------------------------------------- Has ID(s)
                   6776:                  my @possibilities=split(/\,/,$ids);
1.39      www      6777:                  if ($#possibilities==0) {
                   6778: # ----------------------------------------------- There is only one possibility
1.37      www      6779: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6780: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6781: 						    $resid,$thisfn);
1.249     www      6782:                  } elsif (!$donotrecurse) {
1.39      www      6783: # ------------------------------------------ There is more than one possibility
                   6784:                      my $realpossible=0;
1.800     albertel 6785:                      foreach my $id (@possibilities) {
                   6786: 			 my $file=$bighash{'src_'.$id};
1.39      www      6787:                          if (&allowed('bre',$file)) {
1.800     albertel 6788:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6789:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6790: 				$realpossible++;
1.626     albertel 6791:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6792: 						    $resid,$thisfn);
1.39      www      6793:                             }
                   6794: 			 }
1.191     harris41 6795:                      }
1.39      www      6796: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6797:                  } else {
                   6798:                      $syval='';
1.37      www      6799:                  }
                   6800: 	      }
                   6801:               untie(%bighash)
1.481     raeburn  6802:            }
1.31      www      6803:         }
1.62      www      6804:         if ($syval) {
1.620     albertel 6805: 	    return $env{$cache_str}=$syval;
1.62      www      6806:         }
1.31      www      6807:     }
1.44      www      6808:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6809:     return $env{$cache_str}='';
1.31      www      6810: }
                   6811: 
                   6812: # ---------------------------------------------------------- Return random seed
                   6813: 
1.32      www      6814: sub numval {
                   6815:     my $txt=shift;
                   6816:     $txt=~tr/A-J/0-9/;
                   6817:     $txt=~tr/a-j/0-9/;
                   6818:     $txt=~tr/K-T/0-9/;
                   6819:     $txt=~tr/k-t/0-9/;
                   6820:     $txt=~tr/U-Z/0-5/;
                   6821:     $txt=~tr/u-z/0-5/;
                   6822:     $txt=~s/\D//g;
1.564     albertel 6823:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6824:     return int($txt);
1.368     albertel 6825: }
                   6826: 
1.484     albertel 6827: sub numval2 {
                   6828:     my $txt=shift;
                   6829:     $txt=~tr/A-J/0-9/;
                   6830:     $txt=~tr/a-j/0-9/;
                   6831:     $txt=~tr/K-T/0-9/;
                   6832:     $txt=~tr/k-t/0-9/;
                   6833:     $txt=~tr/U-Z/0-5/;
                   6834:     $txt=~tr/u-z/0-5/;
                   6835:     $txt=~s/\D//g;
                   6836:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6837:     my $total;
                   6838:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6839:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6840:     return int($total);
                   6841: }
                   6842: 
1.575     albertel 6843: sub numval3 {
                   6844:     use integer;
                   6845:     my $txt=shift;
                   6846:     $txt=~tr/A-J/0-9/;
                   6847:     $txt=~tr/a-j/0-9/;
                   6848:     $txt=~tr/K-T/0-9/;
                   6849:     $txt=~tr/k-t/0-9/;
                   6850:     $txt=~tr/U-Z/0-5/;
                   6851:     $txt=~tr/u-z/0-5/;
                   6852:     $txt=~s/\D//g;
                   6853:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6854:     my $total;
                   6855:     foreach my $val (@txts) { $total+=$val; }
                   6856:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6857:     return $total;
                   6858: }
                   6859: 
1.675     albertel 6860: sub digest {
                   6861:     my ($data)=@_;
                   6862:     my $digest=&Digest::MD5::md5($data);
                   6863:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6864:     my ($e,$f);
                   6865:     {
                   6866:         use integer;
                   6867:         $e=($a+$b);
                   6868:         $f=($c+$d);
                   6869:         if ($_64bit) {
                   6870:             $e=(($e<<32)>>32);
                   6871:             $f=(($f<<32)>>32);
                   6872:         }
                   6873:     }
                   6874:     if (wantarray) {
                   6875: 	return ($e,$f);
                   6876:     } else {
                   6877: 	my $g;
                   6878: 	{
                   6879: 	    use integer;
                   6880: 	    $g=($e+$f);
                   6881: 	    if ($_64bit) {
                   6882: 		$g=(($g<<32)>>32);
                   6883: 	    }
                   6884: 	}
                   6885: 	return $g;
                   6886:     }
                   6887: }
                   6888: 
1.368     albertel 6889: sub latest_rnd_algorithm_id {
1.675     albertel 6890:     return '64bit5';
1.366     albertel 6891: }
1.32      www      6892: 
1.503     albertel 6893: sub get_rand_alg {
                   6894:     my ($courseid)=@_;
1.790     albertel 6895:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6896:     if ($courseid) {
1.620     albertel 6897: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6898:     }
                   6899:     return &latest_rnd_algorithm_id();
                   6900: }
                   6901: 
1.562     albertel 6902: sub validCODE {
                   6903:     my ($CODE)=@_;
                   6904:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6905:     return 0;
                   6906: }
                   6907: 
1.491     albertel 6908: sub getCODE {
1.620     albertel 6909:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6910:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6911: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6912: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6913: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6914:     }
                   6915:     return undef;
                   6916: }
                   6917: 
1.31      www      6918: sub rndseed {
1.155     albertel 6919:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6920: 
1.790     albertel 6921:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6922:     if (!$symb) {
1.366     albertel 6923: 	unless ($symb=$wsymb) { return time; }
                   6924:     }
                   6925:     if (!$courseid) { $courseid=$wcourseid; }
                   6926:     if (!$domain) { $domain=$wdomain; }
                   6927:     if (!$username) { $username=$wusername }
1.503     albertel 6928:     my $which=&get_rand_alg();
1.803     albertel 6929: 
1.491     albertel 6930:     if (defined(&getCODE())) {
1.675     albertel 6931: 	if ($which eq '64bit5') {
                   6932: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6933: 	} elsif ($which eq '64bit4') {
1.575     albertel 6934: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6935: 	} else {
                   6936: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6937: 	}
1.675     albertel 6938:     } elsif ($which eq '64bit5') {
                   6939: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6940:     } elsif ($which eq '64bit4') {
                   6941: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6942:     } elsif ($which eq '64bit3') {
                   6943: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6944:     } elsif ($which eq '64bit2') {
                   6945: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6946:     } elsif ($which eq '64bit') {
                   6947: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6948:     }
                   6949:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6950: }
                   6951: 
                   6952: sub rndseed_32bit {
                   6953:     my ($symb,$courseid,$domain,$username)=@_;
                   6954:     {
                   6955: 	use integer;
                   6956: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6957: 	my $symbseed=numval($symb) << 22;
                   6958: 	my $namechck=unpack("%32C*",$username) << 17;
                   6959: 	my $nameseed=numval($username) << 12;
                   6960: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6961: 	my $courseseed=unpack("%32C*",$courseid);
                   6962: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6963: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6964: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6965: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6966: 	return $num;
                   6967:     }
                   6968: }
                   6969: 
                   6970: sub rndseed_64bit {
                   6971:     my ($symb,$courseid,$domain,$username)=@_;
                   6972:     {
                   6973: 	use integer;
                   6974: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6975: 	my $symbseed=numval($symb) << 10;
                   6976: 	my $namechck=unpack("%32S*",$username);
                   6977: 	
                   6978: 	my $nameseed=numval($username) << 21;
                   6979: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6980: 	my $courseseed=unpack("%32S*",$courseid);
                   6981: 	
                   6982: 	my $num1=$symbchck+$symbseed+$namechck;
                   6983: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6984: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6985: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6986: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6987: 	return "$num1,$num2";
1.155     albertel 6988:     }
1.366     albertel 6989: }
                   6990: 
1.443     albertel 6991: sub rndseed_64bit2 {
                   6992:     my ($symb,$courseid,$domain,$username)=@_;
                   6993:     {
                   6994: 	use integer;
                   6995: 	# strings need to be an even # of cahracters long, it it is odd the
                   6996:         # last characters gets thrown away
                   6997: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6998: 	my $symbseed=numval($symb) << 10;
                   6999: 	my $namechck=unpack("%32S*",$username.' ');
                   7000: 	
                   7001: 	my $nameseed=numval($username) << 21;
1.501     albertel 7002: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7003: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7004: 	
                   7005: 	my $num1=$symbchck+$symbseed+$namechck;
                   7006: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7007: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7008: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7009: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7010: 	return "$num1,$num2";
                   7011:     }
                   7012: }
                   7013: 
                   7014: sub rndseed_64bit3 {
                   7015:     my ($symb,$courseid,$domain,$username)=@_;
                   7016:     {
                   7017: 	use integer;
                   7018: 	# strings need to be an even # of cahracters long, it it is odd the
                   7019:         # last characters gets thrown away
                   7020: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7021: 	my $symbseed=numval2($symb) << 10;
                   7022: 	my $namechck=unpack("%32S*",$username.' ');
                   7023: 	
                   7024: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7025: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7026: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7027: 	
                   7028: 	my $num1=$symbchck+$symbseed+$namechck;
                   7029: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7030: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7031: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7032: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7033: 	
1.503     albertel 7034: 	return "$num1:$num2";
1.443     albertel 7035:     }
                   7036: }
                   7037: 
1.575     albertel 7038: sub rndseed_64bit4 {
                   7039:     my ($symb,$courseid,$domain,$username)=@_;
                   7040:     {
                   7041: 	use integer;
                   7042: 	# strings need to be an even # of cahracters long, it it is odd the
                   7043:         # last characters gets thrown away
                   7044: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7045: 	my $symbseed=numval3($symb) << 10;
                   7046: 	my $namechck=unpack("%32S*",$username.' ');
                   7047: 	
                   7048: 	my $nameseed=numval3($username) << 21;
                   7049: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7050: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7051: 	
                   7052: 	my $num1=$symbchck+$symbseed+$namechck;
                   7053: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7054: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7055: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7056: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7057: 	
                   7058: 	return "$num1:$num2";
                   7059:     }
                   7060: }
                   7061: 
1.675     albertel 7062: sub rndseed_64bit5 {
                   7063:     my ($symb,$courseid,$domain,$username)=@_;
                   7064:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7065:     return "$num1:$num2";
                   7066: }
                   7067: 
1.366     albertel 7068: sub rndseed_CODE_64bit {
                   7069:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7070:     {
1.366     albertel 7071: 	use integer;
1.443     albertel 7072: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7073: 	my $symbseed=numval2($symb);
1.491     albertel 7074: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7075: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7076: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7077: 	my $num1=$symbseed+$CODEchck;
                   7078: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7079: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7080: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7081: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7082: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7083: 	return "$num1:$num2";
1.366     albertel 7084:     }
                   7085: }
                   7086: 
1.575     albertel 7087: sub rndseed_CODE_64bit4 {
                   7088:     my ($symb,$courseid,$domain,$username)=@_;
                   7089:     {
                   7090: 	use integer;
                   7091: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7092: 	my $symbseed=numval3($symb);
                   7093: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7094: 	my $CODEseed=numval3(&getCODE());
                   7095: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7096: 	my $num1=$symbseed+$CODEchck;
                   7097: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7098: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7099: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7100: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7101: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7102: 	return "$num1:$num2";
                   7103:     }
                   7104: }
                   7105: 
1.675     albertel 7106: sub rndseed_CODE_64bit5 {
                   7107:     my ($symb,$courseid,$domain,$username)=@_;
                   7108:     my $code = &getCODE();
                   7109:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7110:     return "$num1:$num2";
                   7111: }
                   7112: 
1.366     albertel 7113: sub setup_random_from_rndseed {
                   7114:     my ($rndseed)=@_;
1.503     albertel 7115:     if ($rndseed =~/([,:])/) {
                   7116: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7117: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7118:     } else {
                   7119: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7120:     }
1.36      albertel 7121: }
                   7122: 
1.474     albertel 7123: sub latest_receipt_algorithm_id {
1.835     albertel 7124:     return 'receipt3';
1.474     albertel 7125: }
                   7126: 
1.480     www      7127: sub recunique {
                   7128:     my $fucourseid=shift;
                   7129:     my $unique;
1.835     albertel 7130:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7131: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7132: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7133:     } else {
                   7134: 	$unique=$perlvar{'lonReceipt'};
                   7135:     }
                   7136:     return unpack("%32C*",$unique);
                   7137: }
                   7138: 
                   7139: sub recprefix {
                   7140:     my $fucourseid=shift;
                   7141:     my $prefix;
1.835     albertel 7142:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7143: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7144: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7145:     } else {
                   7146: 	$prefix=$perlvar{'lonHostID'};
                   7147:     }
                   7148:     return unpack("%32C*",$prefix);
                   7149: }
                   7150: 
1.76      www      7151: sub ireceipt {
1.474     albertel 7152:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7153: 
                   7154:     my $return =&recprefix($fucourseid).'-';
                   7155: 
                   7156:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7157: 	$env{'request.state'} eq 'construct') {
                   7158: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7159: 	return $return;
                   7160:     }
                   7161: 
1.76      www      7162:     my $cuname=unpack("%32C*",$funame);
                   7163:     my $cudom=unpack("%32C*",$fudom);
                   7164:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7165:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7166:     my $cunique=&recunique($fucourseid);
1.474     albertel 7167:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7168:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7169: 
1.790     albertel 7170: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7171: 			       
                   7172: 	$return.= ($cunique%$cuname+
                   7173: 		   $cunique%$cudom+
                   7174: 		   $cusymb%$cuname+
                   7175: 		   $cusymb%$cudom+
                   7176: 		   $cucourseid%$cuname+
                   7177: 		   $cucourseid%$cudom+
                   7178: 		   $cpart%$cuname+
                   7179: 		   $cpart%$cudom);
                   7180:     } else {
                   7181: 	$return.= ($cunique%$cuname+
                   7182: 		   $cunique%$cudom+
                   7183: 		   $cusymb%$cuname+
                   7184: 		   $cusymb%$cudom+
                   7185: 		   $cucourseid%$cuname+
                   7186: 		   $cucourseid%$cudom);
                   7187:     }
                   7188:     return $return;
1.76      www      7189: }
                   7190: 
                   7191: sub receipt {
1.474     albertel 7192:     my ($part)=@_;
1.790     albertel 7193:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7194:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7195: }
1.260     ng       7196: 
1.790     albertel 7197: sub whichuser {
                   7198:     my ($passedsymb)=@_;
                   7199:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7200:     if (defined($env{'form.grade_symb'})) {
                   7201: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7202: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7203: 	if (!$allowed &&
                   7204: 	    exists($env{'request.course.sec'}) &&
                   7205: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7206: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7207: 			      '/'.$env{'request.course.sec'});
                   7208: 	}
                   7209: 	if ($allowed) {
                   7210: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7211: 	    $courseid=$tmp_courseid;
                   7212: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7213: 	    ($name)=&get_env_multiple('form.grade_username');
                   7214: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7215: 	}
                   7216:     }
                   7217:     if (!$passedsymb) {
                   7218: 	$symb=&symbread();
                   7219:     } else {
                   7220: 	$symb=$passedsymb;
                   7221:     }
                   7222:     $courseid=$env{'request.course.id'};
                   7223:     $domain=$env{'user.domain'};
                   7224:     $name=$env{'user.name'};
                   7225:     if ($name eq 'public' && $domain eq 'public') {
                   7226: 	if (!defined($env{'form.username'})) {
                   7227: 	    $env{'form.username'}.=time.rand(10000000);
                   7228: 	}
                   7229: 	$name.=$env{'form.username'};
                   7230:     }
                   7231:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7232: 
                   7233: }
                   7234: 
1.36      albertel 7235: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7236: # returns either the contents of the file or 
                   7237: # -1 if the file doesn't exist
1.481     raeburn  7238: #
                   7239: # if the target is a file that was uploaded via DOCS, 
                   7240: # a check will be made to see if a current copy exists on the local server,
                   7241: # if it does this will be served, otherwise a copy will be retrieved from
                   7242: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7243: # the local server.   
1.472     albertel 7244: 
1.36      albertel 7245: sub getfile {
1.538     albertel 7246:     my ($file) = @_;
1.609     banghart 7247:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7248:     &repcopy($file);
                   7249:     return &readfile($file);
                   7250: }
                   7251: 
                   7252: sub repcopy_userfile {
                   7253:     my ($file)=@_;
1.609     banghart 7254:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7255:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7256:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7257: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7258:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7259:     if (-e "$file") {
1.828     www      7260: # we already have a local copy, check it out
1.538     albertel 7261: 	my @fileinfo = stat($file);
1.828     www      7262: 	my $rtncode;
                   7263: 	my $info;
1.538     albertel 7264: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7265: 	if ($lwpresp ne 'ok') {
1.828     www      7266: # there is no such file anymore, even though we had a local copy
1.482     albertel 7267: 	    if ($rtncode eq '404') {
1.538     albertel 7268: 		unlink($file);
1.482     albertel 7269: 	    }
                   7270: 	    return -1;
                   7271: 	}
                   7272: 	if ($info < $fileinfo[9]) {
1.828     www      7273: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7274: 	    return 'ok';
1.828     www      7275: 	} else {
                   7276: # the file is outdated, get rid of it
                   7277: 	    unlink($file);
1.482     albertel 7278: 	}
1.828     www      7279:     }
                   7280: # one way or the other, at this point, we don't have the file
                   7281: # construct the correct path for the file
                   7282:     my @parts = ($cdom,$cnum); 
                   7283:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7284: 	push @parts, split(/\//,$1);
                   7285:     }
                   7286:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7287:     foreach my $part (@parts) {
                   7288: 	$path .= '/'.$part;
                   7289: 	if (!-e $path) {
                   7290: 	    mkdir($path,0770);
1.482     albertel 7291: 	}
                   7292:     }
1.828     www      7293: # now the path exists for sure
                   7294: # get a user agent
                   7295:     my $ua=new LWP::UserAgent;
                   7296:     my $transferfile=$file.'.in.transfer';
                   7297: # FIXME: this should flock
                   7298:     if (-e $transferfile) { return 'ok'; }
                   7299:     my $request;
                   7300:     $uri=~s/^\///;
1.838     albertel 7301:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7302:     my $response=$ua->request($request,$transferfile);
                   7303: # did it work?
                   7304:     if ($response->is_error()) {
                   7305: 	unlink($transferfile);
                   7306: 	&logthis("Userfile repcopy failed for $uri");
                   7307: 	return -1;
                   7308:     }
                   7309: # worked, rename the transfer file
                   7310:     rename($transferfile,$file);
1.607     raeburn  7311:     return 'ok';
1.481     raeburn  7312: }
                   7313: 
1.517     albertel 7314: sub tokenwrapper {
                   7315:     my $uri=shift;
1.552     albertel 7316:     $uri=~s|^http\://([^/]+)||;
                   7317:     $uri=~s|^/||;
1.620     albertel 7318:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7319:     my $token=$1;
1.552     albertel 7320:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7321:     if ($udom && $uname && $file) {
                   7322: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7323:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7324:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7325:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7326:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7327:     } else {
                   7328:         return '/adm/notfound.html';
                   7329:     }
                   7330: }
                   7331: 
1.828     www      7332: # call with reqtype HEAD: get last modification time
                   7333: # call with reqtype GET: get the file contents
                   7334: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7335: #
1.481     raeburn  7336: sub getuploaded {
                   7337:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7338:     $uri=~s/^\///;
1.838     albertel 7339:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7340:     my $ua=new LWP::UserAgent;
                   7341:     my $request=new HTTP::Request($reqtype,$uri);
                   7342:     my $response=$ua->request($request);
                   7343:     $$rtncode = $response->code;
1.482     albertel 7344:     if (! $response->is_success()) {
                   7345: 	return 'failed';
                   7346:     }      
                   7347:     if ($reqtype eq 'HEAD') {
1.486     www      7348: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7349:     } elsif ($reqtype eq 'GET') {
                   7350: 	$$info = $response->content;
1.472     albertel 7351:     }
1.482     albertel 7352:     return 'ok';
1.36      albertel 7353: }
                   7354: 
1.481     raeburn  7355: sub readfile {
                   7356:     my $file = shift;
                   7357:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7358:     my $fh;
                   7359:     open($fh,"<$file");
                   7360:     my $a='';
1.800     albertel 7361:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7362:     return $a;
                   7363: }
                   7364: 
1.36      albertel 7365: sub filelocation {
1.590     banghart 7366:     my ($dir,$file) = @_;
                   7367:     my $location;
                   7368:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7369: 
                   7370:     if ($file =~ m-^/adm/-) {
                   7371: 	$file=~s-^/adm/wrapper/-/-;
                   7372: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7373:     }
1.590     banghart 7374:     if ($file=~m:^/~:) { # is a contruction space reference
                   7375:         $location = $file;
                   7376:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7377:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7378: 	# is a correct contruction space reference
                   7379:         $location = $file;
1.609     banghart 7380:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7381:         my ($udom,$uname,$filename)=
1.811     albertel 7382:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7383:         my $home=&homeserver($uname,$udom);
                   7384:         my $is_me=0;
                   7385:         my @ids=&current_machine_ids();
                   7386:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7387:         if ($is_me) {
1.740     www      7388:   	    $location=&propath($udom,$uname).
1.590     banghart 7389:   	      '/userfiles/'.$filename;
                   7390:         } else {
                   7391:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7392:   	      $udom.'/'.$uname.'/'.$filename;
                   7393:         }
                   7394:     } else {
                   7395:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7396:         $file=~s:^/res/:/:;
                   7397:         if ( !( $file =~ m:^/:) ) {
                   7398:             $location = $dir. '/'.$file;
                   7399:         } else {
                   7400:             $location = '/home/httpd/html/res'.$file;
                   7401:         }
1.59      albertel 7402:     }
1.590     banghart 7403:     $location=~s://+:/:g; # remove duplicate /
                   7404:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7405:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7406:     return $location;
1.46      www      7407: }
1.36      albertel 7408: 
1.46      www      7409: sub hreflocation {
                   7410:     my ($dir,$file)=@_;
1.460     albertel 7411:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7412: 	$file=filelocation($dir,$file);
1.700     albertel 7413:     } elsif ($file=~m-^/adm/-) {
                   7414: 	$file=~s-^/adm/wrapper/-/-;
                   7415: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7416:     }
                   7417:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7418: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7419:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7420: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7421:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7422: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7423: 	    -/uploaded/$1/$2/-x;
1.46      www      7424:     }
1.462     albertel 7425:     return $file;
1.465     albertel 7426: }
                   7427: 
                   7428: sub current_machine_domains {
1.838     albertel 7429:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7430:     my @domains;
1.838     albertel 7431:     my %hostname = &all_hostnames();
1.465     albertel 7432:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7433: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7434: 	if ($hostname eq $name) {
1.844     albertel 7435: 	    push(@domains,&host_domain($id));
1.465     albertel 7436: 	}
                   7437:     }
                   7438:     return @domains;
                   7439: }
                   7440: 
                   7441: sub current_machine_ids {
1.838     albertel 7442:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7443:     my @ids;
1.838     albertel 7444:     my %hostname = &all_hostnames();
1.465     albertel 7445:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7446: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7447: 	if ($hostname eq $name) {
                   7448: 	    push(@ids,$id);
                   7449: 	}
                   7450:     }
                   7451:     return @ids;
1.31      www      7452: }
                   7453: 
1.824     raeburn  7454: sub additional_machine_domains {
                   7455:     my @domains;
                   7456:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7457:     while( my $line = <$fh>) {
                   7458:         $line =~ s/\s//g;
                   7459:         push(@domains,$line);
                   7460:     }
                   7461:     return @domains;
                   7462: }
                   7463: 
                   7464: sub default_login_domain {
                   7465:     my $domain = $perlvar{'lonDefDomain'};
                   7466:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7467:     foreach my $posdom (&current_machine_domains(),
                   7468:                         &additional_machine_domains()) {
                   7469:         if (lc($posdom) eq lc($testdomain)) {
                   7470:             $domain=$posdom;
                   7471:             last;
                   7472:         }
                   7473:     }
                   7474:     return $domain;
                   7475: }
                   7476: 
1.31      www      7477: # ------------------------------------------------------------- Declutters URLs
                   7478: 
                   7479: sub declutter {
                   7480:     my $thisfn=shift;
1.569     albertel 7481:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7482:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7483:     $thisfn=~s/^\///;
1.697     albertel 7484:     $thisfn=~s|^adm/wrapper/||;
                   7485:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7486:     $thisfn=~s/^res\///;
1.235     www      7487:     $thisfn=~s/\?.+$//;
1.268     www      7488:     return $thisfn;
                   7489: }
                   7490: 
                   7491: # ------------------------------------------------------------- Clutter up URLs
                   7492: 
                   7493: sub clutter {
                   7494:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7495:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7496:        $thisfn='/res'.$thisfn; 
                   7497:     }
1.694     albertel 7498:     if ($thisfn !~m|/adm|) {
1.695     albertel 7499: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7500: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7501: 	} else {
                   7502: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7503: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7504: 	    if ($embstyle eq 'ssi'
                   7505: 		|| ($embstyle eq 'hdn')
                   7506: 		|| ($embstyle eq 'rat')
                   7507: 		|| ($embstyle eq 'prv')
                   7508: 		|| ($embstyle eq 'ign')) {
                   7509: 		#do nothing with these
                   7510: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7511: 		|| ($embstyle eq 'emb')
                   7512: 		|| ($embstyle eq 'wrp')) {
                   7513: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7514: 	    } elsif ($embstyle eq 'unk'
                   7515: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7516: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7517: 	    } else {
1.718     www      7518: #		&logthis("Got a blank emb style");
1.695     albertel 7519: 	    }
1.694     albertel 7520: 	}
                   7521:     }
1.31      www      7522:     return $thisfn;
1.12      www      7523: }
                   7524: 
1.787     albertel 7525: sub clutter_with_no_wrapper {
                   7526:     my $uri = &clutter(shift);
                   7527:     if ($uri =~ m-^/adm/-) {
                   7528: 	$uri =~ s-^/adm/wrapper/-/-;
                   7529: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7530:     }
                   7531:     return $uri;
                   7532: }
                   7533: 
1.557     albertel 7534: sub freeze_escape {
                   7535:     my ($value)=@_;
                   7536:     if (ref($value)) {
                   7537: 	$value=&nfreeze($value);
                   7538: 	return '__FROZEN__'.&escape($value);
                   7539:     }
                   7540:     return &escape($value);
                   7541: }
                   7542: 
1.11      www      7543: 
1.557     albertel 7544: sub thaw_unescape {
                   7545:     my ($value)=@_;
                   7546:     if ($value =~ /^__FROZEN__/) {
                   7547: 	substr($value,0,10,undef);
                   7548: 	$value=&unescape($value);
                   7549: 	return &thaw($value);
                   7550:     }
                   7551:     return &unescape($value);
                   7552: }
                   7553: 
1.436     albertel 7554: sub correct_line_ends {
                   7555:     my ($result)=@_;
                   7556:     $$result =~s/\r\n/\n/mg;
                   7557:     $$result =~s/\r/\n/mg;
1.415     albertel 7558: }
1.1       albertel 7559: # ================================================================ Main Program
                   7560: 
1.184     www      7561: sub goodbye {
1.204     albertel 7562:    &logthis("Starting Shut down");
1.443     albertel 7563: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7564:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7565: #converted
1.599     albertel 7566: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7567:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7568: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7569: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7570: #1.1 only
1.599     albertel 7571: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7572: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7573: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7574: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7575:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7576:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7577:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7578:    &flushcourselogs();
                   7579:    &logthis("Shutting down");
                   7580: }
                   7581: 
1.179     www      7582: BEGIN {
1.228     harris41 7583: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7584:     unless ($readit) {
1.217     harris41 7585: {
1.781     raeburn  7586:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7587:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7588: }
1.1       albertel 7589: 
1.327     albertel 7590: # ------------------------------------------------------------ Read domain file
                   7591: {
1.846     albertel 7592:     my %domain;
                   7593: 
1.448     albertel 7594:     my $fh;
                   7595:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7596: 	while (my $line = <$fh>) {
1.846     albertel 7597: 	    next if ($line =~ /^(\#|\s*$ )/);
1.403     www      7598: 
1.846     albertel 7599: 	    chomp($line);
                   7600: 	    my ($name,@elements) =  split(/:/,$line,9);
                   7601: 	    my %this_domain;
                   7602: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7603: 			       'lang_def', 'city', 'longi', 'lati',
                   7604: 			       'primary') {
                   7605: 		$this_domain{$field} = shift(@elements);
                   7606: 	    }
                   7607: 	    $domain{$name} = \%this_domain;
1.327     albertel 7608: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7609: 	}
1.327     albertel 7610:     }
1.448     albertel 7611:     close ($fh);
1.846     albertel 7612: 
                   7613:     sub domain {
                   7614: 	my ($name,$what) = @_;
                   7615: 	return if ( !exists($domain{$name}) );
                   7616: 
                   7617: 	if (!$what) {
                   7618: 	    return $domain{$name}{'description'};
                   7619: 	}
                   7620: 	return $domain{$name}{$what};
                   7621:     }
1.327     albertel 7622: }
                   7623: 
                   7624: 
1.1       albertel 7625: # ------------------------------------------------------------- Read hosts file
                   7626: {
1.838     albertel 7627:     my %hostname;
1.844     albertel 7628:     my %hostdom;
1.845     albertel 7629:     my %libserv;
1.448     albertel 7630:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7631: 
                   7632:     while (my $configline=<$config>) {
1.303     matthew  7633:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7634:        chomp($configline);
1.595     albertel 7635:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7636:        $name=~s/\s//g;
1.595     albertel 7637:        if ($id && $domain && $role && $name) {
1.252     albertel 7638: 	 $hostname{$id}=$name;
                   7639: 	 $hostdom{$id}=$domain;
                   7640: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7641:        }
1.1       albertel 7642:     }
1.448     albertel 7643:     close($config);
1.619     albertel 7644:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7645:     #&get_iphost();
1.838     albertel 7646: 
                   7647:     sub hostname {
                   7648: 	my ($lonid) = @_;
                   7649: 	return $hostname{$lonid};
                   7650:     }
1.845     albertel 7651: 
1.838     albertel 7652:     sub all_hostnames {
                   7653: 	return %hostname;
                   7654:     }
1.845     albertel 7655: 
                   7656:     sub is_library {
                   7657: 	return exists($libserv{$_[0]});
                   7658:     }
                   7659: 
                   7660:     sub all_library {
                   7661: 	return %libserv;
                   7662:     }
                   7663: 
1.841     albertel 7664:     sub get_servers {
                   7665: 	my ($domain,$type) = @_;
                   7666: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7667: 	                                          : %hostname;
                   7668: 	my %result;
1.842     albertel 7669: 	if (ref($domain) eq 'ARRAY') {
                   7670: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7671: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7672: 		    $result{$host} = $hostname;
                   7673: 		}
                   7674: 	    }
                   7675: 	} else {
                   7676: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7677: 		if ($hostdom{$host} eq $domain) {
                   7678: 		    $result{$host} = $hostname;
                   7679: 		}
1.841     albertel 7680: 	    }
                   7681: 	}
                   7682: 	return %result;
                   7683:     }
1.845     albertel 7684: 
1.844     albertel 7685:     sub host_domain {
                   7686: 	my ($lonid) = @_;
                   7687: 	return $hostdom{$lonid};
                   7688:     }
                   7689: 
1.841     albertel 7690:     sub all_domains {
                   7691: 	my %seen;
                   7692: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7693: 	return @uniq;
                   7694:     }
1.1       albertel 7695: }
                   7696: 
1.847     albertel 7697: { 
                   7698:     my %iphost;
                   7699:     sub get_hosts_from_ip {
                   7700: 	my ($ip) = @_;
                   7701: 	my %iphosts = &get_iphost();
                   7702: 	if (ref($iphosts{$ip})) {
                   7703: 	    return @{$iphosts{$ip}};
                   7704: 	}
                   7705: 	return;
1.839     albertel 7706:     }
1.847     albertel 7707:     
                   7708:     sub get_iphost {
                   7709: 	if (%iphost) { return %iphost; }
                   7710: 	my %name_to_ip;
                   7711: 	my %hostname = &all_hostnames();
                   7712: 	foreach my $id (keys(%hostname)) {
                   7713: 	    my $name=$hostname{$id};
                   7714: 	    my $ip;
                   7715: 	    if (!exists($name_to_ip{$name})) {
                   7716: 		$ip = gethostbyname($name);
                   7717: 		if (!$ip || length($ip) ne 4) {
                   7718: 		    &logthis("Skipping host $id name $name no IP found");
                   7719: 		    next;
                   7720: 		}
                   7721: 		$ip=inet_ntoa($ip);
                   7722: 		$name_to_ip{$name} = $ip;
                   7723: 	    } else {
                   7724: 		$ip = $name_to_ip{$name};
1.653     albertel 7725: 	    }
1.847     albertel 7726: 	    push(@{$iphost{$ip}},$id);
1.598     albertel 7727: 	}
1.847     albertel 7728: 	return %iphost;
1.598     albertel 7729:     }
                   7730: }
                   7731: 
1.1       albertel 7732: # ------------------------------------------------------ Read spare server file
                   7733: {
1.448     albertel 7734:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7735: 
                   7736:     while (my $configline=<$config>) {
                   7737:        chomp($configline);
1.284     matthew  7738:        if ($configline) {
1.784     albertel 7739: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7740: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7741: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7742:        }
                   7743:     }
1.448     albertel 7744:     close($config);
1.1       albertel 7745: }
1.11      www      7746: # ------------------------------------------------------------ Read permissions
                   7747: {
1.448     albertel 7748:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7749: 
                   7750:     while (my $configline=<$config>) {
1.448     albertel 7751: 	chomp($configline);
                   7752: 	if ($configline) {
                   7753: 	    my ($role,$perm)=split(/ /,$configline);
                   7754: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7755: 	}
1.11      www      7756:     }
1.448     albertel 7757:     close($config);
1.11      www      7758: }
                   7759: 
                   7760: # -------------------------------------------- Read plain texts for permissions
                   7761: {
1.448     albertel 7762:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7763: 
                   7764:     while (my $configline=<$config>) {
1.448     albertel 7765: 	chomp($configline);
                   7766: 	if ($configline) {
1.742     raeburn  7767: 	    my ($short,@plain)=split(/:/,$configline);
                   7768:             %{$prp{$short}} = ();
                   7769: 	    if (@plain > 0) {
                   7770:                 $prp{$short}{'std'} = $plain[0];
                   7771:                 for (my $i=1; $i<@plain; $i++) {
                   7772:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7773:                 }
                   7774:             }
1.448     albertel 7775: 	}
1.135     www      7776:     }
1.448     albertel 7777:     close($config);
1.135     www      7778: }
                   7779: 
                   7780: # ---------------------------------------------------------- Read package table
                   7781: {
1.448     albertel 7782:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7783: 
                   7784:     while (my $configline=<$config>) {
1.483     albertel 7785: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7786: 	chomp($configline);
                   7787: 	my ($short,$plain)=split(/:/,$configline);
                   7788: 	my ($pack,$name)=split(/\&/,$short);
                   7789: 	if ($plain ne '') {
                   7790: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7791: 	    $packagetab{$short}=$plain; 
                   7792: 	}
1.11      www      7793:     }
1.448     albertel 7794:     close($config);
1.329     matthew  7795: }
                   7796: 
                   7797: # ------------- set up temporary directory
                   7798: {
                   7799:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7800: 
1.11      www      7801: }
                   7802: 
1.794     albertel 7803: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7804: 				'compress_threshold'=> 20_000,
                   7805:  			        });
1.185     www      7806: 
1.281     www      7807: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7808: $dumpcount=0;
1.22      www      7809: 
1.163     harris41 7810: &logtouch();
1.672     albertel 7811: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7812: $readit=1;
1.564     albertel 7813:     {
                   7814: 	use integer;
                   7815: 	my $test=(2**32)+1;
1.568     albertel 7816: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7817: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7818:     }
1.195     www      7819: }
1.1       albertel 7820: }
1.179     www      7821: 
1.1       albertel 7822: 1;
1.191     harris41 7823: __END__
                   7824: 
1.243     albertel 7825: =pod
                   7826: 
1.191     harris41 7827: =head1 NAME
                   7828: 
1.243     albertel 7829: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7830: 
                   7831: =head1 SYNOPSIS
                   7832: 
1.243     albertel 7833: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7834: 
                   7835:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7836: 
1.243     albertel 7837: Common parameters:
                   7838: 
                   7839: =over 4
                   7840: 
                   7841: =item *
                   7842: 
                   7843: $uname : an internal username (if $cname expecting a course Id specifically)
                   7844: 
                   7845: =item *
                   7846: 
                   7847: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7848: 
                   7849: =item *
                   7850: 
                   7851: $symb : a resource instance identifier
                   7852: 
                   7853: =item *
                   7854: 
                   7855: $namespace : the name of a .db file that contains the data needed or
                   7856: being set.
                   7857: 
                   7858: =back
                   7859: 
1.394     bowersj2 7860: =head1 OVERVIEW
1.191     harris41 7861: 
1.394     bowersj2 7862: lonnet provides subroutines which interact with the
                   7863: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7864: about classes, users, and resources.
1.243     albertel 7865: 
                   7866: For many of these objects you can also use this to store data about
                   7867: them or modify them in various ways.
1.191     harris41 7868: 
1.394     bowersj2 7869: =head2 Symbs
1.191     harris41 7870: 
1.394     bowersj2 7871: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7872: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7873: map, the resource number of the resource in the map, and the URL of
                   7874: the resource itself. The latter is somewhat redundant, but might help
                   7875: if maps change.
                   7876: 
                   7877: An example is
                   7878: 
                   7879:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7880: 
                   7881: The respective map entry is
                   7882: 
                   7883:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7884:   title="Problem 2">
                   7885:  </resource>
                   7886: 
                   7887: Symbs are used by the random number generator, as well as to store and
                   7888: restore data specific to a certain instance of for example a problem.
                   7889: 
                   7890: =head2 Storing And Retrieving Data
                   7891: 
                   7892: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7893: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7894: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7895: is is the non-critical message twin of cstore. These functions are for
                   7896: handlers to store a perl hash to a user's permanent data space in an
                   7897: easy manner, and to retrieve it again on another call. It is expected
                   7898: that a handler would use this once at the beginning to retrieve data,
                   7899: and then again once at the end to send only the new data back.
                   7900: 
                   7901: The data is stored in the user's data directory on the user's
                   7902: homeserver under the ID of the course.
                   7903: 
                   7904: The hash that is returned by restore will have all of the previous
                   7905: value for all of the elements of the hash.
                   7906: 
                   7907: Example:
                   7908: 
                   7909:  #creating a hash
                   7910:  my %hash;
                   7911:  $hash{'foo'}='bar';
                   7912: 
                   7913:  #storing it
                   7914:  &Apache::lonnet::cstore(\%hash);
                   7915: 
                   7916:  #changing a value
                   7917:  $hash{'foo'}='notbar';
                   7918: 
                   7919:  #adding a new value
                   7920:  $hash{'bar'}='foo';
                   7921:  &Apache::lonnet::cstore(\%hash);
                   7922: 
                   7923:  #retrieving the hash
                   7924:  my %history=&Apache::lonnet::restore();
                   7925: 
                   7926:  #print the hash
                   7927:  foreach my $key (sort(keys(%history))) {
                   7928:    print("\%history{$key} = $history{$key}");
                   7929:  }
                   7930: 
                   7931: Will print out:
1.191     harris41 7932: 
1.394     bowersj2 7933:  %history{1:foo} = bar
                   7934:  %history{1:keys} = foo:timestamp
                   7935:  %history{1:timestamp} = 990455579
                   7936:  %history{2:bar} = foo
                   7937:  %history{2:foo} = notbar
                   7938:  %history{2:keys} = foo:bar:timestamp
                   7939:  %history{2:timestamp} = 990455580
                   7940:  %history{bar} = foo
                   7941:  %history{foo} = notbar
                   7942:  %history{timestamp} = 990455580
                   7943:  %history{version} = 2
                   7944: 
                   7945: Note that the special hash entries C<keys>, C<version> and
                   7946: C<timestamp> were added to the hash. C<version> will be equal to the
                   7947: total number of versions of the data that have been stored. The
                   7948: C<timestamp> attribute will be the UNIX time the hash was
                   7949: stored. C<keys> is available in every historical section to list which
                   7950: keys were added or changed at a specific historical revision of a
                   7951: hash.
                   7952: 
                   7953: B<Warning>: do not store the hash that restore returns directly. This
                   7954: will cause a mess since it will restore the historical keys as if the
                   7955: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7956: 
1.394     bowersj2 7957: Calling convention:
1.191     harris41 7958: 
1.394     bowersj2 7959:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7960:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7961: 
1.394     bowersj2 7962: For more detailed information, see lonnet specific documentation.
1.191     harris41 7963: 
1.394     bowersj2 7964: =head1 RETURN MESSAGES
1.191     harris41 7965: 
1.394     bowersj2 7966: =over 4
1.191     harris41 7967: 
1.394     bowersj2 7968: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7969: 
1.394     bowersj2 7970: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7971: when the connection is brought back up
1.191     harris41 7972: 
1.394     bowersj2 7973: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7974: for later delivery
1.191     harris41 7975: 
1.394     bowersj2 7976: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7977: 
1.394     bowersj2 7978: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7979: that was requested
1.191     harris41 7980: 
1.243     albertel 7981: =back
1.191     harris41 7982: 
1.243     albertel 7983: =head1 PUBLIC SUBROUTINES
1.191     harris41 7984: 
1.243     albertel 7985: =head2 Session Environment Functions
1.191     harris41 7986: 
1.243     albertel 7987: =over 4
1.191     harris41 7988: 
1.394     bowersj2 7989: =item * 
                   7990: X<appenv()>
                   7991: B<appenv(%hash)>: the value of %hash is written to
                   7992: the user envirnoment file, and will be restored for each access this
1.620     albertel 7993: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7994: process
1.191     harris41 7995: 
                   7996: =item *
1.394     bowersj2 7997: X<delenv()>
                   7998: B<delenv($regexp)>: removes all items from the session
                   7999: environment file that matches the regular expression in $regexp. The
1.620     albertel 8000: values are also delted from the current processes %env.
1.191     harris41 8001: 
1.795     albertel 8002: =item * get_env_multiple($name) 
                   8003: 
                   8004: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8005: values may be defined and end up as an array ref.
                   8006: 
                   8007: returns an array of values
                   8008: 
1.243     albertel 8009: =back
                   8010: 
                   8011: =head2 User Information
1.191     harris41 8012: 
1.243     albertel 8013: =over 4
1.191     harris41 8014: 
                   8015: =item *
1.394     bowersj2 8016: X<queryauthenticate()>
                   8017: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8018: authentication scheme
                   8019: 
                   8020: =item *
1.394     bowersj2 8021: X<authenticate()>
                   8022: B<authenticate($uname,$upass,$udom)>: try to
                   8023: authenticate user from domain's lib servers (first use the current
                   8024: one). C<$upass> should be the users password.
1.191     harris41 8025: 
                   8026: =item *
1.394     bowersj2 8027: X<homeserver()>
                   8028: B<homeserver($uname,$udom)>: find the server which has
                   8029: the user's directory and files (there must be only one), this caches
                   8030: the answer, and also caches if there is a borken connection.
1.191     harris41 8031: 
                   8032: =item *
1.394     bowersj2 8033: X<idget()>
                   8034: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8035: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8036: username, and only 1 username per ID in a specific domain) (returns
                   8037: hash: id=>name,id=>name)
1.191     harris41 8038: 
                   8039: =item *
1.394     bowersj2 8040: X<idrget()>
                   8041: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8042: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8043: 
                   8044: =item *
1.394     bowersj2 8045: X<idput()>
                   8046: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8047: 
                   8048: =item *
1.394     bowersj2 8049: X<rolesinit()>
                   8050: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8051: 
                   8052: =item *
1.551     albertel 8053: X<getsection()>
                   8054: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8055: course $cname, return section name/number or '' for "not in course"
                   8056: and '-1' for "no section"
                   8057: 
                   8058: =item *
1.394     bowersj2 8059: X<userenvironment()>
                   8060: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8061: passed in @what from the requested user's environment, returns a hash
                   8062: 
                   8063: =back
                   8064: 
                   8065: =head2 User Roles
                   8066: 
                   8067: =over 4
                   8068: 
                   8069: =item *
                   8070: 
1.810     raeburn  8071: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8072:  F: full access
                   8073:  U,I,K: authentication modes (cxx only)
                   8074:  '': forbidden
                   8075:  1: user needs to choose course
                   8076:  2: browse allowed
1.766     albertel 8077:  A: passphrase authentication needed
1.243     albertel 8078: 
                   8079: =item *
                   8080: 
                   8081: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8082: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8083: and course level
                   8084: 
                   8085: =item *
                   8086: 
                   8087: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8088: explanation of a user role term
                   8089: 
1.832     raeburn  8090: =item *
                   8091: 
1.834     albertel 8092: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
                   8093: optional.  Returns a hash of a user's roles, with keys set to
                   8094: colon-sparated $uname,$udom,and $role, and value set to
                   8095: colon-separated start and end times for the role. If no username and
                   8096: domain are specified, will default to current user/domain. Types,
                   8097: roles, and roledoms are references to arrays, of role statuses
                   8098: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
                   8099: of the roles which can be used to restrict the list if roles
                   8100: reported. If no array ref is provided for types, will default to
                   8101: return only active roles.
                   8102: 
1.243     albertel 8103: =back
                   8104: 
                   8105: =head2 User Modification
                   8106: 
                   8107: =over 4
                   8108: 
                   8109: =item *
                   8110: 
                   8111: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8112: user for the level given by URL.  Optional start and end dates (leave empty
                   8113: string or zero for "no date")
1.191     harris41 8114: 
                   8115: =item *
                   8116: 
1.243     albertel 8117: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8118: change a users, password, possible return values are: ok,
                   8119: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8120: refused
1.191     harris41 8121: 
                   8122: =item *
                   8123: 
1.243     albertel 8124: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8125: 
                   8126: =item *
                   8127: 
1.243     albertel 8128: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8129: modify user
1.191     harris41 8130: 
                   8131: =item *
                   8132: 
1.286     matthew  8133: modifystudent
                   8134: 
                   8135: modify a students enrollment and identification information.
                   8136: The course id is resolved based on the current users environment.  
                   8137: This means the envoking user must be a course coordinator or otherwise
                   8138: associated with a course.
                   8139: 
1.297     matthew  8140: This call is essentially a wrapper for lonnet::modifyuser and
                   8141: lonnet::modify_student_enrollment
1.286     matthew  8142: 
                   8143: Inputs: 
                   8144: 
                   8145: =over 4
                   8146: 
                   8147: =item B<$udom> Students loncapa domain
                   8148: 
                   8149: =item B<$uname> Students loncapa login name
                   8150: 
                   8151: =item B<$uid> Students id/student number
                   8152: 
                   8153: =item B<$umode> Students authentication mode
                   8154: 
                   8155: =item B<$upass> Students password
                   8156: 
                   8157: =item B<$first> Students first name
                   8158: 
                   8159: =item B<$middle> Students middle name
                   8160: 
                   8161: =item B<$last> Students last name
                   8162: 
                   8163: =item B<$gene> Students generation
                   8164: 
                   8165: =item B<$usec> Students section in course
                   8166: 
                   8167: =item B<$end> Unix time of the roles expiration
                   8168: 
                   8169: =item B<$start> Unix time of the roles start date
                   8170: 
                   8171: =item B<$forceid> If defined, allow $uid to be changed
                   8172: 
                   8173: =item B<$desiredhome> server to use as home server for student
                   8174: 
                   8175: =back
1.297     matthew  8176: 
                   8177: =item *
                   8178: 
                   8179: modify_student_enrollment
                   8180: 
                   8181: Change a students enrollment status in a class.  The environment variable
                   8182: 'role.request.course' must be defined for this function to proceed.
                   8183: 
                   8184: Inputs:
                   8185: 
                   8186: =over 4
                   8187: 
                   8188: =item $udom, students domain
                   8189: 
                   8190: =item $uname, students name
                   8191: 
                   8192: =item $uid, students user id
                   8193: 
                   8194: =item $first, students first name
                   8195: 
                   8196: =item $middle
                   8197: 
                   8198: =item $last
                   8199: 
                   8200: =item $gene
                   8201: 
                   8202: =item $usec
                   8203: 
                   8204: =item $end
                   8205: 
                   8206: =item $start
                   8207: 
                   8208: =back
                   8209: 
1.191     harris41 8210: 
                   8211: =item *
                   8212: 
1.243     albertel 8213: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8214: custom role; give a custom role to a user for the level given by URL.  Specify
                   8215: name and domain of role author, and role name
1.191     harris41 8216: 
                   8217: =item *
                   8218: 
1.243     albertel 8219: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8220: 
                   8221: =item *
                   8222: 
1.243     albertel 8223: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8224: 
                   8225: =back
                   8226: 
                   8227: =head2 Course Infomation
                   8228: 
                   8229: =over 4
1.191     harris41 8230: 
                   8231: =item *
                   8232: 
1.631     albertel 8233: coursedescription($courseid) : returns a hash of information about the
                   8234: specified course id, including all environment settings for the
                   8235: course, the description of the course will be in the hash under the
                   8236: key 'description'
1.191     harris41 8237: 
                   8238: =item *
                   8239: 
1.624     albertel 8240: resdata($name,$domain,$type,@which) : request for current parameter
                   8241: setting for a specific $type, where $type is either 'course' or 'user',
                   8242: @what should be a list of parameters to ask about. This routine caches
                   8243: answers for 5 minutes.
1.243     albertel 8244: 
                   8245: =back
                   8246: 
                   8247: =head2 Course Modification
                   8248: 
                   8249: =over 4
1.191     harris41 8250: 
                   8251: =item *
                   8252: 
1.243     albertel 8253: writecoursepref($courseid,%prefs) : write preferences (environment
                   8254: database) for a course
1.191     harris41 8255: 
                   8256: =item *
                   8257: 
1.243     albertel 8258: createcourse($udom,$description,$url) : make/modify course
                   8259: 
                   8260: =back
                   8261: 
                   8262: =head2 Resource Subroutines
                   8263: 
                   8264: =over 4
1.191     harris41 8265: 
                   8266: =item *
                   8267: 
1.243     albertel 8268: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8269: 
                   8270: =item *
                   8271: 
1.243     albertel 8272: repcopy($filename) : subscribes to the requested file, and attempts to
                   8273: replicate from the owning library server, Might return
1.607     raeburn  8274: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8275: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8276: resource. Expects the local filesystem pathname
                   8277: (/home/httpd/html/res/....)
                   8278: 
                   8279: =back
                   8280: 
                   8281: =head2 Resource Information
                   8282: 
                   8283: =over 4
1.191     harris41 8284: 
                   8285: =item *
                   8286: 
1.243     albertel 8287: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8288: a vairety of different possible values, $varname should be a request
                   8289: string, and the other parameters can be used to specify who and what
                   8290: one is asking about.
                   8291: 
                   8292: Possible values for $varname are environment.lastname (or other item
                   8293: from the envirnment hash), user.name (or someother aspect about the
                   8294: user), resource.0.maxtries (or some other part and parameter of a
                   8295: resource)
1.204     albertel 8296: 
                   8297: =item *
                   8298: 
1.243     albertel 8299: directcondval($number) : get current value of a condition; reads from a state
                   8300: string
1.204     albertel 8301: 
                   8302: =item *
                   8303: 
1.243     albertel 8304: condval($condidx) : value of condition index based on state
1.204     albertel 8305: 
                   8306: =item *
                   8307: 
1.243     albertel 8308: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8309: resource's metadata, $what should be either a specific key, or either
                   8310: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8311: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8312: 
                   8313: this function automatically caches all requests
1.191     harris41 8314: 
                   8315: =item *
                   8316: 
1.243     albertel 8317: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8318: network of library servers; returns file handle of where SQL and regex results
                   8319: will be stored for query
1.191     harris41 8320: 
                   8321: =item *
                   8322: 
1.243     albertel 8323: symbread($filename) : return symbolic list entry (filename argument optional);
                   8324: returns the data handle
1.191     harris41 8325: 
                   8326: =item *
                   8327: 
1.243     albertel 8328: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8329: a possible symb for the URL in $thisfn, and if is an encryypted
                   8330: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8331: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8332: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8333: 
1.191     harris41 8334: 
                   8335: =item *
                   8336: 
1.243     albertel 8337: symbclean($symb) : removes versions numbers from a symb, returns the
                   8338: cleaned symb
1.191     harris41 8339: 
                   8340: =item *
                   8341: 
1.243     albertel 8342: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8343: course map, user must be in a course for it to work.
1.191     harris41 8344: 
                   8345: =item *
                   8346: 
1.243     albertel 8347: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8348: 
                   8349: =item *
                   8350: 
1.243     albertel 8351: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8352: a random seed, all arguments are optional, if they aren't sent it uses the
                   8353: environment to derive them. Note: if symb isn't sent and it can't get one
                   8354: from &symbread it will use the current time as its return value
1.191     harris41 8355: 
                   8356: =item *
                   8357: 
1.243     albertel 8358: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8359: unfakeable, receipt
1.191     harris41 8360: 
                   8361: =item *
                   8362: 
1.620     albertel 8363: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8364: 
                   8365: =item *
                   8366: 
1.243     albertel 8367: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8368: 
                   8369: =item *
                   8370: 
1.243     albertel 8371: 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 8372: 
                   8373: =item *
                   8374: 
1.243     albertel 8375: 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 8376: 
                   8377: =item *
                   8378: 
1.243     albertel 8379: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8380: 
                   8381: =item *
                   8382: 
1.243     albertel 8383: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8384: forcing spreadsheet to reevaluate the resource scores next time.
                   8385: 
                   8386: =back
                   8387: 
                   8388: =head2 Storing/Retreiving Data
                   8389: 
                   8390: =over 4
1.191     harris41 8391: 
                   8392: =item *
                   8393: 
1.243     albertel 8394: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8395: for this url; hashref needs to be given and should be a \%hashname; the
                   8396: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8397: be derived from the env
1.191     harris41 8398: 
                   8399: =item *
                   8400: 
1.243     albertel 8401: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8402: uses critical subroutine
1.191     harris41 8403: 
                   8404: =item *
                   8405: 
1.243     albertel 8406: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8407: all args are optional
1.191     harris41 8408: 
                   8409: =item *
                   8410: 
1.717     albertel 8411: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8412: dumps the complete (or key matching regexp) namespace into a hash
                   8413: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8414: normally &store()ed into
                   8415: 
                   8416: $range should be either an integer '100' (give me the first 100
                   8417:                                            matching records)
                   8418:               or be  two integers sperated by a - with no spaces
                   8419:                  '30-50' (give me the 30th through the 50th matching
                   8420:                           records)
                   8421: 
                   8422: 
                   8423: =item *
                   8424: 
                   8425: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8426: replaces a &store() version of data with a replacement set of data
                   8427: for a particular resource in a namespace passed in the $storehash hash 
                   8428: reference
                   8429: 
                   8430: =item *
                   8431: 
1.243     albertel 8432: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8433: works very similar to store/cstore, but all data is stored in a
                   8434: temporary location and can be reset using tmpreset, $storehash should
                   8435: be a hash reference, returns nothing on success
1.191     harris41 8436: 
                   8437: =item *
                   8438: 
1.243     albertel 8439: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8440: similar to restore, but all data is stored in a temporary location and
                   8441: can be reset using tmpreset. Returns a hash of values on success,
                   8442: error string otherwise.
1.191     harris41 8443: 
                   8444: =item *
                   8445: 
1.243     albertel 8446: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8447: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8448: 
                   8449: =item *
                   8450: 
1.243     albertel 8451: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8452: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8453: 
                   8454: =item *
                   8455: 
1.243     albertel 8456: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8457: namesp ($udom and $uname are optional)
1.191     harris41 8458: 
                   8459: =item *
                   8460: 
1.702     albertel 8461: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8462: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8463: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8464: 
1.702     albertel 8465: $range should be either an integer '100' (give me the first 100
                   8466:                                            matching records)
                   8467:               or be  two integers sperated by a - with no spaces
                   8468:                  '30-50' (give me the 30th through the 50th matching
                   8469:                           records)
1.449     matthew  8470: =item *
                   8471: 
                   8472: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8473: $store can be a scalar, an array reference, or if the amount to be 
                   8474: incremented is > 1, a hash reference.
                   8475: 
                   8476: ($udom and $uname are optional)
1.191     harris41 8477: 
                   8478: =item *
                   8479: 
1.243     albertel 8480: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8481: ($udom and $uname are optional)
1.191     harris41 8482: 
                   8483: =item *
                   8484: 
1.243     albertel 8485: cput($namespace,$storehash,$udom,$uname) : critical put
                   8486: ($udom and $uname are optional)
1.191     harris41 8487: 
                   8488: =item *
                   8489: 
1.748     albertel 8490: newput($namespace,$storehash,$udom,$uname) :
                   8491: 
                   8492: Attempts to store the items in the $storehash, but only if they don't
                   8493: currently exist, if this succeeds you can be certain that you have 
                   8494: successfully created a new key value pair in the $namespace db.
                   8495: 
                   8496: 
                   8497: Args:
                   8498:  $namespace: name of database to store values to
                   8499:  $storehash: hashref to store to the db
                   8500:  $udom: (optional) domain of user containing the db
                   8501:  $uname: (optional) name of user caontaining the db
                   8502: 
                   8503: Returns:
                   8504:  'ok' -> succeeded in storing all keys of $storehash
                   8505:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8506:                         least <key> already existed in the db (other
                   8507:                         requested keys may also already exist)
                   8508:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8509:  'con_lost' -> unable to contact request server
                   8510:  'refused' -> action was not allowed by remote machine
                   8511: 
                   8512: 
                   8513: =item *
                   8514: 
1.243     albertel 8515: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8516: reference filled in from namesp (encrypts the return communication)
                   8517: ($udom and $uname are optional)
1.191     harris41 8518: 
                   8519: =item *
                   8520: 
1.243     albertel 8521: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8522: critical subroutine
                   8523: 
1.806     raeburn  8524: =item *
                   8525: 
                   8526: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8527: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8528: 
                   8529: =item *
                   8530: 
                   8531: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8532: 
1.243     albertel 8533: =back
                   8534: 
                   8535: =head2 Network Status Functions
                   8536: 
                   8537: =over 4
1.191     harris41 8538: 
                   8539: =item *
                   8540: 
                   8541: dirlist($uri) : return directory list based on URI
                   8542: 
                   8543: =item *
                   8544: 
1.243     albertel 8545: spareserver() : find server with least workload from spare.tab
                   8546: 
                   8547: =back
                   8548: 
                   8549: =head2 Apache Request
                   8550: 
                   8551: =over 4
1.191     harris41 8552: 
                   8553: =item *
                   8554: 
1.243     albertel 8555: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8556: localhost, posts hash
                   8557: 
                   8558: =back
                   8559: 
                   8560: =head2 Data to String to Data
                   8561: 
                   8562: =over 4
1.191     harris41 8563: 
                   8564: =item *
                   8565: 
1.243     albertel 8566: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8567: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8568: 
                   8569: =item *
                   8570: 
1.243     albertel 8571: hashref2str($hashref) : convert a hashref into a string complete with
                   8572: escaping and '=' and '&' separators, supports elements that are
                   8573: arrayrefs and hashrefs
1.191     harris41 8574: 
                   8575: =item *
                   8576: 
1.243     albertel 8577: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8578: with escaping and '&' separators, supports elements that are arrayrefs
                   8579: and hashrefs
1.191     harris41 8580: 
                   8581: =item *
                   8582: 
1.243     albertel 8583: str2hash($string) : convert string to hash using unescaping and
                   8584: splitting on '=' and '&', supports elements that are arrayrefs and
                   8585: hashrefs
1.191     harris41 8586: 
                   8587: =item *
                   8588: 
1.243     albertel 8589: str2array($string) : convert string to hash using unescaping and
                   8590: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8591: 
                   8592: =back
                   8593: 
                   8594: =head2 Logging Routines
                   8595: 
                   8596: =over 4
                   8597: 
                   8598: These routines allow one to make log messages in the lonnet.log and
                   8599: lonnet.perm logfiles.
1.191     harris41 8600: 
                   8601: =item *
                   8602: 
1.243     albertel 8603: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8604: 
                   8605: =item *
                   8606: 
1.243     albertel 8607: logthis() : append message to the normal lonnet.log file, it gets
                   8608: preiodically rolled over and deleted.
1.191     harris41 8609: 
                   8610: =item *
                   8611: 
1.243     albertel 8612: logperm() : append a permanent message to lonnet.perm.log, this log
                   8613: file never gets deleted by any automated portion of the system, only
                   8614: messages of critical importance should go in here.
                   8615: 
                   8616: =back
                   8617: 
                   8618: =head2 General File Helper Routines
                   8619: 
                   8620: =over 4
1.191     harris41 8621: 
                   8622: =item *
                   8623: 
1.481     raeburn  8624: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8625: (a) files in /uploaded
                   8626:   (i) If a local copy of the file exists - 
                   8627:       compares modification date of local copy with last-modified date for 
                   8628:       definitive version stored on home server for course. If local copy is 
                   8629:       stale, requests a new version from the home server and stores it. 
                   8630:       If the original has been removed from the home server, then local copy 
                   8631:       is unlinked.
                   8632:   (ii) If local copy does not exist -
                   8633:       requests the file from the home server and stores it. 
                   8634:   
                   8635:   If $caller is 'uploadrep':  
                   8636:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8637:     for request for files originally uploaded via DOCS. 
                   8638:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8639:   
                   8640:   Otherwise:
                   8641:      This indicates a call from the content generation phase of the request.
                   8642:      -  returns the entire contents of the file or -1.
                   8643:      
                   8644: (b) files in /res
                   8645:    - returns the entire contents of a file or -1; 
                   8646:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8647: 
1.712     albertel 8648: 
                   8649: =item *
                   8650: 
                   8651: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8652:                   reference
                   8653: 
                   8654: returns either a stat() list of data about the file or an empty list
                   8655: if the file doesn't exist or couldn't find out about it (connection
                   8656: problems or user unknown)
                   8657: 
1.191     harris41 8658: =item *
                   8659: 
1.243     albertel 8660: filelocation($dir,$file) : returns file system location of a file
                   8661: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8662: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8663: and a file of ../bob will become /a/bob)
1.191     harris41 8664: 
                   8665: =item *
                   8666: 
                   8667: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8668: filelocation except for hrefs
                   8669: 
                   8670: =item *
                   8671: 
                   8672: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8673: 
1.243     albertel 8674: =back
                   8675: 
1.608     albertel 8676: =head2 Usererfile file routines (/uploaded*)
                   8677: 
                   8678: =over 4
                   8679: 
                   8680: =item *
                   8681: 
                   8682: userfileupload(): main rotine for putting a file in a user or course's
                   8683:                   filespace, arguments are,
                   8684: 
1.620     albertel 8685:  formname - required - this is the name of the element in $env where the
1.608     albertel 8686:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8687:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8688:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8689:  coursedoc - if true, store the file in the course of the active role
                   8690:              of the current user
                   8691:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8692:          if undefined, it will be placed in "unknown"
                   8693: 
                   8694:  (This routine calls clean_filename() to remove any dangerous
                   8695:  characters from the filename, and then calls finuserfileupload() to
                   8696:  complete the transaction)
                   8697: 
                   8698:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8699:  and /adm/notfound.html if unsuccessful
                   8700: 
                   8701: =item *
                   8702: 
                   8703: clean_filename(): routine for cleaing a filename up for storage in
                   8704:                  userfile space, argument is:
                   8705: 
                   8706:  filename - proposed filename
                   8707: 
                   8708: returns: the new clean filename
                   8709: 
                   8710: =item *
                   8711: 
                   8712: finishuserfileupload(): routine that creaes and sends the file to
                   8713: userspace, probably shouldn't be called directly
                   8714: 
                   8715:   docuname: username or courseid of destination for the file
                   8716:   docudom: domain of user/course of destination for the file
                   8717:   formname: same as for userfileupload()
                   8718:   fname: filename (inculding subdirectories) for the file
                   8719: 
                   8720:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8721:  and /adm/notfound.html if unsuccessful
                   8722: 
                   8723: =item *
                   8724: 
                   8725: renameuserfile(): renames an existing userfile to a new name
                   8726: 
                   8727:   Args:
                   8728:    docuname: username or courseid of destination for the file
                   8729:    docudom: domain of user/course of destination for the file
                   8730:    old: current file name (including any subdirs under userfiles)
                   8731:    new: desired file name (including any subdirs under userfiles)
                   8732: 
                   8733: =item *
                   8734: 
                   8735: mkdiruserfile(): creates a directory is a userfiles dir
                   8736: 
                   8737:   Args:
                   8738:    docuname: username or courseid of destination for the file
                   8739:    docudom: domain of user/course of destination for the file
                   8740:    dir: dir to create (including any subdirs under userfiles)
                   8741: 
                   8742: =item *
                   8743: 
                   8744: removeuserfile(): removes a file that exists in userfiles
                   8745: 
                   8746:   Args:
                   8747:    docuname: username or courseid of destination for the file
                   8748:    docudom: domain of user/course of destination for the file
                   8749:    fname: filname to delete (including any subdirs under userfiles)
                   8750: 
                   8751: =item *
                   8752: 
                   8753: removeuploadedurl(): convience function for removeuserfile()
                   8754: 
                   8755:   Args:
                   8756:    url:  a full /uploaded/... url to delete
                   8757: 
1.747     albertel 8758: =item * 
                   8759: 
                   8760: get_portfile_permissions():
                   8761:   Args:
                   8762:     domain: domain of user or course contain the portfolio files
                   8763:     user: name of user or num of course contain the portfolio files
                   8764:   Returns:
                   8765:     hashref of a dump of the proper file_permissions.db
                   8766:    
                   8767: 
                   8768: =item * 
                   8769: 
                   8770: get_access_controls():
                   8771: 
                   8772: Args:
                   8773:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8774:   group: (optional) the group you want the files associated with
                   8775:   file: (optional) the file you want access info on
                   8776: 
                   8777: Returns:
1.749     raeburn  8778:     a hash (keys are file names) of hashes containing
                   8779:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8780:         values are XML containing access control settings (see below) 
1.747     albertel 8781: 
                   8782: Internal notes:
                   8783: 
1.749     raeburn  8784:  access controls are stored in file_permissions.db as key=value pairs.
                   8785:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8786:         where scope -> public,guest,course,group,domains or users.
                   8787:               end -> UNIX time for end of access (0 -> no end date)
                   8788:               start -> UNIX time for start of access
                   8789: 
                   8790:     value -> XML description of access control
                   8791:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8792:             <start></start>
                   8793:             <end></end>
                   8794: 
                   8795:             <password></password>  for scope type = guest
                   8796: 
                   8797:             <domain></domain>     for scope type = course or group
                   8798:             <number></number>
                   8799:             <roles id="">
                   8800:              <role></role>
                   8801:              <access></access>
                   8802:              <section></section>
                   8803:              <group></group>
                   8804:             </roles>
                   8805: 
                   8806:             <dom></dom>         for scope type = domains
                   8807: 
                   8808:             <users>             for scope type = users
                   8809:              <user>
                   8810:               <uname></uname>
                   8811:               <udom></udom>
                   8812:              </user>
                   8813:             </users>
                   8814:            </scope> 
                   8815:               
                   8816:  Access data is also aggregated for each file in an additional key=value pair:
                   8817:  key -> path to file/file_name\0accesscontrol 
                   8818:  value -> reference to hash
                   8819:           hash contains key = value pairs
                   8820:           where key = uniqueID:scope_end_start
                   8821:                 value = UNIX time record was last updated
                   8822: 
                   8823:           Used to improve speed of look-ups of access controls for each file.  
                   8824:  
                   8825:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8826: 
                   8827: modify_access_controls():
                   8828: 
                   8829: Modifies access controls for a portfolio file
                   8830: Args
                   8831: 1. file name
                   8832: 2. reference to hash of required changes,
                   8833: 3. domain
                   8834: 4. username
                   8835:   where domain,username are the domain of the portfolio owner 
                   8836:   (either a user or a course) 
                   8837: 
                   8838: Returns:
                   8839: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8840: 2. result of deletions ('ok' or 'error', with error message).
                   8841: 3. reference to hash of any new or updated access controls.
                   8842: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8843:    key = integer (inbound ID)
                   8844:    value = uniqueID  
1.747     albertel 8845: 
1.608     albertel 8846: =back
                   8847: 
1.243     albertel 8848: =head2 HTTP Helper Routines
                   8849: 
                   8850: =over 4
                   8851: 
1.191     harris41 8852: =item *
                   8853: 
                   8854: escape() : unpack non-word characters into CGI-compatible hex codes
                   8855: 
                   8856: =item *
                   8857: 
                   8858: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8859: 
1.243     albertel 8860: =back
                   8861: 
                   8862: =head1 PRIVATE SUBROUTINES
                   8863: 
                   8864: =head2 Underlying communication routines (Shouldn't call)
                   8865: 
                   8866: =over 4
                   8867: 
                   8868: =item *
                   8869: 
                   8870: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8871: 
                   8872: =item *
                   8873: 
                   8874: reply() : uses subreply to send a message to remote machine, logs all failures
                   8875: 
                   8876: =item *
                   8877: 
                   8878: critical() : passes a critical message to another server; if cannot
                   8879: get through then place message in connection buffer directory and
                   8880: returns con_delayed, if incapable of saving message, returns
                   8881: con_failed
                   8882: 
                   8883: =item *
                   8884: 
                   8885: reconlonc() : tries to reconnect lonc client processes.
                   8886: 
                   8887: =back
                   8888: 
                   8889: =head2 Resource Access Logging
                   8890: 
                   8891: =over 4
                   8892: 
                   8893: =item *
                   8894: 
                   8895: flushcourselogs() : flush (save) buffer logs and access logs
                   8896: 
                   8897: =item *
                   8898: 
                   8899: courselog($what) : save message for course in hash
                   8900: 
                   8901: =item *
                   8902: 
                   8903: courseacclog($what) : save message for course using &courselog().  Perform
                   8904: special processing for specific resource types (problems, exams, quizzes, etc).
                   8905: 
1.191     harris41 8906: =item *
                   8907: 
                   8908: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8909: as a PerlChildExitHandler
1.243     albertel 8910: 
                   8911: =back
                   8912: 
                   8913: =head2 Other
                   8914: 
                   8915: =over 4
                   8916: 
                   8917: =item *
                   8918: 
                   8919: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8920: 
                   8921: =back
                   8922: 
                   8923: =cut

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