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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.805   ! raeburn     4: # $Id: lonnet.pm,v 1.804 2006/11/15 14:35:10 raeburn 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.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.740     www        56: use lib '/home/httpd/lib/perl';
                     57: use LONCAPA;
                     58: use LONCAPA::Configuration;
1.676     albertel   59: 
1.195     www        60: my $readit;
1.550     foxr       61: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   62: 
1.619     albertel   63: require Exporter;
                     64: 
                     65: our @ISA = qw (Exporter);
                     66: our @EXPORT = qw(%env);
                     67: 
1.449     matthew    68: =pod
                     69: 
                     70: =head1 Package Variables
                     71: 
                     72: These are largely undocumented, so if you decipher one please note it here.
                     73: 
                     74: =over 4
                     75: 
                     76: =item $processmarker
                     77: 
                     78: Contains the time this process was started and this servers host id.
                     79: 
                     80: =item $dumpcount
                     81: 
                     82: Counts the number of times a message log flush has been attempted (regardless
                     83: of success) by this process.  Used as part of the filename when messages are
                     84: delayed.
                     85: 
                     86: =back
                     87: 
                     88: =cut
                     89: 
                     90: 
1.1       albertel   91: # --------------------------------------------------------------------- Logging
1.729     www        92: {
                     93:     my $logid;
                     94:     sub instructor_log {
                     95: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     96: 	$logid++;
                     97: 	my $id=time().'00000'.$$.'00000'.$logid;
                     98: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        99: 				    { $id => {
                    100: 					'exe_uname' => $env{'user.name'},
                    101: 					'exe_udom'  => $env{'user.domain'},
                    102: 					'exe_time'  => time(),
                    103: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    104: 					'delflag'   => $delflag,
                    105: 					'logentry'  => $storehash,
                    106: 					'uname'     => $uname,
                    107: 					'udom'      => $udom,
                    108: 				    }
                    109: 				  },
1.729     www       110: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    111: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    112: 				    );
                    113:     }
                    114: }
1.1       albertel  115: 
1.163     harris41  116: sub logtouch {
                    117:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  118:     unless (-e "$execdir/logs/lonnet.log") {	
                    119: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  120: 	close $fh;
                    121:     }
                    122:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    123:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    124: }
                    125: 
1.1       albertel  126: sub logthis {
                    127:     my $message=shift;
                    128:     my $execdir=$perlvar{'lonDaemons'};
                    129:     my $now=time;
                    130:     my $local=localtime($now);
1.448     albertel  131:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    132: 	print $fh "$local ($$): $message\n";
                    133: 	close($fh);
                    134:     }
1.1       albertel  135:     return 1;
                    136: }
                    137: 
                    138: sub logperm {
                    139:     my $message=shift;
                    140:     my $execdir=$perlvar{'lonDaemons'};
                    141:     my $now=time;
                    142:     my $local=localtime($now);
1.448     albertel  143:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    144: 	print $fh "$now:$message:$local\n";
                    145: 	close($fh);
                    146:     }
1.1       albertel  147:     return 1;
                    148: }
                    149: 
                    150: # -------------------------------------------------- Non-critical communication
                    151: sub subreply {
                    152:     my ($cmd,$server)=@_;
1.704     albertel  153:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      154:     #
                    155:     #  With loncnew process trimming, there's a timing hole between lonc server
                    156:     #  process exit and the master server picking up the listen on the AF_UNIX
                    157:     #  socket.  In that time interval, a lock file will exist:
                    158: 
                    159:     my $lockfile=$peerfile.".lock";
                    160:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    161: 	sleep(1);
                    162:     }
                    163:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      164:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      165:     #
1.550     foxr      166:     #   We'll give the connection a few tries before abandoning it.  If
                    167:     #   connection is not possible, we'll con_lost back to the client.
                    168:     #   
                    169:     my $client;
                    170:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    171: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    172: 				      Type    => SOCK_STREAM,
                    173: 				      Timeout => 10);
                    174: 	if($client) {
                    175: 	    last;		# Connected!
                    176: 	}
                    177: 	sleep(1);		# Try again later if failed connection.
                    178:     }
                    179:     my $answer;
                    180:     if ($client) {
1.704     albertel  181: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      182: 	$answer=<$client>;
                    183: 	if (!$answer) { $answer="con_lost"; }
                    184: 	chomp($answer);
                    185:     } else {
                    186: 	$answer = 'con_lost';	# Failed connection.
                    187:     }
1.1       albertel  188:     return $answer;
                    189: }
                    190: 
                    191: sub reply {
                    192:     my ($cmd,$server)=@_;
1.205     www       193:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  194:     my $answer=subreply($cmd,$server);
1.65      www       195:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  196:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       197:                 " $cmd to $server returned $answer</font>");
                    198:     }
1.1       albertel  199:     return $answer;
                    200: }
                    201: 
                    202: # ----------------------------------------------------------- Send USR1 to lonc
                    203: 
                    204: sub reconlonc {
                    205:     my $peerfile=shift;
                    206:     &logthis("Trying to reconnect for $peerfile");
                    207:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  208:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  209: 	my $loncpid=<$fh>;
                    210:         chomp($loncpid);
                    211:         if (kill 0 => $loncpid) {
                    212: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    213:             kill USR1 => $loncpid;
                    214:             sleep 1;
                    215:             if (-e "$peerfile") { return; }
                    216:             &logthis("$peerfile still not there, give it another try");
                    217:             sleep 5;
                    218:             if (-e "$peerfile") { return; }
1.12      www       219:             &logthis(
1.672     albertel  220:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  221:         } else {
1.12      www       222: 	    &logthis(
1.672     albertel  223:                "<font color=\"blue\">WARNING:".
1.12      www       224:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  225:         }
                    226:     } else {
1.672     albertel  227:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  228:     }
                    229: }
                    230: 
                    231: # ------------------------------------------------------ Critical communication
1.12      www       232: 
1.1       albertel  233: sub critical {
                    234:     my ($cmd,$server)=@_;
1.89      www       235:     unless ($hostname{$server}) {
1.672     albertel  236:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       237:                " Critical message to unknown server ($server)</font>");
                    238:         return 'no_such_host';
                    239:     }
1.1       albertel  240:     my $answer=reply($cmd,$server);
                    241:     if ($answer eq 'con_lost') {
                    242: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  243: 	my $answer=reply($cmd,$server);
1.1       albertel  244:         if ($answer eq 'con_lost') {
                    245:             my $now=time;
                    246:             my $middlename=$cmd;
1.5       www       247:             $middlename=substr($middlename,0,16);
1.1       albertel  248:             $middlename=~s/\W//g;
                    249:             my $dfilename=
1.305     www       250:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    251:             $dumpcount++;
1.1       albertel  252:             {
1.448     albertel  253: 		my $dfh;
                    254: 		if (open($dfh,">$dfilename")) {
                    255: 		    print $dfh "$cmd\n"; 
                    256: 		    close($dfh);
                    257: 		}
1.1       albertel  258:             }
                    259:             sleep 2;
                    260:             my $wcmd='';
                    261:             {
1.448     albertel  262: 		my $dfh;
                    263: 		if (open($dfh,"<$dfilename")) {
                    264: 		    $wcmd=<$dfh>; 
                    265: 		    close($dfh);
                    266: 		}
1.1       albertel  267:             }
                    268:             chomp($wcmd);
1.7       www       269:             if ($wcmd eq $cmd) {
1.672     albertel  270: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       271:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  272:                 &logperm("D:$server:$cmd");
                    273: 	        return 'con_delayed';
                    274:             } else {
1.672     albertel  275:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       276:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  277:                 &logperm("F:$server:$cmd");
                    278:                 return 'con_failed';
                    279:             }
                    280:         }
                    281:     }
                    282:     return $answer;
1.405     albertel  283: }
                    284: 
1.755     albertel  285: # ------------------------------------------- check if return value is an error
                    286: 
                    287: sub error {
                    288:     my ($result) = @_;
1.756     albertel  289:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  290: 	if ($2 == 2) { return undef; }
                    291: 	return $1;
                    292:     }
                    293:     return undef;
                    294: }
                    295: 
1.783     albertel  296: sub convert_and_load_session_env {
                    297:     my ($lonidsdir,$handle)=@_;
                    298:     my @profile;
                    299:     {
                    300: 	open(my $idf,"$lonidsdir/$handle.id");
                    301: 	flock($idf,LOCK_SH);
                    302: 	@profile=<$idf>;
                    303: 	close($idf);
                    304:     }
                    305:     my %temp_env;
                    306:     foreach my $line (@profile) {
1.786     albertel  307: 	if ($line !~ m/=/) {
                    308: 	    return 0;
                    309: 	}
1.783     albertel  310: 	chomp($line);
                    311: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    312: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    313:     }
                    314:     unlink("$lonidsdir/$handle.id");
                    315:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    316: 	    0640)) {
                    317: 	%disk_env = %temp_env;
                    318: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    319: 	untie(%disk_env);
                    320:     }
1.786     albertel  321:     return 1;
1.783     albertel  322: }
                    323: 
1.374     www       324: # ------------------------------------------- Transfer profile into environment
1.780     albertel  325: my $env_loaded;
                    326: sub transfer_profile_to_env {
1.788     albertel  327:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    328:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       329: 
1.720     albertel  330:     if (!defined($lonidsdir)) {
                    331: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    332:     }
                    333:     if (!defined($handle)) {
                    334:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    335:     }
                    336: 
1.786     albertel  337:     my $convert;
                    338:     {
                    339:     	open(my $idf,"$lonidsdir/$handle.id");
                    340: 	flock($idf,LOCK_SH);
                    341: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    342: 		&GDBM_READER(),0640)) {
                    343: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    344: 	    untie(%disk_env);
                    345: 	} else {
                    346: 	    $convert = 1;
                    347: 	}
                    348:     }
                    349:     if ($convert) {
                    350: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    351: 	    &logthis("Failed to load session, or convert session.");
                    352: 	}
1.374     www       353:     }
1.783     albertel  354: 
1.786     albertel  355:     my %remove;
1.783     albertel  356:     while ( my $envname = each(%env) ) {
1.433     matthew   357:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    358:             if ($time < time-300) {
1.783     albertel  359:                 $remove{$key}++;
1.433     matthew   360:             }
                    361:         }
                    362:     }
1.783     albertel  363: 
1.619     albertel  364:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  365:     $env_loaded=1;
1.783     albertel  366:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   367:         &delenv($expired_key);
1.374     www       368:     }
1.1       albertel  369: }
                    370: 
1.5       www       371: # ---------------------------------------------------------- Append Environment
                    372: 
                    373: sub appenv {
1.6       www       374:     my %newenv=@_;
1.692     albertel  375:     foreach my $key (keys(%newenv)) {
                    376: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  377:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  378:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       379:                 .'</font>');
1.692     albertel  380: 	    delete($newenv{$key});
1.35      www       381:         } else {
1.692     albertel  382:             $env{$key}=$newenv{$key};
1.35      www       383:         }
1.191     harris41  384:     }
1.783     albertel  385:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    386: 	    0640)) {
                    387: 	while (my ($key,$value) = each(%newenv)) {
                    388: 	    $disk_env{$key} = $value;
1.448     albertel  389: 	}
1.783     albertel  390: 	untie(%disk_env);
1.56      www       391:     }
                    392:     return 'ok';
                    393: }
                    394: # ----------------------------------------------------- Delete from Environment
                    395: 
                    396: sub delenv {
                    397:     my $delthis=shift;
                    398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  399:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       400:                 "Attempt to delete from environment ".$delthis);
                    401:         return 'error';
                    402:     }
1.783     albertel  403:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    404: 	    0640)) {
                    405: 	foreach my $key (keys(%disk_env)) {
                    406: 	    if ($key=~/^$delthis/) { 
1.619     albertel  407:                 delete($env{$key});
1.783     albertel  408:                 delete($disk_env{$key});
1.473     matthew   409:             }
1.448     albertel  410: 	}
1.783     albertel  411: 	untie(%disk_env);
1.5       www       412:     }
                    413:     return 'ok';
1.369     albertel  414: }
                    415: 
1.790     albertel  416: sub get_env_multiple {
                    417:     my ($name) = @_;
                    418:     my @values;
                    419:     if (defined($env{$name})) {
                    420:         # exists is it an array
                    421:         if (ref($env{$name})) {
                    422:             @values=@{ $env{$name} };
                    423:         } else {
                    424:             $values[0]=$env{$name};
                    425:         }
                    426:     }
                    427:     return(@values);
                    428: }
                    429: 
1.369     albertel  430: # ------------------------------------------ Find out current server userload
                    431: # there is a copy in lond
                    432: sub userload {
                    433:     my $numusers=0;
                    434:     {
                    435: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    436: 	my $filename;
                    437: 	my $curtime=time;
                    438: 	while ($filename=readdir(LONIDS)) {
                    439: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  440: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  441: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  442: 	}
                    443: 	closedir(LONIDS);
                    444:     }
                    445:     my $userloadpercent=0;
                    446:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    447:     if ($maxuserload) {
1.371     albertel  448: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  449:     }
1.372     albertel  450:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  451:     return $userloadpercent;
1.283     www       452: }
                    453: 
                    454: # ------------------------------------------ Fight off request when overloaded
                    455: 
                    456: sub overloaderror {
                    457:     my ($r,$checkserver)=@_;
                    458:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    459:     my $loadavg;
                    460:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  461:        open(my $loadfile,'/proc/loadavg');
1.283     www       462:        $loadavg=<$loadfile>;
                    463:        $loadavg =~ s/\s.*//g;
1.285     matthew   464:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  465:        close($loadfile);
1.283     www       466:     } else {
                    467:        $loadavg=&reply('load',$checkserver);
                    468:     }
1.285     matthew   469:     my $overload=$loadavg-100;
1.283     www       470:     if ($overload>0) {
1.285     matthew   471: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       472:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       473:         return 413;
1.283     www       474:     }    
                    475:     return '';
1.5       www       476: }
1.1       albertel  477: 
                    478: # ------------------------------ Find server with least workload from spare.tab
1.11      www       479: 
1.1       albertel  480: sub spareserver {
1.670     albertel  481:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  482:     my $spare_server;
1.370     albertel  483:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  484:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    485:                                                      :  $userloadpercent;
                    486:     
                    487:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    488: 	($spare_server, $lowest_load) =
                    489: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    490:     }
                    491: 
                    492:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    493: 
                    494:     if (!$found_server) {
                    495: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    496: 	    ($spare_server, $lowest_load) =
                    497: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    498: 	}
                    499:     }
                    500: 
                    501:     if (!$want_server_name) {
                    502: 	$spare_server="http://$hostname{$spare_server}";
                    503:     }
                    504:     return $spare_server;
                    505: }
                    506: 
                    507: sub compare_server_load {
                    508:     my ($try_server, $spare_server, $lowest_load) = @_;
                    509: 
                    510:     my $loadans     = &reply('load',    $try_server);
                    511:     my $userloadans = &reply('userload',$try_server);
                    512: 
                    513:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    514: 	next; #didn't get a number from the server
                    515:     }
                    516: 
                    517:     my $load;
                    518:     if ($loadans =~ /\d/) {
                    519: 	if ($userloadans =~ /\d/) {
                    520: 	    #both are numbers, pick the bigger one
                    521: 	    $load = ($loadans > $userloadans) ? $loadans 
                    522: 		                              : $userloadans;
1.411     albertel  523: 	} else {
1.784     albertel  524: 	    $load = $loadans;
1.411     albertel  525: 	}
1.784     albertel  526:     } else {
                    527: 	$load = $userloadans;
                    528:     }
                    529: 
                    530:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    531: 	$spare_server = $try_server;
                    532: 	$lowest_load  = $load;
1.370     albertel  533:     }
1.784     albertel  534:     return ($spare_server,$lowest_load);
1.202     matthew   535: }
                    536: # --------------------------------------------- Try to change a user's password
                    537: 
                    538: sub changepass {
1.799     raeburn   539:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   540:     $currentpass = &escape($currentpass);
                    541:     $newpass     = &escape($newpass);
1.799     raeburn   542:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   543: 		       $server);
                    544:     if (! $answer) {
                    545: 	&logthis("No reply on password change request to $server ".
                    546: 		 "by $uname in domain $udom.");
                    547:     } elsif ($answer =~ "^ok") {
                    548:         &logthis("$uname in $udom successfully changed their password ".
                    549: 		 "on $server.");
                    550:     } elsif ($answer =~ "^pwchange_failure") {
                    551: 	&logthis("$uname in $udom was unable to change their password ".
                    552: 		 "on $server.  The action was blocked by either lcpasswd ".
                    553: 		 "or pwchange");
                    554:     } elsif ($answer =~ "^non_authorized") {
                    555:         &logthis("$uname in $udom did not get their password correct when ".
                    556: 		 "attempting to change it on $server.");
                    557:     } elsif ($answer =~ "^auth_mode_error") {
                    558:         &logthis("$uname in $udom attempted to change their password despite ".
                    559: 		 "not being locally or internally authenticated on $server.");
                    560:     } elsif ($answer =~ "^unknown_user") {
                    561:         &logthis("$uname in $udom attempted to change their password ".
                    562: 		 "on $server but were unable to because $server is not ".
                    563: 		 "their home server.");
                    564:     } elsif ($answer =~ "^refused") {
                    565: 	&logthis("$server refused to change $uname in $udom password because ".
                    566: 		 "it was sent an unencrypted request to change the password.");
                    567:     }
                    568:     return $answer;
1.1       albertel  569: }
                    570: 
1.169     harris41  571: # ----------------------- Try to determine user's current authentication scheme
                    572: 
                    573: sub queryauthenticate {
                    574:     my ($uname,$udom)=@_;
1.456     albertel  575:     my $uhome=&homeserver($uname,$udom);
                    576:     if (!$uhome) {
                    577: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    578: 	return 'no_host';
                    579:     }
                    580:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    581:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    582: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  583:     }
1.456     albertel  584:     return $answer;
1.169     harris41  585: }
                    586: 
1.1       albertel  587: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       588: 
1.1       albertel  589: sub authenticate {
                    590:     my ($uname,$upass,$udom)=@_;
1.12      www       591:     $upass=escape($upass);
1.199     www       592:     $uname=~s/\W//g;
1.471     albertel  593:     my $uhome=&homeserver($uname,$udom);
                    594:     if (!$uhome) {
                    595: 	&logthis("User $uname at $udom is unknown in authenticate");
                    596: 	return 'no_host';
1.1       albertel  597:     }
1.471     albertel  598:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    599:     if ($answer eq 'authorized') {
                    600: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    601: 	return $uhome; 
                    602:     }
                    603:     if ($answer eq 'non_authorized') {
                    604: 	&logthis("User $uname at $udom rejected by $uhome");
                    605: 	return 'no_host'; 
1.9       www       606:     }
1.471     albertel  607:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  608:     return 'no_host';
                    609: }
                    610: 
                    611: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       612: 
1.599     albertel  613: my %homecache;
1.1       albertel  614: sub homeserver {
1.230     stredwic  615:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  616:     my $index="$uname:$udom";
1.426     albertel  617: 
1.599     albertel  618:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  619:     my $tryserver;
                    620:     foreach $tryserver (keys %libserv) {
1.230     stredwic  621:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  622: 		 exists($badServerCache{$tryserver}));
1.1       albertel  623: 	if ($hostdom{$tryserver} eq $udom) {
                    624:            my $answer=reply("home:$udom:$uname",$tryserver);
                    625:            if ($answer eq 'found') { 
1.599     albertel  626: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  627:            } elsif ($answer eq 'no_host') {
                    628: 	       $badServerCache{$tryserver}=1;
1.221     matthew   629:            }
1.1       albertel  630:        }
                    631:     }    
                    632:     return 'no_host';
1.70      www       633: }
                    634: 
                    635: # ------------------------------------- Find the usernames behind a list of IDs
                    636: 
                    637: sub idget {
                    638:     my ($udom,@ids)=@_;
                    639:     my %returnhash=();
                    640:     
                    641:     my $tryserver;
                    642:     foreach $tryserver (keys %libserv) {
                    643:        if ($hostdom{$tryserver} eq $udom) {
                    644: 	  my $idlist=join('&',@ids);
                    645:           $idlist=~tr/A-Z/a-z/; 
                    646: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    647:           my @answer=();
1.76      www       648:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       649: 	      @answer=split(/\&/,$reply);
                    650:           }                    ;
                    651:           my $i;
                    652:           for ($i=0;$i<=$#ids;$i++) {
                    653:               if ($answer[$i]) {
                    654: 		  $returnhash{$ids[$i]}=$answer[$i];
                    655:               } 
                    656:           }
                    657:        }
                    658:     }    
                    659:     return %returnhash;
                    660: }
                    661: 
                    662: # ------------------------------------- Find the IDs behind a list of usernames
                    663: 
                    664: sub idrget {
                    665:     my ($udom,@unames)=@_;
                    666:     my %returnhash=();
1.800     albertel  667:     foreach my $uname (@unames) {
                    668:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  669:     }
1.70      www       670:     return %returnhash;
                    671: }
                    672: 
                    673: # ------------------------------- Store away a list of names and associated IDs
                    674: 
                    675: sub idput {
                    676:     my ($udom,%ids)=@_;
                    677:     my %servers=();
1.800     albertel  678:     foreach my $uname (keys(%ids)) {
                    679: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    680:         my $uhom=&homeserver($uname,$udom);
1.70      www       681:         if ($uhom ne 'no_host') {
1.800     albertel  682:             my $id=&escape($ids{$uname});
1.70      www       683:             $id=~tr/A-Z/a-z/;
1.800     albertel  684:             my $esc_unam=&escape($uname);
1.70      www       685: 	    if ($servers{$uhom}) {
1.800     albertel  686: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       687:             } else {
1.800     albertel  688:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       689:             }
                    690:         }
1.191     harris41  691:     }
1.800     albertel  692:     foreach my $server (keys(%servers)) {
                    693:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  694:     }
1.344     www       695: }
                    696: 
                    697: # --------------------------------------------------- Assign a key to a student
                    698: 
                    699: sub assign_access_key {
1.364     www       700: #
                    701: # a valid key looks like uname:udom#comments
                    702: # comments are being appended
                    703: #
1.498     www       704:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    705:     $kdom=
1.620     albertel  706:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       707:     $knum=
1.620     albertel  708:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       709:     $cdom=
1.620     albertel  710:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       711:     $cnum=
1.620     albertel  712:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    713:     $udom=$env{'user.name'} unless (defined($udom));
                    714:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       715:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       716:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  717:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       718:                                                   # assigned to this person
                    719:                                                   # - this should not happen,
1.345     www       720:                                                   # unless something went wrong
                    721:                                                   # the first time around
                    722: # ready to assign
1.364     www       723:         $logentry=$1.'; '.$logentry;
1.496     www       724:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       725:                                                  $kdom,$knum) eq 'ok') {
1.345     www       726: # key now belongs to user
1.346     www       727: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       728:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    729:                 &appenv('environment.'.$envkey => $ckey);
                    730:                 return 'ok';
                    731:             } else {
                    732:                 return 
                    733:   'error: Count not permanently assign key, will need to be re-entered later.';
                    734: 	    }
                    735:         } else {
                    736:             return 'error: Could not assign key, try again later.';
                    737:         }
1.364     www       738:     } elsif (!$existing{$ckey}) {
1.345     www       739: # the key does not exist
                    740: 	return 'error: The key does not exist';
                    741:     } else {
                    742: # the key is somebody else's
                    743: 	return 'error: The key is already in use';
                    744:     }
1.344     www       745: }
                    746: 
1.364     www       747: # ------------------------------------------ put an additional comment on a key
                    748: 
                    749: sub comment_access_key {
                    750: #
                    751: # a valid key looks like uname:udom#comments
                    752: # comments are being appended
                    753: #
                    754:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    755:     $cdom=
1.620     albertel  756:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       757:     $cnum=
1.620     albertel  758:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       759:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    760:     if ($existing{$ckey}) {
                    761:         $existing{$ckey}.='; '.$logentry;
                    762: # ready to assign
1.367     www       763:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       764:                                                  $cdom,$cnum) eq 'ok') {
                    765: 	    return 'ok';
                    766:         } else {
                    767: 	    return 'error: Count not store comment.';
                    768:         }
                    769:     } else {
                    770: # the key does not exist
                    771: 	return 'error: The key does not exist';
                    772:     }
                    773: }
                    774: 
1.344     www       775: # ------------------------------------------------------ Generate a set of keys
                    776: 
                    777: sub generate_access_keys {
1.364     www       778:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       779:     $cdom=
1.620     albertel  780:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       781:     $cnum=
1.620     albertel  782:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       783:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       784:     unless (($cdom) && ($cnum)) { return 0; }
                    785:     if ($number>10000) { return 0; }
                    786:     sleep(2); # make sure don't get same seed twice
                    787:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    788:     my $total=0;
                    789:     for (my $i=1;$i<=$number;$i++) {
                    790:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    791:                   sprintf("%lx",int(100000*rand)).'-'.
                    792:                   sprintf("%lx",int(100000*rand));
                    793:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    794:        $newkey=~s/0/h/g; # and also 0 and O
                    795:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    796:        if ($existing{$newkey}) {
                    797:            $i--;
                    798:        } else {
1.364     www       799: 	  if (&put('accesskeys',
                    800:               { $newkey => '# generated '.localtime().
1.620     albertel  801:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       802:                            '; '.$logentry },
                    803: 		   $cdom,$cnum) eq 'ok') {
1.344     www       804:               $total++;
                    805: 	  }
                    806:        }
                    807:     }
1.620     albertel  808:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       809:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    810:     return $total;
                    811: }
                    812: 
                    813: # ------------------------------------------------------- Validate an accesskey
                    814: 
                    815: sub validate_access_key {
                    816:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    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.domain'} unless (defined($udom));
                    822:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       823:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  824:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       825: }
                    826: 
                    827: # ------------------------------------- Find the section of student in a course
1.652     albertel  828: sub devalidate_getsection_cache {
                    829:     my ($udom,$unam,$courseid)=@_;
                    830:     $courseid=~s/\_/\//g;
                    831:     $courseid=~s/^(\w)/\/$1/;
                    832:     my $hashid="$udom:$unam:$courseid";
                    833:     &devalidate_cache_new('getsection',$hashid);
                    834: }
1.298     matthew   835: 
                    836: sub getsection {
                    837:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  838:     my $cachetime=1800;
1.298     matthew   839:     $courseid=~s/\_/\//g;
                    840:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  841: 
                    842:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  843:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  844:     if (defined($cached)) { return $result; }
                    845: 
1.298     matthew   846:     my %Pending; 
                    847:     my %Expired;
                    848:     #
                    849:     # Each role can either have not started yet (pending), be active, 
                    850:     #    or have expired.
                    851:     #
                    852:     # If there is an active role, we are done.
                    853:     #
                    854:     # If there is more than one role which has not started yet, 
                    855:     #     choose the one which will start sooner
                    856:     # If there is one role which has not started yet, return it.
                    857:     #
                    858:     # If there is more than one expired role, choose the one which ended last.
                    859:     # If there is a role which has expired, return it.
                    860:     #
1.800     albertel  861:     foreach my $line (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    862: 					&homeserver($unam,$udom)))) {
                    863:         my ($key,$value)=split(/\=/,$line,2);
1.298     matthew   864:         $key=&unescape($key);
1.479     albertel  865:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   866:         my $section=$1;
                    867:         if ($key eq $courseid.'_st') { $section=''; }
                    868:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    869:         my $now=time;
1.548     albertel  870:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   871:             $Expired{$end}=$section;
                    872:             next;
                    873:         }
1.548     albertel  874:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   875:             $Pending{$start}=$section;
                    876:             next;
                    877:         }
1.599     albertel  878:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   879:     }
                    880:     #
                    881:     # Presumedly there will be few matching roles from the above
                    882:     # loop and the sorting time will be negligible.
                    883:     if (scalar(keys(%Pending))) {
                    884:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  885:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   886:     } 
                    887:     if (scalar(keys(%Expired))) {
                    888:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    889:         my $time = pop(@sorted);
1.599     albertel  890:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   891:     }
1.599     albertel  892:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   893: }
1.70      www       894: 
1.599     albertel  895: sub save_cache {
                    896:     &purge_remembered();
1.722     albertel  897:     #&Apache::loncommon::validate_page();
1.620     albertel  898:     undef(%env);
1.780     albertel  899:     undef($env_loaded);
1.599     albertel  900: }
1.452     albertel  901: 
1.599     albertel  902: my $to_remember=-1;
                    903: my %remembered;
                    904: my %accessed;
                    905: my $kicks=0;
                    906: my $hits=0;
                    907: sub devalidate_cache_new {
                    908:     my ($name,$id,$debug) = @_;
                    909:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    910:     $id=&escape($name.':'.$id);
                    911:     $memcache->delete($id);
                    912:     delete($remembered{$id});
                    913:     delete($accessed{$id});
                    914: }
                    915: 
                    916: sub is_cached_new {
                    917:     my ($name,$id,$debug) = @_;
                    918:     $id=&escape($name.':'.$id);
                    919:     if (exists($remembered{$id})) {
                    920: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    921: 	$accessed{$id}=[&gettimeofday()];
                    922: 	$hits++;
                    923: 	return ($remembered{$id},1);
                    924:     }
                    925:     my $value = $memcache->get($id);
                    926:     if (!(defined($value))) {
                    927: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  928: 	return (undef,undef);
1.416     albertel  929:     }
1.599     albertel  930:     if ($value eq '__undef__') {
                    931: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    932: 	$value=undef;
                    933:     }
                    934:     &make_room($id,$value,$debug);
                    935:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    936:     return ($value,1);
                    937: }
                    938: 
                    939: sub do_cache_new {
                    940:     my ($name,$id,$value,$time,$debug) = @_;
                    941:     $id=&escape($name.':'.$id);
                    942:     my $setvalue=$value;
                    943:     if (!defined($setvalue)) {
                    944: 	$setvalue='__undef__';
                    945:     }
1.623     albertel  946:     if (!defined($time) ) {
                    947: 	$time=600;
                    948:     }
1.599     albertel  949:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  950:     $memcache->set($id,$setvalue,$time);
                    951:     # need to make a copy of $value
                    952:     #&make_room($id,$value,$debug);
1.599     albertel  953:     return $value;
                    954: }
                    955: 
                    956: sub make_room {
                    957:     my ($id,$value,$debug)=@_;
                    958:     $remembered{$id}=$value;
                    959:     if ($to_remember<0) { return; }
                    960:     $accessed{$id}=[&gettimeofday()];
                    961:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    962:     my $to_kick;
                    963:     my $max_time=0;
                    964:     foreach my $other (keys(%accessed)) {
                    965: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    966: 	    $to_kick=$other;
                    967: 	    $max_time=&tv_interval($accessed{$other});
                    968: 	}
                    969:     }
                    970:     delete($remembered{$to_kick});
                    971:     delete($accessed{$to_kick});
                    972:     $kicks++;
                    973:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  974:     return;
                    975: }
                    976: 
1.599     albertel  977: sub purge_remembered {
1.604     albertel  978:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    979:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  980:     undef(%remembered);
                    981:     undef(%accessed);
1.428     albertel  982: }
1.70      www       983: # ------------------------------------- Read an entry from a user's environment
                    984: 
                    985: sub userenvironment {
                    986:     my ($udom,$unam,@what)=@_;
                    987:     my %returnhash=();
                    988:     my @answer=split(/\&/,
                    989:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    990:                       &homeserver($unam,$udom)));
                    991:     my $i;
                    992:     for ($i=0;$i<=$#what;$i++) {
                    993: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    994:     }
                    995:     return %returnhash;
1.1       albertel  996: }
                    997: 
1.617     albertel  998: # ---------------------------------------------------------- Get a studentphoto
                    999: sub studentphoto {
                   1000:     my ($udom,$unam,$ext) = @_;
                   1001:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1002:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1003:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1004:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1005:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1006:             } else {
                   1007:                 my ($result,$perm_reqd)=
1.707     albertel 1008: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1009:                 if ($result eq 'ok') {
                   1010:                     if (!($perm_reqd eq 'yes')) {
                   1011:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1012:                     }
                   1013:                 }
                   1014:             }
                   1015:         }
                   1016:     } else {
                   1017:         my ($result,$perm_reqd) = 
1.707     albertel 1018: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1019:         if ($result eq 'ok') {
                   1020:             if (!($perm_reqd eq 'yes')) {
                   1021:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1022:             }
                   1023:         }
                   1024:     }
                   1025:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1026: }
                   1027: 
                   1028: sub retrievestudentphoto {
                   1029:     my ($udom,$unam,$ext,$type) = @_;
                   1030:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1031:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1032:     if ($ret eq 'ok') {
                   1033:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1034:         if ($type eq 'thumbnail') {
                   1035:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1036:         }
                   1037:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1038:         return $tokenurl;
                   1039:     } else {
                   1040:         if ($type eq 'thumbnail') {
                   1041:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1042:         } else { 
                   1043:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1044:         }
1.617     albertel 1045:     }
                   1046: }
                   1047: 
1.263     www      1048: # -------------------------------------------------------------------- New chat
                   1049: 
                   1050: sub chatsend {
1.724     raeburn  1051:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1052:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1053:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1054:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1055:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1056: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1057: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1058: }
                   1059: 
                   1060: # ------------------------------------------ Find current version of a resource
                   1061: 
                   1062: sub getversion {
                   1063:     my $fname=&clutter(shift);
                   1064:     unless ($fname=~/^\/res\//) { return -1; }
                   1065:     return &currentversion(&filelocation('',$fname));
                   1066: }
                   1067: 
                   1068: sub currentversion {
                   1069:     my $fname=shift;
1.599     albertel 1070:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1071:     if (defined($cached)) { return $result; }
1.292     www      1072:     my $author=$fname;
                   1073:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1074:     my ($udom,$uname)=split(/\//,$author);
                   1075:     my $home=homeserver($uname,$udom);
                   1076:     if ($home eq 'no_host') { 
                   1077:         return -1; 
                   1078:     }
                   1079:     my $answer=reply("currentversion:$fname",$home);
                   1080:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1081: 	return -1;
                   1082:     }
1.599     albertel 1083:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1084: }
                   1085: 
1.1       albertel 1086: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1087: 
1.1       albertel 1088: sub subscribe {
                   1089:     my $fname=shift;
1.761     raeburn  1090:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1091:     $fname=~s/[\n\r]//g;
1.1       albertel 1092:     my $author=$fname;
                   1093:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1094:     my ($udom,$uname)=split(/\//,$author);
                   1095:     my $home=homeserver($uname,$udom);
1.335     albertel 1096:     if ($home eq 'no_host') {
                   1097:         return 'not_found';
1.1       albertel 1098:     }
                   1099:     my $answer=reply("sub:$fname",$home);
1.64      www      1100:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1101: 	$answer.=' by '.$home;
                   1102:     }
1.1       albertel 1103:     return $answer;
                   1104: }
                   1105:     
1.8       www      1106: # -------------------------------------------------------------- Replicate file
                   1107: 
                   1108: sub repcopy {
                   1109:     my $filename=shift;
1.23      www      1110:     $filename=~s/\/+/\//g;
1.607     raeburn  1111:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1112:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1113:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1114: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1115: 	return &repcopy_userfile($filename);
                   1116:     }
1.532     albertel 1117:     $filename=~s/[\n\r]//g;
1.8       www      1118:     my $transname="$filename.in.transfer";
1.607     raeburn  1119:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1120:     my $remoteurl=subscribe($filename);
1.64      www      1121:     if ($remoteurl =~ /^con_lost by/) {
                   1122: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1123:            return 'unavailable';
1.8       www      1124:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1125: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1126: 	   return 'not_found';
1.64      www      1127:     } elsif ($remoteurl =~ /^rejected by/) {
                   1128: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1129:            return 'forbidden';
1.20      www      1130:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1131:            return 'ok';
1.8       www      1132:     } else {
1.290     www      1133:         my $author=$filename;
                   1134:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1135:         my ($udom,$uname)=split(/\//,$author);
                   1136:         my $home=homeserver($uname,$udom);
                   1137:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1138:            my @parts=split(/\//,$filename);
                   1139:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1140:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1141:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1142: 	       return 'bad_request';
1.8       www      1143:            }
                   1144:            my $count;
                   1145:            for ($count=5;$count<$#parts;$count++) {
                   1146:                $path.="/$parts[$count]";
                   1147:                if ((-e $path)!=1) {
                   1148: 		   mkdir($path,0777);
                   1149:                }
                   1150:            }
                   1151:            my $ua=new LWP::UserAgent;
                   1152:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1153:            my $response=$ua->request($request,$transname);
                   1154:            if ($response->is_error()) {
                   1155: 	       unlink($transname);
                   1156:                my $message=$response->status_line;
1.672     albertel 1157:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1158:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1159:                return 'unavailable';
1.8       www      1160:            } else {
1.16      www      1161: 	       if ($remoteurl!~/\.meta$/) {
                   1162:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1163:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1164:                   if ($mresponse->is_error()) {
                   1165: 		      unlink($filename.'.meta');
                   1166:                       &logthis(
1.672     albertel 1167:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1168:                   }
                   1169: 	       }
1.8       www      1170:                rename($transname,$filename);
1.607     raeburn  1171:                return 'ok';
1.8       www      1172:            }
1.290     www      1173:        }
1.8       www      1174:     }
1.330     www      1175: }
                   1176: 
                   1177: # ------------------------------------------------ Get server side include body
                   1178: sub ssi_body {
1.381     albertel 1179:     my ($filelink,%form)=@_;
1.606     matthew  1180:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1181:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1182:     }
1.330     www      1183:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1184:                                      &ssi($filelink,%form));
1.778     albertel 1185:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1186:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1187:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1188:     return $output;
1.8       www      1189: }
                   1190: 
1.15      www      1191: # --------------------------------------------------------- Server Side Include
                   1192: 
1.782     albertel 1193: sub absolute_url {
                   1194:     my ($host_name) = @_;
                   1195:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1196:     if ($host_name eq '') {
                   1197: 	$host_name = $ENV{'SERVER_NAME'};
                   1198:     }
                   1199:     return $protocol.$host_name;
                   1200: }
                   1201: 
1.15      www      1202: sub ssi {
                   1203: 
1.23      www      1204:     my ($fn,%form)=@_;
1.15      www      1205: 
                   1206:     my $ua=new LWP::UserAgent;
1.23      www      1207:     
                   1208:     my $request;
1.711     albertel 1209: 
                   1210:     $form{'no_update_last_known'}=1;
                   1211: 
1.23      www      1212:     if (%form) {
1.782     albertel 1213:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1214:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1215:     } else {
1.782     albertel 1216:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1217:     }
                   1218: 
1.15      www      1219:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1220:     my $response=$ua->request($request);
                   1221: 
1.324     www      1222:     return $response->content;
                   1223: }
                   1224: 
                   1225: sub externalssi {
                   1226:     my ($url)=@_;
                   1227:     my $ua=new LWP::UserAgent;
                   1228:     my $request=new HTTP::Request('GET',$url);
                   1229:     my $response=$ua->request($request);
1.15      www      1230:     return $response->content;
                   1231: }
1.254     www      1232: 
1.492     albertel 1233: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1234: 
                   1235: sub allowuploaded {
                   1236:     my ($srcurl,$url)=@_;
                   1237:     $url=&clutter(&declutter($url));
                   1238:     my $dir=$url;
                   1239:     $dir=~s/\/[^\/]+$//;
                   1240:     my %httpref=();
                   1241:     my $httpurl=&hreflocation('',$url);
                   1242:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1243:     &Apache::lonnet::appenv(%httpref);
1.254     www      1244: }
1.477     raeburn  1245: 
1.478     albertel 1246: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1247: # input: action, courseID, current domain, intended
1.637     raeburn  1248: #        path to file, source of file, instruction to parse file for objects,
                   1249: #        ref to hash for embedded objects,
                   1250: #        ref to hash for codebase of java objects.
                   1251: #
1.485     raeburn  1252: # output: url to file (if action was uploaddoc), 
                   1253: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1254: #
1.478     albertel 1255: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1256: # course.
1.477     raeburn  1257: #
1.478     albertel 1258: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1259: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1260: #          course's home server.
1.477     raeburn  1261: #
1.478     albertel 1262: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1263: #          be copied from $source (current location) to 
                   1264: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1265: #         and will then be copied to
                   1266: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1267: #         course's home server.
1.485     raeburn  1268: #
1.481     raeburn  1269: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1270: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1271: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1272: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1273: #         in course's home server.
1.637     raeburn  1274: #
1.477     raeburn  1275: 
                   1276: sub process_coursefile {
1.638     albertel 1277:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1278:     my $fetchresult;
1.638     albertel 1279:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1280:     if ($action eq 'propagate') {
1.638     albertel 1281:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1282: 			     $home);
1.481     raeburn  1283:     } else {
1.477     raeburn  1284:         my $fpath = '';
                   1285:         my $fname = $file;
1.478     albertel 1286:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1287:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1288:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1289:         if ($action eq 'copy') {
                   1290:             if ($source eq '') {
                   1291:                 $fetchresult = 'no source file';
                   1292:                 return $fetchresult;
                   1293:             } else {
                   1294:                 my $destination = $filepath.'/'.$fname;
                   1295:                 rename($source,$destination);
                   1296:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1297:                                  $home);
1.481     raeburn  1298:             }
                   1299:         } elsif ($action eq 'uploaddoc') {
                   1300:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1301:             print $fh $env{'form.'.$source};
1.481     raeburn  1302:             close($fh);
1.637     raeburn  1303:             if ($parser eq 'parse') {
                   1304:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1305:                 unless ($parse_result eq 'ok') {
                   1306:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1307:                 }
                   1308:             }
1.477     raeburn  1309:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1310:                                  $home);
1.481     raeburn  1311:             if ($fetchresult eq 'ok') {
                   1312:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1313:             } else {
                   1314:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1315:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1316:                 return '/adm/notfound.html';
                   1317:             }
1.477     raeburn  1318:         }
                   1319:     }
1.485     raeburn  1320:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1321:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1322:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1323:     }
                   1324:     return $fetchresult;
                   1325: }
                   1326: 
1.637     raeburn  1327: sub build_filepath {
                   1328:     my ($fpath) = @_;
                   1329:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1330:     unless ($fpath eq '') {
                   1331:         my @parts=split('/',$fpath);
                   1332:         foreach my $part (@parts) {
                   1333:             $filepath.= '/'.$part;
                   1334:             if ((-e $filepath)!=1) {
                   1335:                 mkdir($filepath,0777);
                   1336:             }
                   1337:         }
                   1338:     }
                   1339:     return $filepath;
                   1340: }
                   1341: 
                   1342: sub store_edited_file {
1.638     albertel 1343:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1344:     my $file = $primary_url;
                   1345:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1346:     my $fpath = '';
                   1347:     my $fname = $file;
                   1348:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1349:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1350:     my $filepath = &build_filepath($fpath);
                   1351:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1352:     print $fh $content;
                   1353:     close($fh);
1.638     albertel 1354:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1355:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1356: 			  $home);
1.637     raeburn  1357:     if ($$fetchresult eq 'ok') {
                   1358:         return '/uploaded/'.$fpath.'/'.$fname;
                   1359:     } else {
1.638     albertel 1360:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1361: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1362:         return '/adm/notfound.html';
                   1363:     }
                   1364: }
                   1365: 
1.531     albertel 1366: sub clean_filename {
                   1367:     my ($fname)=@_;
1.315     www      1368: # Replace Windows backslashes by forward slashes
1.257     www      1369:     $fname=~s/\\/\//g;
1.315     www      1370: # Get rid of everything but the actual filename
1.257     www      1371:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1372: # Replace spaces by underscores
                   1373:     $fname=~s/\s+/\_/g;
                   1374: # Replace all other weird characters by nothing
1.317     www      1375:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1376: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1377: # numbers
                   1378:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1379:     return $fname;
                   1380: }
                   1381: 
1.608     albertel 1382: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1383: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1384: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1385: #        $coursedoc - if true up to the current course
                   1386: #                     if false
                   1387: #        $subdir - directory in userfile to store the file into
                   1388: #        $parser, $allfiles, $codebase - unknown
                   1389: #
                   1390: # output: url of file in userspace, or error: <message> 
                   1391: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1392: 
                   1393: 
1.531     albertel 1394: sub userfileupload {
1.719     banghart 1395:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1396:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1397:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1398:     $fname=&clean_filename($fname);
1.315     www      1399: # See if there is anything left
1.257     www      1400:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1401:     chop($env{'form.'.$formname});
1.523     raeburn  1402:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1403:         my $now = time;
                   1404:         my $filepath = 'tmp/helprequests/'.$now;
                   1405:         my @parts=split(/\//,$filepath);
                   1406:         my $fullpath = $perlvar{'lonDaemons'};
                   1407:         for (my $i=0;$i<@parts;$i++) {
                   1408:             $fullpath .= '/'.$parts[$i];
                   1409:             if ((-e $fullpath)!=1) {
                   1410:                 mkdir($fullpath,0777);
                   1411:             }
                   1412:         }
                   1413:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1414:         print $fh $env{'form.'.$formname};
1.523     raeburn  1415:         close($fh);
1.741     raeburn  1416:         return $fullpath.'/'.$fname;
                   1417:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1418:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1419:                        '_'.$env{'user.domain'}.'/pending';
                   1420:         my @parts=split(/\//,$filepath);
                   1421:         my $fullpath = $perlvar{'lonDaemons'};
                   1422:         for (my $i=0;$i<@parts;$i++) {
                   1423:             $fullpath .= '/'.$parts[$i];
                   1424:             if ((-e $fullpath)!=1) {
                   1425:                 mkdir($fullpath,0777);
                   1426:             }
                   1427:         }
                   1428:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1429:         print $fh $env{'form.'.$formname};
                   1430:         close($fh);
                   1431:         return $fullpath.'/'.$fname;
1.523     raeburn  1432:     }
1.719     banghart 1433:     
1.258     www      1434: # Create the directory if not present
1.493     albertel 1435:     $fname="$subdir/$fname";
1.259     www      1436:     if ($coursedoc) {
1.638     albertel 1437: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1438: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1439:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1440:             return &finishuserfileupload($docuname,$docudom,
                   1441: 					 $formname,$fname,$parser,$allfiles,
                   1442: 					 $codebase);
1.481     raeburn  1443:         } else {
1.620     albertel 1444:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1445:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1446: 				       $fname,$formname,$parser,
                   1447: 				       $allfiles,$codebase);
1.481     raeburn  1448:         }
1.719     banghart 1449:     } elsif (defined($destuname)) {
                   1450:         my $docuname=$destuname;
                   1451:         my $docudom=$destudom;
                   1452: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1453: 				     $fname,$parser,$allfiles,$codebase);
                   1454:         
1.259     www      1455:     } else {
1.638     albertel 1456:         my $docuname=$env{'user.name'};
                   1457:         my $docudom=$env{'user.domain'};
1.714     raeburn  1458:         if (exists($env{'form.group'})) {
                   1459:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1460:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1461:         }
1.638     albertel 1462: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1463: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1464:     }
1.271     www      1465: }
                   1466: 
                   1467: sub finishuserfileupload {
1.638     albertel 1468:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1469:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1470:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1471:     my ($fnamepath,$file);
                   1472:     $file=$fname;
                   1473:     if ($fname=~m|/|) {
                   1474:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1475: 	$path.=$fnamepath.'/';
                   1476:     }
1.259     www      1477:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1478:     my $count;
                   1479:     for ($count=4;$count<=$#parts;$count++) {
                   1480:         $filepath.="/$parts[$count]";
                   1481:         if ((-e $filepath)!=1) {
                   1482: 	    mkdir($filepath,0777);
                   1483:         }
                   1484:     }
                   1485: # Save the file
                   1486:     {
1.701     albertel 1487: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1488: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1489: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1490: 	    return '/adm/notfound.html';
                   1491: 	}
                   1492: 	if (!print FH ($env{'form.'.$formname})) {
                   1493: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1494: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1495: 	    return '/adm/notfound.html';
                   1496: 	}
1.570     albertel 1497: 	close(FH);
1.258     www      1498:     }
1.637     raeburn  1499:     if ($parser eq 'parse') {
1.638     albertel 1500:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1501: 						   $codebase);
1.637     raeburn  1502:         unless ($parse_result eq 'ok') {
1.638     albertel 1503:             &logthis('Failed to parse '.$filepath.$file.
                   1504: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1505:         }
                   1506:     }
1.259     www      1507: # Notify homeserver to grep it
                   1508: #
1.638     albertel 1509:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1510:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1511:     if ($fetchresult eq 'ok') {
1.259     www      1512: #
1.258     www      1513: # Return the URL to it
1.494     albertel 1514:         return '/uploaded/'.$path.$file;
1.263     www      1515:     } else {
1.494     albertel 1516:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1517: 		 ': '.$fetchresult);
1.263     www      1518:         return '/adm/notfound.html';
                   1519:     }    
1.493     albertel 1520: }
                   1521: 
1.637     raeburn  1522: sub extract_embedded_items {
1.648     raeburn  1523:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1524:     my @state = ();
                   1525:     my %javafiles = (
                   1526:                       codebase => '',
                   1527:                       code => '',
                   1528:                       archive => ''
                   1529:                     );
                   1530:     my %mediafiles = (
                   1531:                       src => '',
                   1532:                       movie => '',
                   1533:                      );
1.648     raeburn  1534:     my $p;
                   1535:     if ($content) {
                   1536:         $p = HTML::LCParser->new($content);
                   1537:     } else {
                   1538:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1539:     }
1.641     albertel 1540:     while (my $t=$p->get_token()) {
1.640     albertel 1541: 	if ($t->[0] eq 'S') {
                   1542: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1543: 	    push (@state, $tagname);
1.648     raeburn  1544:             if (lc($tagname) eq 'allow') {
                   1545:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1546:             }
1.640     albertel 1547: 	    if (lc($tagname) eq 'img') {
                   1548: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1549: 	    }
1.645     raeburn  1550:             if (lc($tagname) eq 'script') {
                   1551:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1552:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1553:                 } else {
                   1554:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1555:                 }
                   1556:             }
                   1557:             if (lc($tagname) eq 'link') {
                   1558:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1559:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1560:                 }
                   1561:             }
1.640     albertel 1562: 	    if (lc($tagname) eq 'object' ||
                   1563: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1564: 		foreach my $item (keys(%javafiles)) {
                   1565: 		    $javafiles{$item} = '';
                   1566: 		}
                   1567: 	    }
                   1568: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1569: 		my $name = lc($attr->{'name'});
                   1570: 		foreach my $item (keys(%javafiles)) {
                   1571: 		    if ($name eq $item) {
                   1572: 			$javafiles{$item} = $attr->{'value'};
                   1573: 			last;
                   1574: 		    }
                   1575: 		}
                   1576: 		foreach my $item (keys(%mediafiles)) {
                   1577: 		    if ($name eq $item) {
                   1578: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1579: 			last;
                   1580: 		    }
                   1581: 		}
                   1582: 	    }
                   1583: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1584: 		foreach my $item (keys(%javafiles)) {
                   1585: 		    if ($attr->{$item}) {
                   1586: 			$javafiles{$item} = $attr->{$item};
                   1587: 			last;
                   1588: 		    }
                   1589: 		}
                   1590: 		foreach my $item (keys(%mediafiles)) {
                   1591: 		    if ($attr->{$item}) {
                   1592: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1593: 			last;
                   1594: 		    }
                   1595: 		}
                   1596: 	    }
                   1597: 	} elsif ($t->[0] eq 'E') {
                   1598: 	    my ($tagname) = ($t->[1]);
                   1599: 	    if ($javafiles{'codebase'} ne '') {
                   1600: 		$javafiles{'codebase'} .= '/';
                   1601: 	    }  
                   1602: 	    if (lc($tagname) eq 'applet' ||
                   1603: 		lc($tagname) eq 'object' ||
                   1604: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1605: 		) {
                   1606: 		foreach my $item (keys(%javafiles)) {
                   1607: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1608: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1609: 			&add_filetype($allfiles,$file,$item);
                   1610: 		    }
                   1611: 		}
                   1612: 	    } 
                   1613: 	    pop @state;
                   1614: 	}
                   1615:     }
1.637     raeburn  1616:     return 'ok';
                   1617: }
                   1618: 
1.639     albertel 1619: sub add_filetype {
                   1620:     my ($allfiles,$file,$type)=@_;
                   1621:     if (exists($allfiles->{$file})) {
                   1622: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1623: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1624: 	}
                   1625:     } else {
                   1626: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1627:     }
                   1628: }
                   1629: 
1.493     albertel 1630: sub removeuploadedurl {
                   1631:     my ($url)=@_;
                   1632:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1633:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1634: }
                   1635: 
                   1636: sub removeuserfile {
                   1637:     my ($docuname,$docudom,$fname)=@_;
                   1638:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1639:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1640:     if ($result eq 'ok') {
                   1641:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1642:             my $metafile = $fname.'.meta';
                   1643:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
                   1644:         }
                   1645:     }
                   1646:     return $result;
1.257     www      1647: }
1.15      www      1648: 
1.530     albertel 1649: sub mkdiruserfile {
                   1650:     my ($docuname,$docudom,$dir)=@_;
                   1651:     my $home=&homeserver($docuname,$docudom);
                   1652:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1653: }
                   1654: 
1.531     albertel 1655: sub renameuserfile {
                   1656:     my ($docuname,$docudom,$old,$new)=@_;
                   1657:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1658:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1659:                         &escape("$old").':'.&escape("$new"),$home);
                   1660:     if ($result eq 'ok') {
                   1661:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1662:             my $oldmeta = $old.'.meta';
                   1663:             my $newmeta = $new.'.meta';
                   1664:             my $metaresult = 
                   1665:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
                   1666:         }
                   1667:     }
                   1668:     return $result;
1.531     albertel 1669: }
                   1670: 
1.14      www      1671: # ------------------------------------------------------------------------- Log
                   1672: 
                   1673: sub log {
                   1674:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1675:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1676: }
                   1677: 
                   1678: # ------------------------------------------------------------------ Course Log
1.352     www      1679: #
                   1680: # This routine flushes several buffers of non-mission-critical nature
                   1681: #
1.157     www      1682: 
                   1683: sub flushcourselogs {
1.352     www      1684:     &logthis('Flushing log buffers');
                   1685: #
                   1686: # course logs
                   1687: # This is a log of all transactions in a course, which can be used
                   1688: # for data mining purposes
                   1689: #
                   1690: # It also collects the courseid database, which lists last transaction
                   1691: # times and course titles for all courseids
                   1692: #
                   1693:     my %courseidbuffer=();
1.800     albertel 1694:     foreach my $crsid (keys %courselogs) {
1.352     www      1695:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1696: 		          &escape($courselogs{$crsid}),
                   1697: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1698: 	    delete $courselogs{$crsid};
                   1699:         } else {
                   1700:             &logthis('Failed to flush log buffer for '.$crsid);
                   1701:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1702:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1703:                         " exceeded maximum size, deleting.</font>");
                   1704:                delete $courselogs{$crsid};
                   1705:             }
1.352     www      1706:         }
                   1707:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1708:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1709: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1710:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1711:         } else {
                   1712:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1713: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1714:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1715:         }
1.191     harris41 1716:     }
1.352     www      1717: #
                   1718: # Write course id database (reverse lookup) to homeserver of courses 
                   1719: # Is used in pickcourse
                   1720: #
1.800     albertel 1721:     foreach my $crsid (keys(%courseidbuffer)) {
                   1722:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1723:     }
                   1724: #
                   1725: # File accesses
                   1726: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1727: #
1.449     matthew  1728:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1729:         if ($entry =~ /___count$/) {
                   1730:             my ($dom,$name);
                   1731:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1732:             if (! defined($dom) || $dom eq '' || 
                   1733:                 ! defined($name) || $name eq '') {
1.620     albertel 1734:                 my $cid = $env{'request.course.id'};
                   1735:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1736:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1737:             }
1.450     matthew  1738:             my $value = $accesshash{$entry};
                   1739:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1740:             my %temphash=($url => $value);
1.449     matthew  1741:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1742:             if ($result eq 'ok') {
                   1743:                 delete $accesshash{$entry};
                   1744:             } elsif ($result eq 'unknown_cmd') {
                   1745:                 # Target server has old code running on it.
1.450     matthew  1746:                 my %temphash=($entry => $value);
1.449     matthew  1747:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1748:                     delete $accesshash{$entry};
                   1749:                 }
                   1750:             }
                   1751:         } else {
1.458     matthew  1752:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1753:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1754:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1755:                 delete $accesshash{$entry};
                   1756:             }
1.185     www      1757:         }
1.191     harris41 1758:     }
1.352     www      1759: #
                   1760: # Roles
                   1761: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1762: #
1.800     albertel 1763:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1764:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1765: 	    split(/\:/,$entry);
                   1766:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1767:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1768:                 $rudom,$runame) eq 'ok') {
                   1769: 	    delete $userrolehash{$entry};
                   1770:         }
                   1771:     }
1.662     raeburn  1772: #
                   1773: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1774: #
                   1775:     my %domrolebuffer = ();
                   1776:     foreach my $entry (keys %domainrolehash) {
                   1777:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1778:         if ($domrolebuffer{$rudom}) {
                   1779:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1780:                       '='.&escape($domainrolehash{$entry});
                   1781:         } else {
                   1782:             $domrolebuffer{$rudom}.=&escape($entry).
                   1783:                       '='.&escape($domainrolehash{$entry});
                   1784:         }
                   1785:         delete $domainrolehash{$entry};
                   1786:     }
                   1787:     foreach my $dom (keys(%domrolebuffer)) {
                   1788:         foreach my $tryserver (keys %libserv) {
                   1789:             if ($hostdom{$tryserver} eq $dom) {
                   1790:                 unless (&reply('domroleput:'.$dom.':'.
                   1791:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1792:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1793:                 }
                   1794:             }
                   1795:         }
                   1796:     }
1.186     www      1797:     $dumpcount++;
1.157     www      1798: }
                   1799: 
                   1800: sub courselog {
                   1801:     my $what=shift;
1.158     www      1802:     $what=time.':'.$what;
1.620     albertel 1803:     unless ($env{'request.course.id'}) { return ''; }
                   1804:     $coursedombuf{$env{'request.course.id'}}=
                   1805:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1806:     $coursenumbuf{$env{'request.course.id'}}=
                   1807:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1808:     $coursehombuf{$env{'request.course.id'}}=
                   1809:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1810:     $coursedescrbuf{$env{'request.course.id'}}=
                   1811:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1812:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1813:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1814:     $courseownerbuf{$env{'request.course.id'}}=
                   1815:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1816:     $coursetypebuf{$env{'request.course.id'}}=
                   1817:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1818:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1819: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1820:     } else {
1.620     albertel 1821: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1822:     }
1.620     albertel 1823:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1824: 	&flushcourselogs();
                   1825:     }
1.158     www      1826: }
                   1827: 
                   1828: sub courseacclog {
                   1829:     my $fnsymb=shift;
1.620     albertel 1830:     unless ($env{'request.course.id'}) { return ''; }
                   1831:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1832:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1833:         $what.=':POST';
1.583     matthew  1834:         # FIXME: Probably ought to escape things....
1.800     albertel 1835: 	foreach my $key (keys(%env)) {
                   1836:             if ($key=~/^form\.(.*)/) {
                   1837: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1838:             }
1.191     harris41 1839:         }
1.583     matthew  1840:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1841:         # FIXME: We should not be depending on a form parameter that someone
                   1842:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1843:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1844:             $what.= ':POST';
                   1845:             # FIXME: Probably ought to escape things....
                   1846:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1847:                                  'crsdiscuss') {
1.620     albertel 1848:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1849:             }
                   1850:         }
1.158     www      1851:     }
                   1852:     &courselog($what);
1.149     www      1853: }
                   1854: 
1.185     www      1855: sub countacc {
                   1856:     my $url=&declutter(shift);
1.458     matthew  1857:     return if (! defined($url) || $url eq '');
1.620     albertel 1858:     unless ($env{'request.course.id'}) { return ''; }
                   1859:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1860:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1861:     $accesshash{$key}++;
1.185     www      1862: }
1.349     www      1863: 
1.361     www      1864: sub linklog {
                   1865:     my ($from,$to)=@_;
                   1866:     $from=&declutter($from);
                   1867:     $to=&declutter($to);
                   1868:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1869:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1870: }
                   1871:   
1.349     www      1872: sub userrolelog {
                   1873:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1874:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1875:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1876:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1877:         ($trole=~/^ta/)) {
1.350     www      1878:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1879:        $userrolehash
                   1880:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1881:                     =$tend.':'.$tstart;
1.662     raeburn  1882:     }
                   1883:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1884:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1885:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1886:         ($trole=~/^sc/)) {
                   1887:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1888:        $domainrolehash
                   1889:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1890:                     = $tend.':'.$tstart;
                   1891:     }
1.351     www      1892: }
                   1893: 
                   1894: sub get_course_adv_roles {
                   1895:     my $cid=shift;
1.620     albertel 1896:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1897:     my %coursehash=&coursedescription($cid);
1.470     www      1898:     my %nothide=();
1.800     albertel 1899:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1900: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      1901:     }
1.351     www      1902:     my %returnhash=();
                   1903:     my %dumphash=
                   1904:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1905:     my $now=time;
1.800     albertel 1906:     foreach my $entry (keys %dumphash) {
                   1907: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      1908:         if (($tstart) && ($tstart<0)) { next; }
                   1909:         if (($tend) && ($tend<$now)) { next; }
                   1910:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1911:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 1912: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1913: 	if ((&privileged($username,$domain)) && 
                   1914: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1915: 	if ($role eq 'cr') { next; }
1.351     www      1916:         my $key=&plaintext($role);
                   1917:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1918:         if ($returnhash{$key}) {
                   1919: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1920:         } else {
                   1921:             $returnhash{$key}=$username.':'.$domain;
                   1922:         }
1.400     www      1923:      }
                   1924:     return %returnhash;
                   1925: }
                   1926: 
                   1927: sub get_my_roles {
                   1928:     my ($uname,$udom)=@_;
1.620     albertel 1929:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1930:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1931:     my %dumphash=
                   1932:             &dump('nohist_userroles',$udom,$uname);
                   1933:     my %returnhash=();
                   1934:     my $now=time;
1.800     albertel 1935:     foreach my $entry (keys(%dumphash)) {
                   1936: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      1937:         if (($tstart) && ($tstart<0)) { next; }
                   1938:         if (($tend) && ($tend<$now)) { next; }
                   1939:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1940:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      1941: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1942:      }
                   1943:     return %returnhash;
1.399     www      1944: }
                   1945: 
                   1946: # ----------------------------------------------------- Frontpage Announcements
                   1947: #
                   1948: #
                   1949: 
                   1950: sub postannounce {
                   1951:     my ($server,$text)=@_;
                   1952:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1953:     unless ($text=~/\w/) { $text=''; }
                   1954:     return &reply('setannounce:'.&escape($text),$server);
                   1955: }
                   1956: 
                   1957: sub getannounce {
1.448     albertel 1958: 
                   1959:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1960: 	my $announcement='';
1.800     albertel 1961: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 1962: 	close($fh);
1.399     www      1963: 	if ($announcement=~/\w/) { 
                   1964: 	    return 
                   1965:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1966:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1967: 	} else {
                   1968: 	    return '';
                   1969: 	}
                   1970:     } else {
                   1971: 	return '';
                   1972:     }
1.351     www      1973: }
1.353     www      1974: 
                   1975: # ---------------------------------------------------------- Course ID routines
                   1976: # Deal with domain's nohist_courseid.db files
                   1977: #
                   1978: 
                   1979: sub courseidput {
                   1980:     my ($domain,$what,$coursehome)=@_;
                   1981:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1982: }
                   1983: 
                   1984: sub courseiddump {
1.791     raeburn  1985:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      1986:     my %returnhash=();
1.355     www      1987:     unless ($domfilter) { $domfilter=''; }
1.353     www      1988:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1989:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1990: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 1991: 	        foreach my $line (
1.506     raeburn  1992:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1993: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  1994:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      1995:                                $tryserver))) {
1.800     albertel 1996: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  1997:                     if (($key) && ($value)) {
1.516     raeburn  1998: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1999:                     }
1.353     www      2000:                 }
                   2001:             }
                   2002:         }
                   2003:     }
                   2004:     return %returnhash;
                   2005: }
                   2006: 
1.658     raeburn  2007: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2008: 
                   2009: sub dcmailput {
1.685     raeburn  2010:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2011:     my $status = &Apache::lonnet::critical(
1.740     www      2012:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2013:        &escape($message),$server);
1.662     raeburn  2014:     return $status;
                   2015: }
                   2016: 
1.658     raeburn  2017: sub dcmaildump {
                   2018:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2019:     my %returnhash=();
                   2020:     if (exists($domain_primary{$dom})) {
                   2021:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2022:                                                          &escape($enddate).':';
                   2023: 	my @esc_senders=map { &escape($_)} @$senders;
                   2024: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2025: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2026:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2027:             if (($key) && ($value)) {
                   2028:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2029:             }
                   2030:         }
                   2031:     }
                   2032:     return %returnhash;
                   2033: }
1.662     raeburn  2034: # ---------------------------------------------------------- Domain roles
                   2035: 
                   2036: sub get_domain_roles {
                   2037:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2038:     if (undef($startdate) || $startdate eq '') {
                   2039:         $startdate = '.';
                   2040:     }
                   2041:     if (undef($enddate) || $enddate eq '') {
                   2042:         $enddate = '.';
                   2043:     }
                   2044:     my $rolelist = join(':',@{$roles});
                   2045:     my %personnel = ();
                   2046:     foreach my $tryserver (keys(%libserv)) {
                   2047:         if ($hostdom{$tryserver} eq $dom) {
                   2048:             %{$personnel{$tryserver}}=();
1.800     albertel 2049:             foreach my $line (
1.662     raeburn  2050:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2051:                    &escape($startdate).':'.&escape($enddate).':'.
                   2052:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2053:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2054:                 if (($key) && ($value)) {
                   2055:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2056:                 }
                   2057:             }
                   2058:         }
                   2059:     }
                   2060:     return %personnel;
                   2061: }
1.658     raeburn  2062: 
1.149     www      2063: # ----------------------------------------------------------- Check out an item
                   2064: 
1.504     albertel 2065: sub get_first_access {
                   2066:     my ($type,$argsymb)=@_;
1.790     albertel 2067:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2068:     if ($argsymb) { $symb=$argsymb; }
                   2069:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2070:     if ($type eq 'map') {
                   2071: 	$res=&symbread($map);
                   2072:     } else {
                   2073: 	$res=$symb;
                   2074:     }
                   2075:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2076:     return $times{"$courseid\0$res"};
1.504     albertel 2077: }
                   2078: 
                   2079: sub set_first_access {
                   2080:     my ($type)=@_;
1.790     albertel 2081:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2082:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2083:     if ($type eq 'map') {
                   2084: 	$res=&symbread($map);
                   2085:     } else {
                   2086: 	$res=$symb;
                   2087:     }
                   2088:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2089:     if (!$firstaccess) {
1.588     albertel 2090: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2091:     }
                   2092:     return 'already_set';
1.504     albertel 2093: }
                   2094: 
1.149     www      2095: sub checkout {
                   2096:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2097:     my $now=time;
                   2098:     my $lonhost=$perlvar{'lonHostID'};
                   2099:     my $infostr=&escape(
1.234     www      2100:                  'CHECKOUTTOKEN&'.
1.149     www      2101:                  $tuname.'&'.
                   2102:                  $tudom.'&'.
                   2103:                  $tcrsid.'&'.
                   2104:                  $symb.'&'.
                   2105: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2106:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2107:     if ($token=~/^error\:/) { 
1.672     albertel 2108:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2109:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2110:                  "</font>");
                   2111:         return ''; 
                   2112:     }
                   2113: 
1.149     www      2114:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2115:     $token=~tr/a-z/A-Z/;
                   2116: 
1.153     www      2117:     my %infohash=('resource.0.outtoken' => $token,
                   2118:                   'resource.0.checkouttime' => $now,
                   2119:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2120: 
                   2121:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2122:        return '';
1.151     www      2123:     } else {
1.672     albertel 2124:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2125:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2126:                  "</font>");
1.149     www      2127:     }    
                   2128: 
                   2129:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2130:                          &escape('Checkout '.$infostr.' - '.
                   2131:                                                  $token)) ne 'ok') {
                   2132: 	return '';
1.151     www      2133:     } else {
1.672     albertel 2134:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2135:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2136:                  "</font>");
1.149     www      2137:     }
1.151     www      2138:     return $token;
1.149     www      2139: }
                   2140: 
                   2141: # ------------------------------------------------------------ Check in an item
                   2142: 
                   2143: sub checkin {
                   2144:     my $token=shift;
1.150     www      2145:     my $now=time;
                   2146:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2147:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2148:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2149:     $dtoken=~s/\W/\_/g;
1.234     www      2150:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2151:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2152: 
1.154     www      2153:     unless (($tuname) && ($tudom)) {
                   2154:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2155:         return '';
                   2156:     }
                   2157:     
                   2158:     unless (&allowed('mgr',$tcrsid)) {
                   2159:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2160:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2161:         return '';
                   2162:     }
                   2163: 
1.153     www      2164:     my %infohash=('resource.0.intoken' => $token,
                   2165:                   'resource.0.checkintime' => $now,
                   2166:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2167: 
                   2168:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2169:        return '';
                   2170:     }    
                   2171: 
                   2172:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2173:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2174: 	return '';
                   2175:     }
                   2176: 
                   2177:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2178: }
                   2179: 
                   2180: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2181: 
                   2182: sub expirespread {
                   2183:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2184:     my $cid=$env{'request.course.id'}; 
1.110     www      2185:     if ($cid) {
                   2186:        my $now=time;
                   2187:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2188:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2189:                             $env{'course.'.$cid.'.num'}.
1.110     www      2190: 	        	    ':nohist_expirationdates:'.
                   2191:                             &escape($key).'='.$now,
1.620     albertel 2192:                             $env{'course.'.$cid.'.home'})
1.110     www      2193:     }
                   2194:     return 'ok';
1.14      www      2195: }
                   2196: 
1.109     www      2197: # ----------------------------------------------------- Devalidate Spreadsheets
                   2198: 
                   2199: sub devalidate {
1.325     www      2200:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2201:     my $cid=$env{'request.course.id'}; 
1.109     www      2202:     if ($cid) {
1.391     matthew  2203:         # delete the stored spreadsheets for
                   2204:         # - the student level sheet of this user in course's homespace
                   2205:         # - the assessment level sheet for this resource 
                   2206:         #   for this user in user's homespace
1.553     albertel 2207: 	# - current conditional state info
1.325     www      2208: 	my $key=$uname.':'.$udom.':';
1.109     www      2209:         my $status=
1.299     matthew  2210: 	    &del('nohist_calculatedsheets',
1.391     matthew  2211: 		 [$key.'studentcalc:'],
1.620     albertel 2212: 		 $env{'course.'.$cid.'.domain'},
                   2213: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2214: 		.' '.
                   2215: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2216: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2217:         unless ($status eq 'ok ok') {
                   2218:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2219:                     $uname.' at '.$udom.' for '.
1.109     www      2220: 		    $symb.': '.$status);
1.133     albertel 2221:         }
1.553     albertel 2222: 	&delenv('user.state.'.$cid);
1.109     www      2223:     }
                   2224: }
                   2225: 
1.265     albertel 2226: sub get_scalar {
                   2227:     my ($string,$end) = @_;
                   2228:     my $value;
                   2229:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2230: 	$value = $1;
                   2231:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2232: 	$value = $1;
                   2233:     }
                   2234:     return &unescape($value);
                   2235: }
                   2236: 
                   2237: sub array2str {
                   2238:   my (@array) = @_;
                   2239:   my $result=&arrayref2str(\@array);
                   2240:   $result=~s/^__ARRAY_REF__//;
                   2241:   $result=~s/__END_ARRAY_REF__$//;
                   2242:   return $result;
                   2243: }
                   2244: 
1.204     albertel 2245: sub arrayref2str {
                   2246:   my ($arrayref) = @_;
1.265     albertel 2247:   my $result='__ARRAY_REF__';
1.204     albertel 2248:   foreach my $elem (@$arrayref) {
1.265     albertel 2249:     if(ref($elem) eq 'ARRAY') {
                   2250:       $result.=&arrayref2str($elem).'&';
                   2251:     } elsif(ref($elem) eq 'HASH') {
                   2252:       $result.=&hashref2str($elem).'&';
                   2253:     } elsif(ref($elem)) {
                   2254:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2255:     } else {
                   2256:       $result.=&escape($elem).'&';
                   2257:     }
                   2258:   }
                   2259:   $result=~s/\&$//;
1.265     albertel 2260:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2261:   return $result;
                   2262: }
                   2263: 
1.168     albertel 2264: sub hash2str {
1.204     albertel 2265:   my (%hash) = @_;
                   2266:   my $result=&hashref2str(\%hash);
1.265     albertel 2267:   $result=~s/^__HASH_REF__//;
                   2268:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2269:   return $result;
                   2270: }
                   2271: 
                   2272: sub hashref2str {
                   2273:   my ($hashref)=@_;
1.265     albertel 2274:   my $result='__HASH_REF__';
1.800     albertel 2275:   foreach my $key (sort(keys(%$hashref))) {
                   2276:     if (ref($key) eq 'ARRAY') {
                   2277:       $result.=&arrayref2str($key).'=';
                   2278:     } elsif (ref($key) eq 'HASH') {
                   2279:       $result.=&hashref2str($key).'=';
                   2280:     } elsif (ref($key)) {
1.265     albertel 2281:       $result.='=';
1.800     albertel 2282:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2283:     } else {
1.800     albertel 2284: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2285:     }
                   2286: 
1.800     albertel 2287:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2288:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2289:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2290:       $result.=&hashref2str($hashref->{$key}).'&';
                   2291:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2292:        $result.='&';
1.800     albertel 2293:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2294:     } else {
1.800     albertel 2295:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2296:     }
                   2297:   }
1.168     albertel 2298:   $result=~s/\&$//;
1.265     albertel 2299:   $result .= '__END_HASH_REF__';
1.168     albertel 2300:   return $result;
                   2301: }
                   2302: 
                   2303: sub str2hash {
1.265     albertel 2304:     my ($string)=@_;
                   2305:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2306:     return %$hash;
                   2307: }
                   2308: 
                   2309: sub str2hashref {
1.168     albertel 2310:   my ($string) = @_;
1.265     albertel 2311: 
                   2312:   my %hash;
                   2313: 
                   2314:   if($string !~ /^__HASH_REF__/) {
                   2315:       if (! ($string eq '' || !defined($string))) {
                   2316: 	  $hash{'error'}='Not hash reference';
                   2317:       }
                   2318:       return (\%hash, $string);
                   2319:   }
                   2320: 
                   2321:   $string =~ s/^__HASH_REF__//;
                   2322: 
                   2323:   while($string !~ /^__END_HASH_REF__/) {
                   2324:       #key
                   2325:       my $key='';
                   2326:       if($string =~ /^__HASH_REF__/) {
                   2327:           ($key, $string)=&str2hashref($string);
                   2328:           if(defined($key->{'error'})) {
                   2329:               $hash{'error'}='Bad data';
                   2330:               return (\%hash, $string);
                   2331:           }
                   2332:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2333:           ($key, $string)=&str2arrayref($string);
                   2334:           if($key->[0] eq 'Array reference error') {
                   2335:               $hash{'error'}='Bad data';
                   2336:               return (\%hash, $string);
                   2337:           }
                   2338:       } else {
                   2339:           $string =~ s/^(.*?)=//;
1.267     albertel 2340: 	  $key=&unescape($1);
1.265     albertel 2341:       }
                   2342:       $string =~ s/^=//;
                   2343: 
                   2344:       #value
                   2345:       my $value='';
                   2346:       if($string =~ /^__HASH_REF__/) {
                   2347:           ($value, $string)=&str2hashref($string);
                   2348:           if(defined($value->{'error'})) {
                   2349:               $hash{'error'}='Bad data';
                   2350:               return (\%hash, $string);
                   2351:           }
                   2352:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2353:           ($value, $string)=&str2arrayref($string);
                   2354:           if($value->[0] eq 'Array reference error') {
                   2355:               $hash{'error'}='Bad data';
                   2356:               return (\%hash, $string);
                   2357:           }
                   2358:       } else {
                   2359: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2360:       }
                   2361:       $string =~ s/^&//;
                   2362: 
                   2363:       $hash{$key}=$value;
1.204     albertel 2364:   }
1.265     albertel 2365: 
                   2366:   $string =~ s/^__END_HASH_REF__//;
                   2367: 
                   2368:   return (\%hash, $string);
1.204     albertel 2369: }
                   2370: 
                   2371: sub str2array {
1.265     albertel 2372:     my ($string)=@_;
                   2373:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2374:     return @$array;
                   2375: }
                   2376: 
                   2377: sub str2arrayref {
1.204     albertel 2378:   my ($string) = @_;
1.265     albertel 2379:   my @array;
                   2380: 
                   2381:   if($string !~ /^__ARRAY_REF__/) {
                   2382:       if (! ($string eq '' || !defined($string))) {
                   2383: 	  $array[0]='Array reference error';
                   2384:       }
                   2385:       return (\@array, $string);
                   2386:   }
                   2387: 
                   2388:   $string =~ s/^__ARRAY_REF__//;
                   2389: 
                   2390:   while($string !~ /^__END_ARRAY_REF__/) {
                   2391:       my $value='';
                   2392:       if($string =~ /^__HASH_REF__/) {
                   2393:           ($value, $string)=&str2hashref($string);
                   2394:           if(defined($value->{'error'})) {
                   2395:               $array[0] ='Array reference error';
                   2396:               return (\@array, $string);
                   2397:           }
                   2398:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2399:           ($value, $string)=&str2arrayref($string);
                   2400:           if($value->[0] eq 'Array reference error') {
                   2401:               $array[0] ='Array reference error';
                   2402:               return (\@array, $string);
                   2403:           }
                   2404:       } else {
                   2405: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2406:       }
                   2407:       $string =~ s/^&//;
                   2408: 
                   2409:       push(@array, $value);
1.191     harris41 2410:   }
1.265     albertel 2411: 
                   2412:   $string =~ s/^__END_ARRAY_REF__//;
                   2413: 
                   2414:   return (\@array, $string);
1.168     albertel 2415: }
                   2416: 
1.167     albertel 2417: # -------------------------------------------------------------------Temp Store
                   2418: 
1.168     albertel 2419: sub tmpreset {
                   2420:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2421:   if (!$symb) {
                   2422:     $symb=&symbread();
1.620     albertel 2423:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2424:   }
                   2425:   $symb=escape($symb);
                   2426: 
1.620     albertel 2427:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2428:   $namespace=~s/\//\_/g;
                   2429:   $namespace=~s/\W//g;
                   2430: 
1.620     albertel 2431:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2432:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2433:   if ($domain eq 'public' && $stuname eq 'public') {
                   2434:       $stuname=$ENV{'REMOTE_ADDR'};
                   2435:   }
1.168     albertel 2436:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2437:   my %hash;
                   2438:   if (tie(%hash,'GDBM_File',
                   2439: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2440: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2441:     foreach my $key (keys %hash) {
1.180     albertel 2442:       if ($key=~ /:$symb/) {
1.168     albertel 2443: 	delete($hash{$key});
                   2444:       }
                   2445:     }
                   2446:   }
                   2447: }
                   2448: 
1.167     albertel 2449: sub tmpstore {
1.168     albertel 2450:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2451: 
                   2452:   if (!$symb) {
                   2453:     $symb=&symbread();
1.620     albertel 2454:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2455:   }
                   2456:   $symb=escape($symb);
                   2457: 
                   2458:   if (!$namespace) {
                   2459:     # I don't think we would ever want to store this for a course.
                   2460:     # it seems this will only be used if we don't have a course.
1.620     albertel 2461:     #$namespace=$env{'request.course.id'};
1.168     albertel 2462:     #if (!$namespace) {
1.620     albertel 2463:       $namespace=$env{'request.state'};
1.168     albertel 2464:     #}
                   2465:   }
                   2466:   $namespace=~s/\//\_/g;
                   2467:   $namespace=~s/\W//g;
1.620     albertel 2468:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2469:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2470:   if ($domain eq 'public' && $stuname eq 'public') {
                   2471:       $stuname=$ENV{'REMOTE_ADDR'};
                   2472:   }
1.168     albertel 2473:   my $now=time;
                   2474:   my %hash;
                   2475:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2476:   if (tie(%hash,'GDBM_File',
                   2477: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2478: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2479:     $hash{"version:$symb"}++;
                   2480:     my $version=$hash{"version:$symb"};
                   2481:     my $allkeys=''; 
                   2482:     foreach my $key (keys(%$storehash)) {
                   2483:       $allkeys.=$key.':';
1.591     albertel 2484:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2485:     }
                   2486:     $hash{"$version:$symb:timestamp"}=$now;
                   2487:     $allkeys.='timestamp';
                   2488:     $hash{"$version:keys:$symb"}=$allkeys;
                   2489:     if (untie(%hash)) {
                   2490:       return 'ok';
                   2491:     } else {
                   2492:       return "error:$!";
                   2493:     }
                   2494:   } else {
                   2495:     return "error:$!";
                   2496:   }
                   2497: }
1.167     albertel 2498: 
1.168     albertel 2499: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2500: 
1.168     albertel 2501: sub tmprestore {
                   2502:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2503: 
1.168     albertel 2504:   if (!$symb) {
                   2505:     $symb=&symbread();
1.620     albertel 2506:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2507:   }
                   2508:   $symb=escape($symb);
                   2509: 
1.620     albertel 2510:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2511: 
1.620     albertel 2512:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2513:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2514:   if ($domain eq 'public' && $stuname eq 'public') {
                   2515:       $stuname=$ENV{'REMOTE_ADDR'};
                   2516:   }
1.168     albertel 2517:   my %returnhash;
                   2518:   $namespace=~s/\//\_/g;
                   2519:   $namespace=~s/\W//g;
                   2520:   my %hash;
                   2521:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2522:   if (tie(%hash,'GDBM_File',
                   2523: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2524: 	  &GDBM_READER(),0640)) {
1.168     albertel 2525:     my $version=$hash{"version:$symb"};
                   2526:     $returnhash{'version'}=$version;
                   2527:     my $scope;
                   2528:     for ($scope=1;$scope<=$version;$scope++) {
                   2529:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2530:       my @keys=split(/:/,$vkeys);
                   2531:       my $key;
                   2532:       $returnhash{"$scope:keys"}=$vkeys;
                   2533:       foreach $key (@keys) {
1.591     albertel 2534: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2535: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2536:       }
                   2537:     }
1.168     albertel 2538:     if (!(untie(%hash))) {
                   2539:       return "error:$!";
                   2540:     }
                   2541:   } else {
                   2542:     return "error:$!";
                   2543:   }
                   2544:   return %returnhash;
1.167     albertel 2545: }
                   2546: 
1.9       www      2547: # ----------------------------------------------------------------------- Store
                   2548: 
                   2549: sub store {
1.124     www      2550:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2551:     my $home='';
                   2552: 
1.168     albertel 2553:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2554: 
1.213     www      2555:     $symb=&symbclean($symb);
1.122     albertel 2556:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2557: 
1.620     albertel 2558:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2559:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2560: 
                   2561:     &devalidate($symb,$stuname,$domain);
1.109     www      2562: 
                   2563:     $symb=escape($symb);
1.187     www      2564:     if (!$namespace) { 
1.620     albertel 2565:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2566:           return ''; 
                   2567:        } 
                   2568:     }
1.620     albertel 2569:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2570: 
                   2571:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2572:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2573: 
1.12      www      2574:     my $namevalue='';
1.800     albertel 2575:     foreach my $key (keys(%$storehash)) {
                   2576:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2577:     }
1.12      www      2578:     $namevalue=~s/\&$//;
1.187     www      2579:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2580:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2581: }
                   2582: 
1.47      www      2583: # -------------------------------------------------------------- Critical Store
                   2584: 
                   2585: sub cstore {
1.124     www      2586:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2587:     my $home='';
                   2588: 
1.168     albertel 2589:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2590: 
1.213     www      2591:     $symb=&symbclean($symb);
1.122     albertel 2592:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2593: 
1.620     albertel 2594:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2595:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2596: 
                   2597:     &devalidate($symb,$stuname,$domain);
1.109     www      2598: 
                   2599:     $symb=escape($symb);
1.187     www      2600:     if (!$namespace) { 
1.620     albertel 2601:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2602:           return ''; 
                   2603:        } 
                   2604:     }
1.620     albertel 2605:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2606: 
                   2607:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2608:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2609: 
1.47      www      2610:     my $namevalue='';
1.800     albertel 2611:     foreach my $key (keys(%$storehash)) {
                   2612:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2613:     }
1.47      www      2614:     $namevalue=~s/\&$//;
1.187     www      2615:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2616:     return critical
                   2617:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2618: }
                   2619: 
1.9       www      2620: # --------------------------------------------------------------------- Restore
                   2621: 
                   2622: sub restore {
1.124     www      2623:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2624:     my $home='';
                   2625: 
1.168     albertel 2626:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2627: 
1.122     albertel 2628:     if (!$symb) {
                   2629:       unless ($symb=escape(&symbread())) { return ''; }
                   2630:     } else {
1.213     www      2631:       $symb=&escape(&symbclean($symb));
1.122     albertel 2632:     }
1.188     www      2633:     if (!$namespace) { 
1.620     albertel 2634:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2635:           return ''; 
                   2636:        } 
                   2637:     }
1.620     albertel 2638:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2639:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2640:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2641:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2642: 
1.12      www      2643:     my %returnhash=();
1.800     albertel 2644:     foreach my $line (split(/\&/,$answer)) {
                   2645: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2646:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2647:     }
1.75      www      2648:     my $version;
                   2649:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2650:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2651:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2652:        }
1.75      www      2653:     }
1.13      www      2654:     return %returnhash;
1.34      www      2655: }
                   2656: 
                   2657: # ---------------------------------------------------------- Course Description
                   2658: 
                   2659: sub coursedescription {
1.731     albertel 2660:     my ($courseid,$args)=@_;
1.34      www      2661:     $courseid=~s/^\///;
1.49      www      2662:     $courseid=~s/\_/\//g;
1.34      www      2663:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2664:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2665:     my $normalid=$cdomain.'_'.$cnum;
                   2666:     # need to always cache even if we get errors otherwise we keep 
                   2667:     # trying and trying and trying to get the course description.
                   2668:     my %envhash=();
                   2669:     my %returnhash=();
1.731     albertel 2670:     
                   2671:     my $expiretime=600;
                   2672:     if ($env{'request.course.id'} eq $normalid) {
                   2673: 	$expiretime=120;
                   2674:     }
                   2675: 
                   2676:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2677:     if (!$args->{'freshen_cache'}
                   2678: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2679: 	foreach my $key (keys(%env)) {
                   2680: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2681: 	    my ($setting) = $1;
                   2682: 	    $returnhash{$setting} = $env{$key};
                   2683: 	}
                   2684: 	return %returnhash;
                   2685:     }
                   2686: 
                   2687:     # get the data agin
                   2688:     if (!$args->{'one_time'}) {
                   2689: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2690:     }
1.34      www      2691:     if ($chome ne 'no_host') {
1.302     albertel 2692:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2693:        if (!exists($returnhash{'con_lost'})) {
                   2694:            $returnhash{'home'}= $chome;
                   2695: 	   $returnhash{'domain'} = $cdomain;
                   2696: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2697:            if (!defined($returnhash{'type'})) {
                   2698:                $returnhash{'type'} = 'Course';
                   2699:            }
1.130     albertel 2700:            while (my ($name,$value) = each %returnhash) {
1.53      www      2701:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2702:            }
1.270     www      2703:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2704:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2705: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2706:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2707:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2708:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2709:        }
                   2710:     }
1.731     albertel 2711:     if (!$args->{'one_time'}) {
                   2712: 	&appenv(%envhash);
                   2713:     }
1.302     albertel 2714:     return %returnhash;
1.461     www      2715: }
                   2716: 
                   2717: # -------------------------------------------------See if a user is privileged
                   2718: 
                   2719: sub privileged {
                   2720:     my ($username,$domain)=@_;
                   2721:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2722: 			&homeserver($username,$domain));
                   2723:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2724:     my $now=time;
                   2725:     if ($rolesdump ne '') {
1.800     albertel 2726:         foreach my $entry (split(/&/,$rolesdump)) {
                   2727: 	    if ($entry!~/^rolesdef_/) {
                   2728: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2729: 		$area=~s/\_\w\w$//;
                   2730: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2731: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2732: 		    my $active=1;
                   2733: 		    if ($tend) {
                   2734: 			if ($tend<$now) { $active=0; }
                   2735: 		    }
                   2736: 		    if ($tstart) {
                   2737: 			if ($tstart>$now) { $active=0; }
                   2738: 		    }
                   2739: 		    if ($active) { return 1; }
                   2740: 		}
                   2741: 	    }
                   2742: 	}
                   2743:     }
                   2744:     return 0;
1.9       www      2745: }
1.1       albertel 2746: 
1.103     harris41 2747: # -------------------------------------------------------- Get user privileges
1.11      www      2748: 
                   2749: sub rolesinit {
                   2750:     my ($domain,$username,$authhost)=@_;
                   2751:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2752:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2753:     my %allroles=();
1.678     raeburn  2754:     my %allgroups=();   
1.11      www      2755:     my $now=time;
1.743     albertel 2756:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2757:     my $group_privs;
1.11      www      2758: 
                   2759:     if ($rolesdump ne '') {
1.800     albertel 2760:         foreach my $entry (split(/&/,$rolesdump)) {
                   2761: 	  if ($entry!~/^rolesdef_/) {
                   2762:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2763: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2764:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2765: 	    if ($role=~/^cr/) { 
1.655     albertel 2766: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2767: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2768: 		    ($tend,$tstart)=split('_',$trest);
                   2769: 		} else {
                   2770: 		    $trole=$role;
                   2771: 		}
1.678     raeburn  2772:             } elsif ($role =~ m|^gr/|) {
                   2773:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2774:                 ($trole,$group_privs) = split(/\//,$trole);
                   2775:                 $group_privs = &unescape($group_privs);
1.587     albertel 2776: 	    } else {
                   2777: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2778: 	    }
1.743     albertel 2779: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2780: 					 $username);
                   2781: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2782:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2783:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2784:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2785: 		my $spec=$trole.'.'.$area;
                   2786: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2787: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2788:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2789:                 } elsif ($trole eq 'gr') {
                   2790:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2791: 		} else {
1.567     raeburn  2792:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2793: 		}
1.12      www      2794:             }
1.662     raeburn  2795:           }
1.191     harris41 2796:         }
1.743     albertel 2797:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2798:         $userroles{'user.adv'}    = $adv;
                   2799: 	$userroles{'user.author'} = $author;
1.620     albertel 2800:         $env{'user.adv'}=$adv;
1.11      www      2801:     }
1.743     albertel 2802:     return \%userroles;  
1.11      www      2803: }
                   2804: 
1.567     raeburn  2805: sub set_arearole {
                   2806:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2807: # log the associated role with the area
                   2808:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2809:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2810: }
                   2811: 
                   2812: sub custom_roleprivs {
                   2813:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2814:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2815:     my $homsvr=homeserver($rauthor,$rdomain);
                   2816:     if ($hostname{$homsvr} ne '') {
                   2817:         my ($rdummy,$roledef)=
                   2818:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2819:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2820:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2821:             if (defined($syspriv)) {
                   2822:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2823:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2824:             }
                   2825:             if ($tdomain ne '') {
                   2826:                 if (defined($dompriv)) {
                   2827:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2828:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2829:                 }
                   2830:                 if (($trest ne '') && (defined($coursepriv))) {
                   2831:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2832:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2833:                 }
                   2834:             }
                   2835:         }
                   2836:     }
                   2837: }
                   2838: 
1.678     raeburn  2839: sub group_roleprivs {
                   2840:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2841:     my $access = 1;
                   2842:     my $now = time;
                   2843:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2844:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2845:     if ($access) {
                   2846:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2847:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2848:     }
                   2849: }
1.567     raeburn  2850: 
                   2851: sub standard_roleprivs {
                   2852:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2853:     if (defined($pr{$trole.':s'})) {
                   2854:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2855:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2856:     }
                   2857:     if ($tdomain ne '') {
                   2858:         if (defined($pr{$trole.':d'})) {
                   2859:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2860:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2861:         }
                   2862:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2863:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2864:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2865:         }
                   2866:     }
                   2867: }
                   2868: 
                   2869: sub set_userprivs {
1.678     raeburn  2870:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2871:     my $author=0;
                   2872:     my $adv=0;
1.678     raeburn  2873:     my %grouproles = ();
                   2874:     if (keys(%{$allgroups}) > 0) {
                   2875:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2876:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2877:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2878:                 $trole = $1;
                   2879:                 $area = $2;
1.681     raeburn  2880:                 $sec = $3;
                   2881:                 $extendedarea = $area.$sec;
                   2882:                 if (exists($$allgroups{$area})) {
                   2883:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2884:                         my $spec = $trole.'.'.$extendedarea;
                   2885:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2886:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2887:                     }
                   2888:                 }
                   2889:             }
                   2890:         }
                   2891:     }
1.800     albertel 2892:     foreach my $group (keys(%grouproles)) {
                   2893:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2894:     }
1.800     albertel 2895:     foreach my $role (keys(%{$allroles})) {
                   2896:         my %thesepriv;
                   2897:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   2898:         foreach my $item (split(/:/,$$allroles{$role})) {
                   2899:             if ($item ne '') {
                   2900:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  2901:                 if ($restrictions eq '') {
                   2902:                     $thesepriv{$privilege}='F';
                   2903:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2904:                     $thesepriv{$privilege}.=$restrictions;
                   2905:                 }
                   2906:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2907:             }
                   2908:         }
                   2909:         my $thesestr='';
1.800     albertel 2910:         foreach my $priv (keys(%thesepriv)) {
                   2911: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   2912: 	}
                   2913:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  2914:     }
                   2915:     return ($author,$adv);
                   2916: }
                   2917: 
1.12      www      2918: # --------------------------------------------------------------- get interface
                   2919: 
                   2920: sub get {
1.131     albertel 2921:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2922:    my $items='';
1.800     albertel 2923:    foreach my $item (@$storearr) {
                   2924:        $items.=&escape($item).'&';
1.191     harris41 2925:    }
1.12      www      2926:    $items=~s/\&$//;
1.620     albertel 2927:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2928:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2929:    my $uhome=&homeserver($uname,$udomain);
                   2930: 
1.133     albertel 2931:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2932:    my @pairs=split(/\&/,$rep);
1.273     albertel 2933:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2934:      return @pairs;
                   2935:    }
1.15      www      2936:    my %returnhash=();
1.42      www      2937:    my $i=0;
1.800     albertel 2938:    foreach my $item (@$storearr) {
                   2939:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      2940:       $i++;
1.191     harris41 2941:    }
1.15      www      2942:    return %returnhash;
1.27      www      2943: }
                   2944: 
                   2945: # --------------------------------------------------------------- del interface
                   2946: 
                   2947: sub del {
1.133     albertel 2948:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2949:    my $items='';
1.800     albertel 2950:    foreach my $item (@$storearr) {
                   2951:        $items.=&escape($item).'&';
1.191     harris41 2952:    }
1.27      www      2953:    $items=~s/\&$//;
1.620     albertel 2954:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2955:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2956:    my $uhome=&homeserver($uname,$udomain);
                   2957: 
                   2958:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2959: }
                   2960: 
                   2961: # -------------------------------------------------------------- dump interface
                   2962: 
                   2963: sub dump {
1.755     albertel 2964:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2965:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2966:     if (!$uname) { $uname=$env{'user.name'}; }
                   2967:     my $uhome=&homeserver($uname,$udomain);
                   2968:     if ($regexp) {
                   2969: 	$regexp=&escape($regexp);
                   2970:     } else {
                   2971: 	$regexp='.';
                   2972:     }
                   2973:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2974:     my @pairs=split(/\&/,$rep);
                   2975:     my %returnhash=();
                   2976:     foreach my $item (@pairs) {
                   2977: 	my ($key,$value)=split(/=/,$item,2);
                   2978: 	$key = &unescape($key);
                   2979: 	next if ($key =~ /^error: 2 /);
                   2980: 	$returnhash{$key}=&thaw_unescape($value);
                   2981:     }
                   2982:     return %returnhash;
1.407     www      2983: }
                   2984: 
1.717     albertel 2985: # --------------------------------------------------------- dumpstore interface
                   2986: 
                   2987: sub dumpstore {
                   2988:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2989:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2990: }
                   2991: 
1.407     www      2992: # -------------------------------------------------------------- keys interface
                   2993: 
                   2994: sub getkeys {
                   2995:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2996:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2997:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2998:    my $uhome=&homeserver($uname,$udomain);
                   2999:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3000:    my @keyarray=();
1.800     albertel 3001:    foreach my $key (split(/\&/,$rep)) {
                   3002:       push(@keyarray,&unescape($key));
1.407     www      3003:    }
                   3004:    return @keyarray;
1.318     matthew  3005: }
                   3006: 
1.319     matthew  3007: # --------------------------------------------------------------- currentdump
                   3008: sub currentdump {
1.328     matthew  3009:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3010:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3011:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3012:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3013:    my $uhome = &homeserver($sname,$sdom);
                   3014:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3015:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3016:    #
1.318     matthew  3017:    my %returnhash=();
1.319     matthew  3018:    #
                   3019:    if ($rep eq "unknown_cmd") { 
                   3020:        # an old lond will not know currentdump
                   3021:        # Do a dump and make it look like a currentdump
1.326     matthew  3022:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3023:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3024:        my %hash = @tmp;
                   3025:        @tmp=();
1.424     matthew  3026:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3027:    } else {
                   3028:        my @pairs=split(/\&/,$rep);
1.800     albertel 3029:        foreach my $pair (@pairs) {
                   3030:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3031:            my ($symb,$param) = split(/:/,$key);
                   3032:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3033:                                                         &thaw_unescape($value);
1.319     matthew  3034:        }
1.191     harris41 3035:    }
1.12      www      3036:    return %returnhash;
1.424     matthew  3037: }
                   3038: 
                   3039: sub convert_dump_to_currentdump{
                   3040:     my %hash = %{shift()};
                   3041:     my %returnhash;
                   3042:     # Code ripped from lond, essentially.  The only difference
                   3043:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3044:     # we might run in to problems with parameter names =~ /^v\./
                   3045:     while (my ($key,$value) = each(%hash)) {
                   3046:         my ($v,$symb,$param) = split(/:/,$key);
                   3047:         next if ($v eq 'version' || $symb eq 'keys');
                   3048:         next if (exists($returnhash{$symb}) &&
                   3049:                  exists($returnhash{$symb}->{$param}) &&
                   3050:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3051:         $returnhash{$symb}->{$param}=$value;
                   3052:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3053:     }
                   3054:     #
                   3055:     # Remove all of the keys in the hashes which keep track of
                   3056:     # the version of the parameter.
                   3057:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3058:         # use a foreach because we are going to delete from the hash.
                   3059:         foreach my $key (keys(%$param_hash)) {
                   3060:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3061:         }
                   3062:     }
                   3063:     return \%returnhash;
1.12      www      3064: }
                   3065: 
1.627     albertel 3066: # ------------------------------------------------------ critical inc interface
                   3067: 
                   3068: sub cinc {
                   3069:     return &inc(@_,'critical');
                   3070: }
                   3071: 
1.449     matthew  3072: # --------------------------------------------------------------- inc interface
                   3073: 
                   3074: sub inc {
1.627     albertel 3075:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3076:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3077:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3078:     my $uhome=&homeserver($uname,$udomain);
                   3079:     my $items='';
                   3080:     if (! ref($store)) {
                   3081:         # got a single value, so use that instead
                   3082:         $items = &escape($store).'=&';
                   3083:     } elsif (ref($store) eq 'SCALAR') {
                   3084:         $items = &escape($$store).'=&';        
                   3085:     } elsif (ref($store) eq 'ARRAY') {
                   3086:         $items = join('=&',map {&escape($_);} @{$store});
                   3087:     } elsif (ref($store) eq 'HASH') {
                   3088:         while (my($key,$value) = each(%{$store})) {
                   3089:             $items.= &escape($key).'='.&escape($value).'&';
                   3090:         }
                   3091:     }
                   3092:     $items=~s/\&$//;
1.627     albertel 3093:     if ($critical) {
                   3094: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3095:     } else {
                   3096: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3097:     }
1.449     matthew  3098: }
                   3099: 
1.12      www      3100: # --------------------------------------------------------------- put interface
                   3101: 
                   3102: sub put {
1.134     albertel 3103:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3104:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3105:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3106:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3107:    my $items='';
1.800     albertel 3108:    foreach my $item (keys(%$storehash)) {
                   3109:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3110:    }
1.12      www      3111:    $items=~s/\&$//;
1.134     albertel 3112:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3113: }
                   3114: 
1.631     albertel 3115: # ------------------------------------------------------------ newput interface
                   3116: 
                   3117: sub newput {
                   3118:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3119:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3120:    if (!$uname) { $uname=$env{'user.name'}; }
                   3121:    my $uhome=&homeserver($uname,$udomain);
                   3122:    my $items='';
                   3123:    foreach my $key (keys(%$storehash)) {
                   3124:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3125:    }
                   3126:    $items=~s/\&$//;
                   3127:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3128: }
                   3129: 
                   3130: # ---------------------------------------------------------  putstore interface
                   3131: 
1.524     raeburn  3132: sub putstore {
1.715     albertel 3133:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3134:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3135:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3136:    my $uhome=&homeserver($uname,$udomain);
                   3137:    my $items='';
1.715     albertel 3138:    foreach my $key (keys(%$storehash)) {
                   3139:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3140:    }
1.715     albertel 3141:    $items=~s/\&$//;
1.716     albertel 3142:    my $esc_symb=&escape($symb);
                   3143:    my $esc_v=&escape($version);
1.715     albertel 3144:    my $reply =
1.716     albertel 3145:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3146: 	      $uhome);
                   3147:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3148:        # gfall back to way things use to be done
1.715     albertel 3149:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3150: 			    $uname);
1.524     raeburn  3151:    }
1.715     albertel 3152:    return $reply;
                   3153: }
                   3154: 
                   3155: sub old_putstore {
1.716     albertel 3156:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3157:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3158:     if (!$uname) { $uname=$env{'user.name'}; }
                   3159:     my $uhome=&homeserver($uname,$udomain);
                   3160:     my %newstorehash;
1.800     albertel 3161:     foreach my $item (keys(%$storehash)) {
                   3162: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3163: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3164:     }
                   3165:     my $items='';
                   3166:     my %allitems = ();
1.800     albertel 3167:     foreach my $item (keys(%newstorehash)) {
                   3168: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3169: 	    my $key = $1.':keys:'.$2;
                   3170: 	    $allitems{$key} .= $3.':';
                   3171: 	}
1.800     albertel 3172: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3173:     }
1.800     albertel 3174:     foreach my $item (keys(%allitems)) {
                   3175: 	$allitems{$item} =~ s/\:$//;
                   3176: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3177:     }
                   3178:     $items=~s/\&$//;
                   3179:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3180: }
                   3181: 
1.47      www      3182: # ------------------------------------------------------ critical put interface
                   3183: 
                   3184: sub cput {
1.134     albertel 3185:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3186:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3187:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3188:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3189:    my $items='';
1.800     albertel 3190:    foreach my $item (keys(%$storehash)) {
                   3191:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3192:    }
1.47      www      3193:    $items=~s/\&$//;
1.134     albertel 3194:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3195: }
                   3196: 
                   3197: # -------------------------------------------------------------- eget interface
                   3198: 
                   3199: sub eget {
1.133     albertel 3200:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3201:    my $items='';
1.800     albertel 3202:    foreach my $item (@$storearr) {
                   3203:        $items.=&escape($item).'&';
1.191     harris41 3204:    }
1.12      www      3205:    $items=~s/\&$//;
1.620     albertel 3206:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3207:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3208:    my $uhome=&homeserver($uname,$udomain);
                   3209:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3210:    my @pairs=split(/\&/,$rep);
                   3211:    my %returnhash=();
1.42      www      3212:    my $i=0;
1.800     albertel 3213:    foreach my $item (@$storearr) {
                   3214:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3215:       $i++;
1.191     harris41 3216:    }
1.12      www      3217:    return %returnhash;
                   3218: }
                   3219: 
1.667     albertel 3220: # ------------------------------------------------------------ tmpput interface
                   3221: sub tmpput {
1.802     raeburn  3222:     my ($storehash,$server,$context)=@_;
1.667     albertel 3223:     my $items='';
1.800     albertel 3224:     foreach my $item (keys(%$storehash)) {
                   3225: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3226:     }
                   3227:     $items=~s/\&$//;
1.802     raeburn  3228:     if (defined($context)) {
                   3229:         $items .= ':'.&escape($context);
                   3230:     }
1.667     albertel 3231:     return &reply("tmpput:$items",$server);
                   3232: }
                   3233: 
                   3234: # ------------------------------------------------------------ tmpget interface
                   3235: sub tmpget {
1.688     albertel 3236:     my ($token,$server)=@_;
                   3237:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3238:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3239:     my %returnhash;
                   3240:     foreach my $item (split(/\&/,$rep)) {
                   3241: 	my ($key,$value)=split(/=/,$item);
                   3242: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3243:     }
                   3244:     return %returnhash;
                   3245: }
                   3246: 
1.688     albertel 3247: # ------------------------------------------------------------ tmpget interface
                   3248: sub tmpdel {
                   3249:     my ($token,$server)=@_;
                   3250:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3251:     return &reply("tmpdel:$token",$server);
                   3252: }
                   3253: 
1.765     albertel 3254: # -------------------------------------------------- portfolio access checking
                   3255: 
                   3256: sub portfolio_access {
1.766     albertel 3257:     my ($requrl) = @_;
1.765     albertel 3258:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3259:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3260:     if ($result eq 'ok') {
1.766     albertel 3261:        return 'F';
1.765     albertel 3262:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3263:        return 'A';
1.765     albertel 3264:     }
1.766     albertel 3265:     return '';
1.765     albertel 3266: }
                   3267: 
                   3268: sub get_portfolio_access {
1.767     albertel 3269:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3270: 
                   3271:     if (!ref($access_hash)) {
                   3272: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3273: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3274: 						   $file_name);
                   3275: 	$access_hash = $access_controls{$file_name};
                   3276:     }
                   3277: 
1.765     albertel 3278:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3279:     my $now = time;
                   3280:     if (ref($access_hash) eq 'HASH') {
                   3281:         foreach my $key (keys(%{$access_hash})) {
                   3282:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3283:             if ($start > $now) {
                   3284:                 next;
                   3285:             }
                   3286:             if ($end && $end<$now) {
                   3287:                 next;
                   3288:             }
                   3289:             if ($scope eq 'public') {
                   3290:                 $public = $key;
                   3291:                 last;
                   3292:             } elsif ($scope eq 'guest') {
                   3293:                 $guest = $key;
                   3294:             } elsif ($scope eq 'domains') {
                   3295:                 push(@domains,$key);
                   3296:             } elsif ($scope eq 'users') {
                   3297:                 push(@users,$key);
                   3298:             } elsif ($scope eq 'course') {
                   3299:                 push(@courses,$key);
                   3300:             } elsif ($scope eq 'group') {
                   3301:                 push(@groups,$key);
                   3302:             }
                   3303:         }
                   3304:         if ($public) {
                   3305:             return 'ok';
                   3306:         }
                   3307:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3308:             if ($guest) {
                   3309:                 return $guest;
                   3310:             }
                   3311:         } else {
                   3312:             if (@domains > 0) {
                   3313:                 foreach my $domkey (@domains) {
                   3314:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3315:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3316:                             return 'ok';
                   3317:                         }
                   3318:                     }
                   3319:                 }
                   3320:             }
                   3321:             if (@users > 0) {
                   3322:                 foreach my $userkey (@users) {
                   3323:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3324:                         return 'ok';
                   3325:                     }
                   3326:                 }
                   3327:             }
                   3328:             my %roleshash;
                   3329:             my @courses_and_groups = @courses;
                   3330:             push(@courses_and_groups,@groups); 
                   3331:             if (@courses_and_groups > 0) {
                   3332:                 my (%allgroups,%allroles); 
                   3333:                 my ($start,$end,$role,$sec,$group);
                   3334:                 foreach my $envkey (%env) {
                   3335:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3336:                         my $cid = $2.'_'.$3; 
                   3337:                         if ($1 eq 'gr') {
                   3338:                             $group = $4;
                   3339:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3340:                         } else {
                   3341:                             if ($4 eq '') {
                   3342:                                 $sec = 'none';
                   3343:                             } else {
                   3344:                                 $sec = $4;
                   3345:                             }
                   3346:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3347:                         }
                   3348:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3349:                         my $cid = $2.'_'.$3;
                   3350:                         if ($4 eq '') {
                   3351:                             $sec = 'none';
                   3352:                         } else {
                   3353:                             $sec = $4;
                   3354:                         }
                   3355:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3356:                     }
                   3357:                 }
                   3358:                 if (keys(%allroles) == 0) {
                   3359:                     return;
                   3360:                 }
                   3361:                 foreach my $key (@courses_and_groups) {
                   3362:                     my %content = %{$$access_hash{$key}};
                   3363:                     my $cnum = $content{'number'};
                   3364:                     my $cdom = $content{'domain'};
                   3365:                     my $cid = $cdom.'_'.$cnum;
                   3366:                     if (!exists($allroles{$cid})) {
                   3367:                         next;
                   3368:                     }    
                   3369:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3370:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3371:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3372:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3373:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3374:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3375:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3376:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3377:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3378:                                         if (grep/^all$/,@sections) {
                   3379:                                             return 'ok';
                   3380:                                         } else {
                   3381:                                             if (grep/^$sec$/,@sections) {
                   3382:                                                 return 'ok';
                   3383:                                             }
                   3384:                                         }
                   3385:                                     }
                   3386:                                 }
                   3387:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3388:                                     if (grep/^none$/,@groups) {
                   3389:                                         return 'ok';
                   3390:                                     }
                   3391:                                 } else {
                   3392:                                     if (grep/^all$/,@groups) {
                   3393:                                         return 'ok';
                   3394:                                     } 
                   3395:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3396:                                         if (grep/^$group$/,@groups) {
                   3397:                                             return 'ok';
                   3398:                                         }
                   3399:                                     }
                   3400:                                 } 
                   3401:                             }
                   3402:                         }
                   3403:                     }
                   3404:                 }
                   3405:             }
                   3406:             if ($guest) {
                   3407:                 return $guest;
                   3408:             }
                   3409:         }
                   3410:     }
                   3411:     return;
                   3412: }
                   3413: 
                   3414: sub course_group_datechecker {
                   3415:     my ($dates,$now,$status) = @_;
                   3416:     my ($start,$end) = split(/\./,$dates);
                   3417:     if (!$start && !$end) {
                   3418:         return 'ok';
                   3419:     }
                   3420:     if (grep/^active$/,@{$status}) {
                   3421:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3422:             return 'ok';
                   3423:         }
                   3424:     }
                   3425:     if (grep/^previous$/,@{$status}) {
                   3426:         if ($end > $now ) {
                   3427:             return 'ok';
                   3428:         }
                   3429:     }
                   3430:     if (grep/^future$/,@{$status}) {
                   3431:         if ($start > $now) {
                   3432:             return 'ok';
                   3433:         }
                   3434:     }
                   3435:     return; 
                   3436: }
                   3437: 
                   3438: sub parse_portfolio_url {
                   3439:     my ($url) = @_;
                   3440: 
                   3441:     my ($type,$udom,$unum,$group,$file_name);
                   3442:     
                   3443:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3444: 	$type = 1;
                   3445:         $udom = $1;
                   3446:         $unum = $2;
                   3447:         $file_name = $3;
                   3448:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3449: 	$type = 2;
                   3450:         $udom = $1;
                   3451:         $unum = $2;
                   3452:         $group = $3;
                   3453:         $file_name = $3.'/'.$4;
                   3454:     }
                   3455:     if (wantarray) {
                   3456: 	return ($type,$udom,$unum,$file_name,$group);
                   3457:     }
                   3458:     return $type;
                   3459: }
                   3460: 
                   3461: sub is_portfolio_url {
                   3462:     my ($url) = @_;
                   3463:     return scalar(&parse_portfolio_url($url));
                   3464: }
                   3465: 
1.798     raeburn  3466: sub is_portfolio_file {
                   3467:     my ($file) = @_;
                   3468:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
                   3469:         return 1;
                   3470:     }
                   3471:     return;
                   3472: }
                   3473: 
                   3474: 
1.341     www      3475: # ---------------------------------------------- Custom access rule evaluation
                   3476: 
                   3477: sub customaccess {
                   3478:     my ($priv,$uri)=@_;
1.620     albertel 3479:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3480:     $urealm=~s/^\W//;
                   3481:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3482:     my $access=0;
1.800     albertel 3483:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3484: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3485:         if ($role) {
                   3486: 	   if ($role ne $urole) { next; }
                   3487:         }
1.800     albertel 3488:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3489:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3490:             if ($tdom) {
                   3491: 		if ($tdom ne $udom) { next; }
                   3492:             }
                   3493:             if ($tcrs) {
                   3494: 		if ($tcrs ne $ucrs) { next; }
                   3495:             }
                   3496:             if ($tsec) {
                   3497: 		if ($tsec ne $usec) { next; }
                   3498:             }
                   3499:             $access=($effect eq 'allow');
                   3500:             last;
1.342     www      3501:         }
1.402     bowersj2 3502: 	if ($realm eq '' && $role eq '') {
                   3503:             $access=($effect eq 'allow');
                   3504: 	}
1.341     www      3505:     }
                   3506:     return $access;
                   3507: }
                   3508: 
1.103     harris41 3509: # ------------------------------------------------- Check for a user privilege
1.12      www      3510: 
                   3511: sub allowed {
1.579     albertel 3512:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3513:     my $ver_orguri=$uri;
1.439     www      3514:     $uri=&deversion($uri);
1.152     www      3515:     my $orguri=$uri;
1.52      www      3516:     $uri=&declutter($uri);
1.545     banghart 3517:     
1.620     albertel 3518:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3519: # Free bre access to adm and meta resources
1.775     albertel 3520:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3521: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3522: 	&& ($priv eq 'bre')) {
1.14      www      3523: 	return 'F';
1.159     www      3524:     }
                   3525: 
1.545     banghart 3526: # Free bre access to user's own portfolio contents
1.714     raeburn  3527:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3528:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3529: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3530:         return 'F';
                   3531:     }
                   3532: 
1.762     raeburn  3533: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3534:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3535:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3536:         if (exists($env{'request.course.id'})) {
                   3537:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3538:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3539:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3540:                 my $courseprivid=$env{'request.course.id'};
                   3541:                 $courseprivid=~s/\_/\//;
                   3542:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3543:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3544:                     return $1; 
1.762     raeburn  3545:                 } else {
                   3546:                     if ($env{'request.course.sec'}) {
                   3547:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3548:                     }
                   3549:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3550:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3551:                         return $2;
                   3552:                     }
1.714     raeburn  3553:                 }
                   3554:             }
                   3555:         }
                   3556:     }
                   3557: 
1.159     www      3558: # Free bre to public access
                   3559: 
                   3560:     if ($priv eq 'bre') {
1.238     www      3561:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3562: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3563:            return 'F'; 
                   3564:         }
1.238     www      3565:         if ($copyright eq 'priv') {
                   3566:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3567: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3568: 		return '';
                   3569:             }
                   3570:         }
                   3571:         if ($copyright eq 'domain') {
                   3572:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3573: 	    unless (($env{'user.domain'} eq $1) ||
                   3574:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3575: 		return '';
                   3576:             }
1.262     matthew  3577:         }
1.620     albertel 3578:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3579:             # Library role, so allow browsing of resources in this domain.
                   3580:             return 'F';
1.238     www      3581:         }
1.341     www      3582:         if ($copyright eq 'custom') {
                   3583: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3584:         }
1.14      www      3585:     }
1.264     matthew  3586:     # Domain coordinator is trying to create a course
1.620     albertel 3587:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3588:         # uri is the requested domain in this case.
                   3589:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3590:         # a role of dc for the domain in question.
1.620     albertel 3591:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3592:     }
1.29      www      3593: 
1.52      www      3594:     my $thisallowed='';
                   3595:     my $statecond=0;
                   3596:     my $courseprivid='';
                   3597: 
                   3598: # Course
                   3599: 
1.620     albertel 3600:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3601:        $thisallowed.=$1;
                   3602:     }
1.29      www      3603: 
1.52      www      3604: # Domain
                   3605: 
1.620     albertel 3606:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3607:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3608:        $thisallowed.=$1;
                   3609:     }
1.52      www      3610: 
                   3611: # Course: uri itself is a course
1.66      www      3612:     my $courseuri=$uri;
                   3613:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3614:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3615: 
1.620     albertel 3616:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3617:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3618:        $thisallowed.=$1;
                   3619:     }
1.29      www      3620: 
1.665     albertel 3621: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3622: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3623:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3624: 	$thisallowed='';
1.671     raeburn  3625:         my ($match)=&is_on_map($uri);
                   3626:         if ($match) {
                   3627:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3628:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3629:                 $thisallowed.=$1;
                   3630:             }
                   3631:         } else {
1.705     albertel 3632:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3633:             if ($refuri) {
                   3634:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3635:                     $thisallowed='F';
1.671     raeburn  3636:                 } else {
                   3637:                     $refuri=&declutter($refuri);
                   3638:                     my ($match) = &is_on_map($refuri);
                   3639:                     if ($match) {
                   3640:                         $thisallowed='F';
                   3641:                     }
1.669     raeburn  3642:                 }
1.671     raeburn  3643:             }
                   3644:         }
1.314     www      3645:     }
1.492     albertel 3646: 
1.766     albertel 3647:     if ($priv eq 'bre'
                   3648: 	&& $thisallowed ne 'F' 
                   3649: 	&& $thisallowed ne '2'
                   3650: 	&& &is_portfolio_url($uri)) {
                   3651: 	$thisallowed = &portfolio_access($uri);
                   3652:     }
                   3653:     
1.52      www      3654: # Full access at system, domain or course-wide level? Exit.
1.29      www      3655: 
                   3656:     if ($thisallowed=~/F/) {
                   3657: 	return 'F';
                   3658:     }
                   3659: 
1.52      www      3660: # If this is generating or modifying users, exit with special codes
1.29      www      3661: 
1.643     www      3662:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3663: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3664: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3665: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3666: 	    unless ($auname) { return $thisallowed; }
                   3667: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3668: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3669: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3670: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3671: 	}
1.52      www      3672: 	return $thisallowed;
                   3673:     }
                   3674: #
1.103     harris41 3675: # Gathered so far: system, domain and course wide privileges
1.52      www      3676: #
                   3677: # Course: See if uri or referer is an individual resource that is part of 
                   3678: # the course
                   3679: 
1.620     albertel 3680:     if ($env{'request.course.id'}) {
1.232     www      3681: 
1.620     albertel 3682:        $courseprivid=$env{'request.course.id'};
                   3683:        if ($env{'request.course.sec'}) {
                   3684:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3685:        }
                   3686:        $courseprivid=~s/\_/\//;
                   3687:        my $checkreferer=1;
1.232     www      3688:        my ($match,$cond)=&is_on_map($uri);
                   3689:        if ($match) {
                   3690:            $statecond=$cond;
1.620     albertel 3691:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3692:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3693:                $thisallowed.=$1;
                   3694:                $checkreferer=0;
                   3695:            }
1.29      www      3696:        }
1.83      www      3697:        
1.148     www      3698:        if ($checkreferer) {
1.620     albertel 3699: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3700:             unless ($refuri) {
1.800     albertel 3701:                 foreach my $key (keys(%env)) {
                   3702: 		    if ($key=~/^httpref\..*\*/) {
                   3703: 			my $pattern=$key;
1.156     www      3704:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3705:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3706:                         $pattern=~s/\//\\\//g;
1.152     www      3707:                         if ($orguri=~/$pattern/) {
1.800     albertel 3708: 			    $refuri=$env{$key};
1.148     www      3709:                         }
                   3710:                     }
1.191     harris41 3711:                 }
1.148     www      3712:             }
1.232     www      3713: 
1.148     www      3714:          if ($refuri) { 
1.152     www      3715: 	  $refuri=&declutter($refuri);
1.232     www      3716:           my ($match,$cond)=&is_on_map($refuri);
                   3717:             if ($match) {
                   3718:               my $refstatecond=$cond;
1.620     albertel 3719:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3720:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3721:                   $thisallowed.=$1;
1.53      www      3722:                   $uri=$refuri;
                   3723:                   $statecond=$refstatecond;
1.52      www      3724:               }
                   3725:           }
1.148     www      3726:         }
1.29      www      3727:        }
1.52      www      3728:    }
1.29      www      3729: 
1.52      www      3730: #
1.103     harris41 3731: # Gathered now: all privileges that could apply, and condition number
1.52      www      3732: # 
                   3733: #
                   3734: # Full or no access?
                   3735: #
1.29      www      3736: 
1.52      www      3737:     if ($thisallowed=~/F/) {
                   3738: 	return 'F';
                   3739:     }
1.29      www      3740: 
1.52      www      3741:     unless ($thisallowed) {
                   3742:         return '';
                   3743:     }
1.29      www      3744: 
1.52      www      3745: # Restrictions exist, deal with them
                   3746: #
                   3747: #   C:according to course preferences
                   3748: #   R:according to resource settings
                   3749: #   L:unless locked
                   3750: #   X:according to user session state
                   3751: #
                   3752: 
                   3753: # Possibly locked functionality, check all courses
1.54      www      3754: # Locks might take effect only after 10 minutes cache expiration for other
                   3755: # courses, and 2 minutes for current course
1.52      www      3756: 
                   3757:     my $envkey;
                   3758:     if ($thisallowed=~/L/) {
1.620     albertel 3759:         foreach $envkey (keys %env) {
1.54      www      3760:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3761:                my $courseid=$2;
                   3762:                my $roleid=$1.'.'.$2;
1.92      www      3763:                $courseid=~s/^\///;
1.54      www      3764:                my $expiretime=600;
1.620     albertel 3765:                if ($env{'request.role'} eq $roleid) {
1.54      www      3766: 		  $expiretime=120;
                   3767:                }
                   3768: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3769:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3770:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3771: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3772:                }
1.620     albertel 3773:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3774:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3775: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3776:                        &log($env{'user.domain'},$env{'user.name'},
                   3777:                             $env{'user.home'},
1.57      www      3778:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3779:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3780:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3781: 		       return '';
                   3782:                    }
                   3783:                }
1.620     albertel 3784:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3785:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3786: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3787:                        &log($env{'user.domain'},$env{'user.name'},
                   3788:                             $env{'user.home'},
1.57      www      3789:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3790:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3791:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3792: 		       return '';
                   3793:                    }
                   3794:                }
                   3795: 	   }
1.29      www      3796:        }
1.52      www      3797:     }
                   3798:    
                   3799: #
                   3800: # Rest of the restrictions depend on selected course
                   3801: #
                   3802: 
1.620     albertel 3803:     unless ($env{'request.course.id'}) {
1.766     albertel 3804: 	if ($thisallowed eq 'A') {
                   3805: 	    return 'A';
                   3806: 	} else {
                   3807: 	    return '1';
                   3808: 	}
1.52      www      3809:     }
1.29      www      3810: 
1.52      www      3811: #
                   3812: # Now user is definitely in a course
                   3813: #
1.53      www      3814: 
                   3815: 
                   3816: # Course preferences
                   3817: 
                   3818:    if ($thisallowed=~/C/) {
1.620     albertel 3819:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3820:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3821:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3822: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3823: 	   if ($priv ne 'pch') { 
                   3824: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3825: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3826: 			$env{'request.course.id'});
                   3827: 	   }
1.237     www      3828:            return '';
                   3829:        }
                   3830: 
1.620     albertel 3831:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3832: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3833: 	   if ($priv ne 'pch') { 
                   3834: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3835: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3836: 			$env{'request.course.id'});
                   3837: 	   }
1.54      www      3838:            return '';
                   3839:        }
1.53      www      3840:    }
                   3841: 
                   3842: # Resource preferences
                   3843: 
                   3844:    if ($thisallowed=~/R/) {
1.620     albertel 3845:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3846:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3847: 	   if ($priv ne 'pch') { 
                   3848: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3849: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3850: 	   }
                   3851: 	   return '';
1.54      www      3852:        }
1.53      www      3853:    }
1.30      www      3854: 
1.246     www      3855: # Restricted by state or randomout?
1.30      www      3856: 
1.52      www      3857:    if ($thisallowed=~/X/) {
1.620     albertel 3858:       if ($env{'acc.randomout'}) {
1.579     albertel 3859: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3860:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3861:             return ''; 
                   3862:          }
1.247     www      3863:       }
                   3864:       if (&condval($statecond)) {
1.52      www      3865: 	 return '2';
                   3866:       } else {
                   3867:          return '';
                   3868:       }
                   3869:    }
1.30      www      3870: 
1.766     albertel 3871:     if ($thisallowed eq 'A') {
                   3872: 	return 'A';
                   3873:     }
1.52      www      3874:    return 'F';
1.232     www      3875: }
                   3876: 
1.710     albertel 3877: sub split_uri_for_cond {
                   3878:     my $uri=&deversion(&declutter(shift));
                   3879:     my @uriparts=split(/\//,$uri);
                   3880:     my $filename=pop(@uriparts);
                   3881:     my $pathname=join('/',@uriparts);
                   3882:     return ($pathname,$filename);
                   3883: }
1.232     www      3884: # --------------------------------------------------- Is a resource on the map?
                   3885: 
                   3886: sub is_on_map {
1.710     albertel 3887:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3888:     #Trying to find the conditional for the file
1.620     albertel 3889:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3890: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3891:     if ($match) {
1.289     bowersj2 3892: 	return (1,$1);
                   3893:     } else {
1.434     www      3894: 	return (0,0);
1.289     bowersj2 3895:     }
1.12      www      3896: }
                   3897: 
1.427     www      3898: # --------------------------------------------------------- Get symb from alias
                   3899: 
                   3900: sub get_symb_from_alias {
                   3901:     my $symb=shift;
                   3902:     my ($map,$resid,$url)=&decode_symb($symb);
                   3903: # Already is a symb
                   3904:     if ($url) { return $symb; }
                   3905: # Must be an alias
                   3906:     my $aliassymb='';
                   3907:     my %bighash;
1.620     albertel 3908:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3909:                             &GDBM_READER(),0640)) {
                   3910:         my $rid=$bighash{'mapalias_'.$symb};
                   3911: 	if ($rid) {
                   3912: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3913: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3914: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3915: 	}
                   3916:         untie %bighash;
                   3917:     }
                   3918:     return $aliassymb;
                   3919: }
                   3920: 
1.12      www      3921: # ----------------------------------------------------------------- Define Role
                   3922: 
                   3923: sub definerole {
                   3924:   if (allowed('mcr','/')) {
                   3925:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 3926:     foreach my $role (split(':',$sysrole)) {
                   3927: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3928:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3929:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3930: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3931:                return "refused:s:$crole&$cqual"; 
                   3932:             }
                   3933:         }
1.191     harris41 3934:     }
1.800     albertel 3935:     foreach my $role (split(':',$domrole)) {
                   3936: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3937:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3938:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3939: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3940:                return "refused:d:$crole&$cqual"; 
                   3941:             }
                   3942:         }
1.191     harris41 3943:     }
1.800     albertel 3944:     foreach my $role (split(':',$courole)) {
                   3945: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3946:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3947:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3948: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3949:                return "refused:c:$crole&$cqual"; 
                   3950:             }
                   3951:         }
1.191     harris41 3952:     }
1.620     albertel 3953:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3954:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3955: 	        "rolesdef_$rolename=".
                   3956:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3957:     return reply($command,$env{'user.home'});
1.12      www      3958:   } else {
                   3959:     return 'refused';
                   3960:   }
1.105     harris41 3961: }
                   3962: 
                   3963: # ---------------- Make a metadata query against the network of library servers
                   3964: 
                   3965: sub metadata_query {
1.244     matthew  3966:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3967:     my %rhash;
1.244     matthew  3968:     my @server_list = (defined($server_array) ? @$server_array
                   3969:                                               : keys(%libserv) );
                   3970:     for my $server (@server_list) {
1.118     harris41 3971: 	unless ($custom or $customshow) {
                   3972: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3973: 	    $rhash{$server}=$reply;
                   3974: 	}
                   3975: 	else {
                   3976: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3977: 			     &escape($custom).':'.&escape($customshow),
                   3978: 			     $server);
                   3979: 	    $rhash{$server}=$reply;
                   3980: 	}
1.112     harris41 3981:     }
1.118     harris41 3982:     return \%rhash;
1.240     www      3983: }
                   3984: 
                   3985: # ----------------------------------------- Send log queries and wait for reply
                   3986: 
                   3987: sub log_query {
                   3988:     my ($uname,$udom,$query,%filters)=@_;
                   3989:     my $uhome=&homeserver($uname,$udom);
                   3990:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3991:     my $uhost=$hostname{$uhome};
1.800     albertel 3992:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      3993:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3994:                        $uhome);
1.479     albertel 3995:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3996:     return get_query_reply($queryid);
                   3997: }
                   3998: 
1.508     raeburn  3999: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4000: 
                   4001: sub fetch_enrollment_query {
1.511     raeburn  4002:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4003:     my $homeserver;
1.547     raeburn  4004:     my $maxtries = 1;
1.508     raeburn  4005:     if ($context eq 'automated') {
                   4006:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4007:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4008:     } else {
                   4009:         $homeserver = &homeserver($cnum,$dom);
                   4010:     }
1.506     raeburn  4011:     my $host=$hostname{$homeserver};
                   4012:     my $cmd = '';
1.800     albertel 4013:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4014:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4015:     }
                   4016:     $cmd =~ s/%%$//;
                   4017:     $cmd = &escape($cmd);
                   4018:     my $query = 'fetchenrollment';
1.620     albertel 4019:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4020:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4021:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4022:         return 'error: '.$queryid;
                   4023:     }
1.506     raeburn  4024:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4025:     my $tries = 1;
                   4026:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4027:         $reply = &get_query_reply($queryid);
                   4028:         $tries ++;
                   4029:     }
1.526     raeburn  4030:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4031:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4032:     } else {
1.515     raeburn  4033:         my @responses = split/:/,$reply;
                   4034:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4035:             foreach my $line (@responses) {
                   4036:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4037:                 $$replyref{$key} = $value;
                   4038:             }
                   4039:         } else {
1.506     raeburn  4040:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4041:             foreach my $line (@responses) {
                   4042:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4043:                 $$replyref{$key} = $value;
                   4044:                 if ($value > 0) {
1.800     albertel 4045:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4046:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4047:                         my $destname = $pathname.'/'.$filename;
                   4048:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4049:                         if ($xml_classlist =~ /^error/) {
                   4050:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4051:                         } else {
1.506     raeburn  4052:                             if ( open(FILE,">$destname") ) {
                   4053:                                 print FILE &unescape($xml_classlist);
                   4054:                                 close(FILE);
1.526     raeburn  4055:                             } else {
                   4056:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4057:                             }
                   4058:                         }
                   4059:                     }
                   4060:                 }
                   4061:             }
                   4062:         }
                   4063:         return 'ok';
                   4064:     }
                   4065:     return 'error';
                   4066: }
                   4067: 
1.242     www      4068: sub get_query_reply {
                   4069:     my $queryid=shift;
1.240     www      4070:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4071:     my $reply='';
                   4072:     for (1..100) {
                   4073: 	sleep 2;
                   4074:         if (-e $replyfile.'.end') {
1.448     albertel 4075: 	    if (open(my $fh,$replyfile)) {
1.240     www      4076:                $reply.=<$fh>;
1.448     albertel 4077:                close($fh);
1.240     www      4078: 	   } else { return 'error: reply_file_error'; }
1.242     www      4079:            return &unescape($reply);
                   4080: 	}
1.240     www      4081:     }
1.242     www      4082:     return 'timeout:'.$queryid;
1.240     www      4083: }
                   4084: 
                   4085: sub courselog_query {
1.241     www      4086: #
                   4087: # possible filters:
                   4088: # url: url or symb
                   4089: # username
                   4090: # domain
                   4091: # action: view, submit, grade
                   4092: # start: timestamp
                   4093: # end: timestamp
                   4094: #
1.240     www      4095:     my (%filters)=@_;
1.620     albertel 4096:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4097:     if ($filters{'url'}) {
                   4098: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4099:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4100:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4101:     }
1.620     albertel 4102:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4103:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4104:     return &log_query($cname,$cdom,'courselog',%filters);
                   4105: }
                   4106: 
                   4107: sub userlog_query {
                   4108:     my ($uname,$udom,%filters)=@_;
                   4109:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4110: }
                   4111: 
1.506     raeburn  4112: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4113: 
                   4114: sub auto_run {
1.508     raeburn  4115:     my ($cnum,$cdom) = @_;
                   4116:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4117:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4118:     return $response;
                   4119: }
1.776     albertel 4120: 
1.506     raeburn  4121: sub auto_get_sections {
1.508     raeburn  4122:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4123:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4124:     my @secs = ();
1.511     raeburn  4125:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4126:     unless ($response eq 'refused') {
                   4127:         @secs = split/:/,$response;
                   4128:     }
                   4129:     return @secs;
                   4130: }
1.776     albertel 4131: 
1.506     raeburn  4132: sub auto_new_course {
1.508     raeburn  4133:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4134:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4135:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4136:     return $response;
                   4137: }
1.776     albertel 4138: 
1.506     raeburn  4139: sub auto_validate_courseID {
1.508     raeburn  4140:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4141:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4142:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4143:     return $response;
                   4144: }
1.776     albertel 4145: 
1.506     raeburn  4146: sub auto_create_password {
1.508     raeburn  4147:     my ($cnum,$cdom,$authparam) = @_;
                   4148:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4149:     my $create_passwd = 0;
                   4150:     my $authchk = '';
1.511     raeburn  4151:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4152:     if ($response eq 'refused') {
                   4153:         $authchk = 'refused';
                   4154:     } else {
                   4155:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4156:     }
                   4157:     return ($authparam,$create_passwd,$authchk);
                   4158: }
                   4159: 
1.706     raeburn  4160: sub auto_photo_permission {
                   4161:     my ($cnum,$cdom,$students) = @_;
                   4162:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4163:     my ($outcome,$perm_reqd,$conditions) = 
                   4164: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4165:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4166: 	return (undef,undef);
                   4167:     }
1.706     raeburn  4168:     return ($outcome,$perm_reqd,$conditions);
                   4169: }
                   4170: 
                   4171: sub auto_checkphotos {
                   4172:     my ($uname,$udom,$pid) = @_;
                   4173:     my $homeserver = &homeserver($uname,$udom);
                   4174:     my ($result,$resulttype);
                   4175:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4176: 				   &escape($uname).':'.&escape($pid),
                   4177: 				   $homeserver));
1.709     albertel 4178:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4179: 	return (undef,undef);
                   4180:     }
1.706     raeburn  4181:     if ($outcome) {
                   4182:         ($result,$resulttype) = split(/:/,$outcome);
                   4183:     } 
                   4184:     return ($result,$resulttype);
                   4185: }
                   4186: 
                   4187: sub auto_photochoice {
                   4188:     my ($cnum,$cdom) = @_;
                   4189:     my $homeserver = &homeserver($cnum,$cdom);
                   4190:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4191: 						       &escape($cdom),
                   4192: 						       $homeserver)));
1.709     albertel 4193:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4194: 	return (undef,undef);
                   4195:     }
1.706     raeburn  4196:     return ($update,$comment);
                   4197: }
                   4198: 
                   4199: sub auto_photoupdate {
                   4200:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4201:     my $homeserver = &homeserver($cnum,$dom);
                   4202:     my $host=$hostname{$homeserver};
                   4203:     my $cmd = '';
                   4204:     my $maxtries = 1;
1.800     albertel 4205:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4206:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4207:     }
                   4208:     $cmd =~ s/%%$//;
                   4209:     $cmd = &escape($cmd);
                   4210:     my $query = 'institutionalphotos';
                   4211:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4212:     unless ($queryid=~/^\Q$host\E\_/) {
                   4213:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4214:         return 'error: '.$queryid;
                   4215:     }
                   4216:     my $reply = &get_query_reply($queryid);
                   4217:     my $tries = 1;
                   4218:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4219:         $reply = &get_query_reply($queryid);
                   4220:         $tries ++;
                   4221:     }
                   4222:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4223:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4224:     } else {
                   4225:         my @responses = split(/:/,$reply);
                   4226:         my $outcome = shift(@responses); 
                   4227:         foreach my $item (@responses) {
                   4228:             my ($key,$value) = split(/=/,$item);
                   4229:             $$photo{$key} = $value;
                   4230:         }
                   4231:         return $outcome;
                   4232:     }
                   4233:     return 'error';
                   4234: }
                   4235: 
1.521     raeburn  4236: sub auto_instcode_format {
1.793     albertel 4237:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4238: 	$cat_order) = @_;
1.521     raeburn  4239:     my $courses = '';
1.772     raeburn  4240:     my @homeservers;
1.521     raeburn  4241:     if ($caller eq 'global') {
1.793     albertel 4242:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4243:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4244:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4245:                     push(@homeservers,$tryserver);
                   4246:                 }
1.584     raeburn  4247:             }
                   4248:         }
1.521     raeburn  4249:     } else {
1.772     raeburn  4250:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4251:     }
1.793     albertel 4252:     foreach my $code (keys(%{$instcodes})) {
                   4253:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4254:     }
                   4255:     chop($courses);
1.772     raeburn  4256:     my $ok_response = 0;
                   4257:     my $response;
                   4258:     while (@homeservers > 0 && $ok_response == 0) {
                   4259:         my $server = shift(@homeservers); 
                   4260:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4261:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4262:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4263: 		split/:/,$response;
1.772     raeburn  4264:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4265:             push(@{$codetitles},&str2array($codetitles_str));
                   4266:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4267:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4268:             $ok_response = 1;
                   4269:         }
                   4270:     }
                   4271:     if ($ok_response) {
1.521     raeburn  4272:         return 'ok';
1.772     raeburn  4273:     } else {
                   4274:         return $response;
1.521     raeburn  4275:     }
                   4276: }
                   4277: 
1.792     raeburn  4278: sub auto_instcode_defaults {
                   4279:     my ($domain,$returnhash,$code_order) = @_;
                   4280:     my @homeservers;
1.793     albertel 4281:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4282:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4283:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4284:                 push(@homeservers,$tryserver);
                   4285:             }
                   4286:         }
                   4287:     }
                   4288:     my $ok_response = 0;
                   4289:     my $response;
                   4290:     while (@homeservers > 0 && $ok_response == 0) {
                   4291:         my $server = shift(@homeservers);
                   4292:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4293:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4294:             foreach my $pair (split(/\&/,$response)) {
                   4295:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4296:                 if ($name eq 'code_order') {
1.796     raeburn  4297:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4298:                 } else {
1.796     raeburn  4299:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4300:                 }
                   4301:             }
1.804     raeburn  4302:             $ok_response = 1;
1.792     raeburn  4303:         }
                   4304:     }
                   4305:     if ($ok_response) {
                   4306:         return 'ok';
                   4307:     } else {
                   4308:         return $response;
                   4309:     }
                   4310: } 
                   4311: 
1.777     albertel 4312: sub auto_validate_class_sec {
1.773     raeburn  4313:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4314:     my $homeserver = &homeserver($cnum,$cdom);
                   4315:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4316:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4317:     return $response;
                   4318: }
                   4319: 
1.679     raeburn  4320: # ------------------------------------------------------- Course Group routines
                   4321: 
                   4322: sub get_coursegroups {
1.683     raeburn  4323:     my ($cdom,$cnum,$group) = @_;
                   4324:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4325: }
                   4326: 
1.805   ! raeburn  4327: sub get_deleted_groups {
        !          4328:     my ($cdom,$cnum,$group) = @_;
        !          4329:     return(&dump('deleted_groups',$cdom,$cnum,$group));
        !          4330: }
        !          4331: 
1.679     raeburn  4332: sub modify_coursegroup {
                   4333:     my ($cdom,$cnum,$groupsettings) = @_;
                   4334:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4335: }
                   4336: 
1.805   ! raeburn  4337: sub delete_coursegroup {
        !          4338:     my ($cdom,$cnum,$group) = @_;
        !          4339:     my %curr_group = &get_coursegroups($cdom,$cnum,$group);
        !          4340:     if (my $tmp = &error(%curr_group)) {
        !          4341:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
        !          4342:         return ('read error',$tmp);
        !          4343:     } else {
        !          4344:         my %savedsettings = %curr_group; 
        !          4345:         my $result = &put('deleted_groups',\%savedsettings,$cdom,$cnum);
        !          4346:         my $deloutcome;
        !          4347:         if ($result eq 'ok') {
        !          4348:             $deloutcome = &del('coursegroups',[$group],$cdom,$cnum);
        !          4349:         } else {
        !          4350:             return ('write error',$result);
        !          4351:         }
        !          4352:         if ($deloutcome eq 'ok') {
        !          4353:             return 'ok';
        !          4354:         } else {
        !          4355:             return ('delete error',$deloutcome);
        !          4356:         }
        !          4357:     }
        !          4358: }
        !          4359: 
1.679     raeburn  4360: sub modify_group_roles {
                   4361:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4362:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4363:     my $role = 'gr/'.&escape($userprivs);
                   4364:     my ($uname,$udom) = split(/:/,$user);
                   4365:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4366:     if ($result eq 'ok') {
                   4367:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4368:     }
1.679     raeburn  4369:     return $result;
                   4370: }
                   4371: 
                   4372: sub modify_coursegroup_membership {
                   4373:     my ($cdom,$cnum,$membership) = @_;
                   4374:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4375:     return $result;
                   4376: }
                   4377: 
1.682     raeburn  4378: sub get_active_groups {
                   4379:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4380:     my $now = time;
                   4381:     my %groups = ();
                   4382:     foreach my $key (keys(%env)) {
                   4383:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4384:             my ($start,$end) = split(/\./,$env{$key});
                   4385:             if (($end!=0) && ($end<$now)) { next; }
                   4386:             if (($start!=0) && ($start>$now)) { next; }
                   4387:             if ($1 eq $cdom && $2 eq $cnum) {
                   4388:                 $groups{$3} = $env{$key} ;
                   4389:             }
                   4390:         }
                   4391:     }
                   4392:     return %groups;
                   4393: }
                   4394: 
1.683     raeburn  4395: sub get_group_membership {
                   4396:     my ($cdom,$cnum,$group) = @_;
                   4397:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4398: }
                   4399: 
                   4400: sub get_users_groups {
                   4401:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4402:     my @usersgroups;
1.683     raeburn  4403:     my $cachetime=1800;
                   4404:     $courseid=~s/\_/\//g;
                   4405:     $courseid=~s/^(\w)/\/$1/;
                   4406: 
                   4407:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4408:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4409:     if (defined($cached)) {
1.734     albertel 4410:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4411:     } else {  
                   4412:         $grouplist = '';
                   4413:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4414:         my ($tmp) = keys(%roleshash);
                   4415:         if ($tmp=~/^error:/) {
                   4416:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4417:         } else {
                   4418:             my $access_end = $env{'course.'.$courseid.
                   4419:                                   '.default_enrollment_end_date'};
                   4420:             my $now = time;
1.734     albertel 4421:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4422:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4423:                     my $group = $1;
                   4424:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4425:                         my $start = $2;
                   4426:                         my $end = $1;
                   4427:                         if ($start == -1) { next; } # deleted from group
                   4428:                         if (($start!=0) && ($start>$now)) { next; }
                   4429:                         if (($end!=0) && ($end<$now)) {
                   4430:                             if ($access_end && $access_end < $now) {
                   4431:                                 if ($access_end - $end < 86400) {
                   4432:                                     push(@usersgroups,$group);
                   4433:                                 }
                   4434:                             }
                   4435:                             next;
                   4436:                         }
                   4437:                         push(@usersgroups,$group);
                   4438:                     }
1.683     raeburn  4439:                 }
                   4440:             }
1.733     raeburn  4441:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4442:             $grouplist = join(':',@usersgroups);
                   4443:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4444:         }
                   4445:     }
1.733     raeburn  4446:     return @usersgroups;
1.683     raeburn  4447: }
                   4448: 
                   4449: sub devalidate_getgroups_cache {
                   4450:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4451:     my $courseid = $cdom.'_'.$cnum;
                   4452:     $courseid=~s/\_/\//g;
                   4453:     $courseid=~s/^(\w)/\/$1/;
                   4454:     my $hashid="$udom:$uname:$courseid";
                   4455:     &devalidate_cache_new('getgroups',$hashid);
                   4456: }
                   4457: 
1.12      www      4458: # ------------------------------------------------------------------ Plain Text
                   4459: 
                   4460: sub plaintext {
1.742     raeburn  4461:     my ($short,$type,$cid) = @_;
1.758     albertel 4462:     if ($short =~ /^cr/) {
                   4463: 	return (split('/',$short))[-1];
                   4464:     }
1.742     raeburn  4465:     if (!defined($cid)) {
                   4466:         $cid = $env{'request.course.id'};
                   4467:     }
                   4468:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4469:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4470:                                           '.plaintext'});
                   4471:     }
                   4472:     my %rolenames = (
                   4473:                       Course => 'std',
                   4474:                       Group => 'alt1',
                   4475:                     );
                   4476:     if (defined($type) && 
                   4477:          defined($rolenames{$type}) && 
                   4478:          defined($prp{$short}{$rolenames{$type}})) {
                   4479:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4480:     } else {
                   4481:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4482:     }
1.12      www      4483: }
                   4484: 
                   4485: # ----------------------------------------------------------------- Assign Role
                   4486: 
                   4487: sub assignrole {
1.357     www      4488:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4489:     my $mrole;
                   4490:     if ($role =~ /^cr\//) {
1.393     www      4491:         my $cwosec=$url;
                   4492:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4493: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4494:            &logthis('Refused custom assignrole: '.
                   4495:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4496: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4497:            return 'refused'; 
                   4498:         }
1.21      www      4499:         $mrole='cr';
1.678     raeburn  4500:     } elsif ($role =~ /^gr\//) {
                   4501:         my $cwogrp=$url;
                   4502:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4503:         unless (&allowed('mdg',$cwogrp)) {
                   4504:             &logthis('Refused group assignrole: '.
                   4505:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4506:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4507:             return 'refused';
                   4508:         }
                   4509:         $mrole='gr';
1.21      www      4510:     } else {
1.82      www      4511:         my $cwosec=$url;
1.83      www      4512:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4513:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4514:            &logthis('Refused assignrole: '.
                   4515:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4516: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4517:            return 'refused'; 
                   4518:         }
1.21      www      4519:         $mrole=$role;
                   4520:     }
1.620     albertel 4521:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4522:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4523:     if ($end) { $command.='_'.$end; }
1.21      www      4524:     if ($start) {
                   4525: 	if ($end) { 
1.81      www      4526:            $command.='_'.$start; 
1.21      www      4527:         } else {
1.81      www      4528:            $command.='_0_'.$start;
1.21      www      4529:         }
                   4530:     }
1.739     raeburn  4531:     my $origstart = $start;
                   4532:     my $origend = $end;
1.357     www      4533: # actually delete
                   4534:     if ($deleteflag) {
1.373     www      4535: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4536: # modify command to delete the role
1.620     albertel 4537:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4538:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4539: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4540: # set start and finish to negative values for userrolelog
                   4541:            $start=-1;
                   4542:            $end=-1;
                   4543:         }
                   4544:     }
                   4545: # send command
1.349     www      4546:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4547: # log new user role if status is ok
1.349     www      4548:     if ($answer eq 'ok') {
1.663     raeburn  4549: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4550: # for course roles, perform group memberships changes triggered by role change.
                   4551:         unless ($role =~ /^gr/) {
                   4552:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4553:                                              $origstart);
                   4554:         }
1.349     www      4555:     }
                   4556:     return $answer;
1.169     harris41 4557: }
                   4558: 
                   4559: # -------------------------------------------------- Modify user authentication
1.197     www      4560: # Overrides without validation
                   4561: 
1.169     harris41 4562: sub modifyuserauth {
                   4563:     my ($udom,$uname,$umode,$upass)=@_;
                   4564:     my $uhome=&homeserver($uname,$udom);
1.197     www      4565:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4566:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4567:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4568:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4569:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4570: 		     &escape($upass),$uhome);
1.620     albertel 4571:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4572:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4573:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4574:     &log($udom,,$uname,$uhome,
1.620     albertel 4575:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4576:                                      $env{'user.name'}.', '.$umode.
1.197     www      4577:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4578:     unless ($reply eq 'ok') {
1.197     www      4579:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4580: 	return 'error: '.$reply;
                   4581:     }   
1.170     harris41 4582:     return 'ok';
1.80      www      4583: }
                   4584: 
1.81      www      4585: # --------------------------------------------------------------- Modify a user
1.80      www      4586: 
1.81      www      4587: sub modifyuser {
1.206     matthew  4588:     my ($udom,    $uname, $uid,
                   4589:         $umode,   $upass, $first,
                   4590:         $middle,  $last,  $gene,
1.387     www      4591:         $forceid, $desiredhome, $email)=@_;
1.198     www      4592:     $udom=~s/\W//g;
                   4593:     $uname=~s/\W//g;
1.81      www      4594:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4595:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4596: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4597:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4598:                                      ' desiredhome not specified'). 
1.620     albertel 4599:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4600:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4601:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4602: # ----------------------------------------------------------------- Create User
1.406     albertel 4603:     if (($uhome eq 'no_host') && 
                   4604: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4605:         my $unhome='';
1.209     matthew  4606:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4607:             $unhome = $desiredhome;
1.620     albertel 4608: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4609: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4610:         } else { # load balancing routine for determining $unhome
1.80      www      4611:             my $tryserver;
1.81      www      4612:             my $loadm=10000000;
1.80      www      4613:             foreach $tryserver (keys %libserv) {
                   4614: 	       if ($hostdom{$tryserver} eq $udom) {
                   4615:                   my $answer=reply('load',$tryserver);
                   4616:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4617: 		      $loadm=$answer;
                   4618:                       $unhome=$tryserver;
                   4619:                   }
                   4620: 	       }
                   4621: 	    }
                   4622:         }
                   4623:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4624: 	    return 'error: unable to find a home server for '.$uname.
                   4625:                    ' in domain '.$udom;
1.80      www      4626:         }
                   4627:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4628:                          &escape($upass),$unhome);
                   4629: 	unless ($reply eq 'ok') {
                   4630:             return 'error: '.$reply;
                   4631:         }   
1.230     stredwic 4632:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4633:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4634: 	    return 'error: unable verify users home machine.';
1.80      www      4635:         }
1.209     matthew  4636:     }   # End of creation of new user
1.80      www      4637: # ---------------------------------------------------------------------- Add ID
                   4638:     if ($uid) {
                   4639:        $uid=~tr/A-Z/a-z/;
                   4640:        my %uidhash=&idrget($udom,$uname);
1.196     www      4641:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4642:          && (!$forceid)) {
1.80      www      4643: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4644: 	      return 'error: user id "'.$uid.'" does not match '.
                   4645:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4646:           }
                   4647:        } else {
                   4648: 	  &idput($udom,($uname => $uid));
                   4649:        }
                   4650:     }
                   4651: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4652:     my @tmp=&get('environment',
1.134     albertel 4653: 		   ['firstname','middlename','lastname','generation'],
                   4654: 		   $udom,$uname);
1.313     matthew  4655:     my %names;
                   4656:     if ($tmp[0] =~ m/^error:.*/) { 
                   4657:         %names=(); 
                   4658:     } else {
                   4659:         %names = @tmp;
                   4660:     }
1.388     www      4661: #
                   4662: # Make sure to not trash student environment if instructor does not bother
                   4663: # to supply name and email information
                   4664: #
                   4665:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4666:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4667:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4668:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4669:     if ($email) {
                   4670:        $email=~s/[^\w\@\.\-\,]//gs;
                   4671:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4672: 			   $names{'critnotification'} = $email;
                   4673: 			   $names{'permanentemail'} = $email; }
                   4674:     }
1.134     albertel 4675:     my $reply = &put('environment', \%names, $udom,$uname);
                   4676:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4677:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4678:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4679:              $umode.', '.$first.', '.$middle.', '.
                   4680: 	     $last.', '.$gene.' by '.
1.620     albertel 4681:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4682:     return 'ok';
1.80      www      4683: }
                   4684: 
1.81      www      4685: # -------------------------------------------------------------- Modify student
1.80      www      4686: 
1.81      www      4687: sub modifystudent {
                   4688:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4689:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4690:     if (!$cid) {
1.620     albertel 4691: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4692: 	    return 'not_in_class';
                   4693: 	}
1.80      www      4694:     }
                   4695: # --------------------------------------------------------------- Make the user
1.81      www      4696:     my $reply=&modifyuser
1.209     matthew  4697: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4698:          $desiredhome,$email);
1.80      www      4699:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4700:     # This will cause &modify_student_enrollment to get the uid from the
                   4701:     # students environment
                   4702:     $uid = undef if (!$forceid);
1.455     albertel 4703:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4704: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4705:     return $reply;
                   4706: }
                   4707: 
                   4708: sub modify_student_enrollment {
1.515     raeburn  4709:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4710:     my ($cdom,$cnum,$chome);
                   4711:     if (!$cid) {
1.620     albertel 4712: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4713: 	    return 'not_in_class';
                   4714: 	}
1.620     albertel 4715: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4716: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4717:     } else {
                   4718: 	($cdom,$cnum)=split(/_/,$cid);
                   4719:     }
1.620     albertel 4720:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4721:     if (!$chome) {
1.457     raeburn  4722: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4723:     }
1.455     albertel 4724:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4725:     # Make sure the user exists
1.81      www      4726:     my $uhome=&homeserver($uname,$udom);
                   4727:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4728: 	return 'error: no such user';
                   4729:     }
1.297     matthew  4730:     # Get student data if we were not given enough information
                   4731:     if (!defined($first)  || $first  eq '' || 
                   4732:         !defined($last)   || $last   eq '' || 
                   4733:         !defined($uid)    || $uid    eq '' || 
                   4734:         !defined($middle) || $middle eq '' || 
                   4735:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4736:         # They did not supply us with enough data to enroll the student, so
                   4737:         # we need to pick up more information.
1.297     matthew  4738:         my %tmp = &get('environment',
1.294     matthew  4739:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4740:                        ,$udom,$uname);
                   4741: 
1.800     albertel 4742:         #foreach my $key (keys(%tmp)) {
                   4743:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4744:         #}
1.294     matthew  4745:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4746:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4747:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4748:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4749:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4750:     }
1.556     albertel 4751:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4752:     my $reply=cput('classlist',
                   4753: 		   {"$uname:$udom" => 
1.515     raeburn  4754: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4755: 		   $cdom,$cnum);
1.81      www      4756:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4757: 	return 'error: '.$reply;
1.652     albertel 4758:     } else {
                   4759: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4760:     }
1.297     matthew  4761:     # Add student role to user
1.83      www      4762:     my $uurl='/'.$cid;
1.81      www      4763:     $uurl=~s/\_/\//g;
                   4764:     if ($usec) {
                   4765: 	$uurl.='/'.$usec;
                   4766:     }
                   4767:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4768: }
                   4769: 
1.556     albertel 4770: sub format_name {
                   4771:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4772:     my $name;
                   4773:     if ($first ne 'lastname') {
                   4774: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4775:     } else {
                   4776: 	if ($lastname=~/\S/) {
                   4777: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4778: 	    $name=~s/\s+,/,/;
                   4779: 	} else {
                   4780: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4781: 	}
                   4782:     }
                   4783:     $name=~s/^\s+//;
                   4784:     $name=~s/\s+$//;
                   4785:     $name=~s/\s+/ /g;
                   4786:     return $name;
                   4787: }
                   4788: 
1.84      www      4789: # ------------------------------------------------- Write to course preferences
                   4790: 
                   4791: sub writecoursepref {
                   4792:     my ($courseid,%prefs)=@_;
                   4793:     $courseid=~s/^\///;
                   4794:     $courseid=~s/\_/\//g;
                   4795:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4796:     my $chome=homeserver($cnum,$cdomain);
                   4797:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4798: 	return 'error: no such course';
                   4799:     }
                   4800:     my $cstring='';
1.800     albertel 4801:     foreach my $pref (keys(%prefs)) {
                   4802: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4803:     }
1.84      www      4804:     $cstring=~s/\&$//;
                   4805:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4806: }
                   4807: 
                   4808: # ---------------------------------------------------------- Make/modify course
                   4809: 
                   4810: sub createcourse {
1.741     raeburn  4811:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4812:         $course_owner,$crstype)=@_;
1.84      www      4813:     $url=&declutter($url);
                   4814:     my $cid='';
1.264     matthew  4815:     unless (&allowed('ccc',$udom)) {
1.84      www      4816:         return 'refused';
                   4817:     }
                   4818: # ------------------------------------------------------------------- Create ID
1.674     www      4819:    my $uname=int(1+rand(9)).
                   4820:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4821:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4822:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4823: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4824:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4825:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4826:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4827:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4828:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4829:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4830:            return 'error: unable to generate unique course-ID';
                   4831:        } 
                   4832:    }
1.264     matthew  4833: # ------------------------------------------------ Check supplied server name
1.620     albertel 4834:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4835:     if (! exists($libserv{$course_server})) {
                   4836:         return 'error:bad server name '.$course_server;
                   4837:     }
1.84      www      4838: # ------------------------------------------------------------- Make the course
                   4839:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4840:                       $course_server);
1.84      www      4841:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4842:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4843:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4844: 	return 'error: no such course';
                   4845:     }
1.271     www      4846: # ----------------------------------------------------------------- Course made
1.516     raeburn  4847: # log existence
                   4848:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4849:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4850:                   &escape($crstype),$uhome);
1.358     www      4851:     &flushcourselogs();
                   4852: # set toplevel url
1.271     www      4853:     my $topurl=$url;
                   4854:     unless ($nonstandard) {
                   4855: # ------------------------------------------ For standard courses, make top url
                   4856:         my $mapurl=&clutter($url);
1.278     www      4857:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4858:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4859: <map>
                   4860: <resource id="1" type="start"></resource>
                   4861: <resource id="2" src="$mapurl"></resource>
                   4862: <resource id="3" type="finish"></resource>
                   4863: <link index="1" from="1" to="2"></link>
                   4864: <link index="2" from="2" to="3"></link>
                   4865: </map>
                   4866: ENDINITMAP
                   4867:         $topurl=&declutter(
1.638     albertel 4868:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4869:                           );
                   4870:     }
                   4871: # ----------------------------------------------------------- Write preferences
1.84      www      4872:     &writecoursepref($udom.'_'.$uname,
                   4873:                      ('description' => $description,
1.271     www      4874:                       'url'         => $topurl));
1.84      www      4875:     return '/'.$udom.'/'.$uname;
                   4876: }
                   4877: 
1.21      www      4878: # ---------------------------------------------------------- Assign Custom Role
                   4879: 
                   4880: sub assigncustomrole {
1.357     www      4881:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4882:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4883:                        $end,$start,$deleteflag);
1.21      www      4884: }
                   4885: 
                   4886: # ----------------------------------------------------------------- Revoke Role
                   4887: 
                   4888: sub revokerole {
1.357     www      4889:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4890:     my $now=time;
1.357     www      4891:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4892: }
                   4893: 
                   4894: # ---------------------------------------------------------- Revoke Custom Role
                   4895: 
                   4896: sub revokecustomrole {
1.357     www      4897:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4898:     my $now=time;
1.357     www      4899:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4900:            $deleteflag);
1.17      www      4901: }
                   4902: 
1.533     banghart 4903: # ------------------------------------------------------------ Disk usage
1.535     albertel 4904: sub diskusage {
1.533     banghart 4905:     my ($udom,$uname,$directoryRoot)=@_;
                   4906:     $directoryRoot =~ s/\/$//;
1.535     albertel 4907:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4908:     return $listing;
1.512     banghart 4909: }
                   4910: 
1.566     banghart 4911: sub is_locked {
                   4912:     my ($file_name, $domain, $user) = @_;
                   4913:     my @check;
                   4914:     my $is_locked;
                   4915:     push @check, $file_name;
1.613     albertel 4916:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4917: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4918:     my ($tmp)=keys(%locked);
                   4919:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4920:     
1.566     banghart 4921:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4922:         $is_locked = 'false';
                   4923:         foreach my $entry (@{$locked{$file_name}}) {
                   4924:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4925:                $is_locked = 'true';
                   4926:                last;
1.745     raeburn  4927:            }
                   4928:        }
1.566     banghart 4929:     } else {
                   4930:         $is_locked = 'false';
                   4931:     }
                   4932: }
                   4933: 
1.759     albertel 4934: sub declutter_portfile {
                   4935:     my ($file) = @_;
                   4936:     &logthis("got $file");
                   4937:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4938:     &logthis("ret $file");
                   4939:     return $file;
                   4940: }
                   4941: 
1.559     banghart 4942: # ------------------------------------------------------------- Mark as Read Only
                   4943: 
                   4944: sub mark_as_readonly {
                   4945:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4946:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4947:     my ($tmp)=keys(%current_permissions);
                   4948:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4949:     foreach my $file (@{$files}) {
1.759     albertel 4950: 	$file = &declutter_portfile($file);
1.561     banghart 4951:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4952:     }
1.613     albertel 4953:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4954:     return;
                   4955: }
                   4956: 
1.572     banghart 4957: # ------------------------------------------------------------Save Selected Files
                   4958: 
                   4959: sub save_selected_files {
                   4960:     my ($user, $path, @files) = @_;
                   4961:     my $filename = $user."savedfiles";
1.573     banghart 4962:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4963:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4964:     foreach my $file (@files) {
1.620     albertel 4965:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4966:     }
                   4967:     foreach my $file (@other_files) {
1.574     banghart 4968:         print (OUT $file."\n");
1.572     banghart 4969:     }
1.574     banghart 4970:     close (OUT);
1.572     banghart 4971:     return 'ok';
                   4972: }
                   4973: 
1.574     banghart 4974: sub clear_selected_files {
                   4975:     my ($user) = @_;
                   4976:     my $filename = $user."savedfiles";
                   4977:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4978:     print (OUT undef);
                   4979:     close (OUT);
                   4980:     return ("ok");    
                   4981: }
                   4982: 
1.572     banghart 4983: sub files_in_path {
                   4984:     my ($user, $path) = @_;
                   4985:     my $filename = $user."savedfiles";
                   4986:     my %return_files;
1.574     banghart 4987:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4988:     while (my $line_in = <IN>) {
1.574     banghart 4989:         chomp ($line_in);
                   4990:         my @paths_and_file = split (m!/!, $line_in);
                   4991:         my $file_part = pop (@paths_and_file);
                   4992:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4993:         $path_part.='/';
                   4994:         my $path_and_file = $path_part.$file_part;
                   4995:         if ($path_part eq $path) {
                   4996:             $return_files{$file_part}= 'selected';
                   4997:         }
                   4998:     }
1.574     banghart 4999:     close (IN);
                   5000:     return (\%return_files);
1.572     banghart 5001: }
                   5002: 
                   5003: # called in portfolio select mode, to show files selected NOT in current directory
                   5004: sub files_not_in_path {
                   5005:     my ($user, $path) = @_;
                   5006:     my $filename = $user."savedfiles";
                   5007:     my @return_files;
                   5008:     my $path_part;
1.800     albertel 5009:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5010:     while (my $line = <IN>) {
1.572     banghart 5011:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5012:         my @paths_and_file = split(m|/|, $line);
                   5013:         my $file_part = pop(@paths_and_file);
                   5014:         chomp($file_part);
                   5015:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5016:         $path_part .= '/';
                   5017:         my $path_and_file = $path_part.$file_part;
                   5018:         if ($path_part ne $path) {
1.800     albertel 5019:             push(@return_files, ($path_and_file));
1.572     banghart 5020:         }
                   5021:     }
1.800     albertel 5022:     close(OUT);
1.574     banghart 5023:     return (@return_files);
1.572     banghart 5024: }
                   5025: 
1.745     raeburn  5026: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5027: 
1.745     raeburn  5028: sub get_portfile_permissions {
                   5029:     my ($domain,$user) = @_;
1.613     albertel 5030:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5031:     my ($tmp)=keys(%current_permissions);
                   5032:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5033:     return \%current_permissions;
                   5034: }
                   5035: 
                   5036: #---------------------------------------------Get portfolio file access controls
                   5037: 
1.749     raeburn  5038: sub get_access_controls {
1.745     raeburn  5039:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5040:     my %access;
                   5041:     my $real_file = $file;
                   5042:     $file =~ s/\.meta$//;
1.745     raeburn  5043:     if (defined($file)) {
1.749     raeburn  5044:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5045:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5046:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5047:             }
                   5048:         }
1.745     raeburn  5049:     } else {
1.749     raeburn  5050:         foreach my $key (keys(%{$current_permissions})) {
                   5051:             if ($key =~ /\0accesscontrol$/) {
                   5052:                 if (defined($group)) {
                   5053:                     if ($key !~ m-^\Q$group\E/-) {
                   5054:                         next;
                   5055:                     }
                   5056:                 }
                   5057:                 my ($fullpath) = split(/\0/,$key);
                   5058:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5059:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5060:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5061:                     }
                   5062:                 }
                   5063:             }
                   5064:         }
                   5065:     }
                   5066:     return %access;
                   5067: }
                   5068: 
                   5069: sub modify_access_controls {
                   5070:     my ($file_name,$changes,$domain,$user)=@_;
                   5071:     my ($outcome,$deloutcome);
                   5072:     my %store_permissions;
                   5073:     my %new_values;
                   5074:     my %new_control;
                   5075:     my %translation;
                   5076:     my @deletions = ();
                   5077:     my $now = time;
                   5078:     if (exists($$changes{'activate'})) {
                   5079:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5080:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5081:             my $numnew = scalar(@newitems);
                   5082:             for (my $i=0; $i<$numnew; $i++) {
                   5083:                 my $newkey = $newitems[$i];
                   5084:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5085:                 if ($newkey =~ /^\d+:/) { 
                   5086:                     $newkey =~ s/^(\d+)/$newid/;
                   5087:                     $translation{$1} = $newid;
                   5088:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5089:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5090:                     $translation{$1} = $newid;
                   5091:                 }
1.749     raeburn  5092:                 $new_values{$file_name."\0".$newkey} = 
                   5093:                                           $$changes{'activate'}{$newitems[$i]};
                   5094:                 $new_control{$newkey} = $now;
                   5095:             }
                   5096:         }
                   5097:     }
                   5098:     my %todelete;
                   5099:     my %changed_items;
                   5100:     foreach my $action ('delete','update') {
                   5101:         if (exists($$changes{$action})) {
                   5102:             if (ref($$changes{$action}) eq 'HASH') {
                   5103:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5104:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5105:                     if ($action eq 'delete') { 
                   5106:                         $todelete{$itemnum} = 1;
                   5107:                     } else {
                   5108:                         $changed_items{$itemnum} = $key;
                   5109:                     }
                   5110:                 }
1.745     raeburn  5111:             }
                   5112:         }
1.749     raeburn  5113:     }
                   5114:     # get lock on access controls for file.
                   5115:     my $lockhash = {
                   5116:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5117:                                                        ':'.$env{'user.domain'},
                   5118:                    }; 
                   5119:     my $tries = 0;
                   5120:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5121:    
                   5122:     while (($gotlock ne 'ok') && $tries <3) {
                   5123:         $tries ++;
                   5124:         sleep 1;
                   5125:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5126:     }
                   5127:     if ($gotlock eq 'ok') {
                   5128:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5129:         my ($tmp)=keys(%curr_permissions);
                   5130:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5131:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5132:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5133:             if (ref($curr_controls) eq 'HASH') {
                   5134:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5135:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5136:                     if (defined($todelete{$itemnum})) {
                   5137:                         push(@deletions,$file_name."\0".$control_item);
                   5138:                     } else {
                   5139:                         if (defined($changed_items{$itemnum})) {
                   5140:                             $new_control{$changed_items{$itemnum}} = $now;
                   5141:                             push(@deletions,$file_name."\0".$control_item);
                   5142:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5143:                         } else {
                   5144:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5145:                         }
                   5146:                     }
1.745     raeburn  5147:                 }
                   5148:             }
                   5149:         }
1.749     raeburn  5150:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5151:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5152:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5153:         #  remove lock
                   5154:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5155:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5156:     } else {
                   5157:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5158:     }
1.749     raeburn  5159:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5160: }
                   5161: 
                   5162: #------------------------------------------------------Get Marked as Read Only
                   5163: 
                   5164: sub get_marked_as_readonly {
                   5165:     my ($domain,$user,$what,$group) = @_;
                   5166:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5167:     my @readonly_files;
1.629     banghart 5168:     my $cmp1=$what;
                   5169:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5170:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5171:         if (defined($group)) {
                   5172:             if ($file_name !~ m-^\Q$group\E/-) {
                   5173:                 next;
                   5174:             }
                   5175:         }
1.561     banghart 5176:         if (ref($value) eq "ARRAY"){
                   5177:             foreach my $stored_what (@{$value}) {
1.629     banghart 5178:                 my $cmp2=$stored_what;
1.759     albertel 5179:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5180:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5181:                 }
1.629     banghart 5182:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5183:                     push(@readonly_files, $file_name);
1.745     raeburn  5184:                     last;
1.563     banghart 5185:                 } elsif (!defined($what)) {
                   5186:                     push(@readonly_files, $file_name);
1.745     raeburn  5187:                     last;
1.561     banghart 5188:                 }
                   5189:             }
1.745     raeburn  5190:         }
1.561     banghart 5191:     }
                   5192:     return @readonly_files;
                   5193: }
1.577     banghart 5194: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5195: 
1.577     banghart 5196: sub get_marked_as_readonly_hash {
1.745     raeburn  5197:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5198:     my %readonly_files;
1.745     raeburn  5199:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5200:         if (defined($group)) {
                   5201:             if ($file_name !~ m-^\Q$group\E/-) {
                   5202:                 next;
                   5203:             }
                   5204:         }
1.577     banghart 5205:         if (ref($value) eq "ARRAY"){
                   5206:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5207:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5208:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5209:                         if ($lock_descriptor eq 'graded') {
                   5210:                             $readonly_files{$file_name} = 'graded';
                   5211:                         } elsif ($lock_descriptor eq 'handback') {
                   5212:                             $readonly_files{$file_name} = 'handback';
                   5213:                         } else {
                   5214:                             if (!exists($readonly_files{$file_name})) {
                   5215:                                 $readonly_files{$file_name} = 'locked';
                   5216:                             }
                   5217:                         }
1.745     raeburn  5218:                     }
1.750     banghart 5219:                 } 
1.577     banghart 5220:             }
                   5221:         } 
                   5222:     }
                   5223:     return %readonly_files;
                   5224: }
1.559     banghart 5225: # ------------------------------------------------------------ Unmark as Read Only
                   5226: 
                   5227: sub unmark_as_readonly {
1.629     banghart 5228:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5229:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5230:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5231:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5232:     my $symb_crs = $what;
                   5233:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5234:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5235:     my ($tmp)=keys(%current_permissions);
                   5236:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5237:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5238:     foreach my $file (@readonly_files) {
1.759     albertel 5239: 	my $clean_file = &declutter_portfile($file);
                   5240: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5241: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5242:         my @new_locks;
                   5243:         my @del_keys;
                   5244:         if (ref($current_locks) eq "ARRAY"){
                   5245:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5246:                 my $compare=$locker;
1.749     raeburn  5247:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5248:                     $compare=join('',@{$locker});
1.746     raeburn  5249:                     if ($compare ne $symb_crs) {
                   5250:                         push(@new_locks, $locker);
                   5251:                     }
1.563     banghart 5252:                 }
                   5253:             }
1.650     albertel 5254:             if (scalar(@new_locks) > 0) {
1.563     banghart 5255:                 $current_permissions{$file} = \@new_locks;
                   5256:             } else {
                   5257:                 push(@del_keys, $file);
1.613     albertel 5258:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5259:                 delete($current_permissions{$file});
1.563     banghart 5260:             }
                   5261:         }
1.561     banghart 5262:     }
1.613     albertel 5263:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5264:     return;
                   5265: }
1.512     banghart 5266: 
1.17      www      5267: # ------------------------------------------------------------ Directory lister
                   5268: 
                   5269: sub dirlist {
1.253     stredwic 5270:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5271: 
1.18      www      5272:     $uri=~s/^\///;
                   5273:     $uri=~s/\/$//;
1.253     stredwic 5274:     my ($udom, $uname);
                   5275:     (undef,$udom,$uname)=split(/\//,$uri);
                   5276:     if(defined($userdomain)) {
                   5277:         $udom = $userdomain;
                   5278:     }
                   5279:     if(defined($username)) {
                   5280:         $uname = $username;
                   5281:     }
                   5282: 
                   5283:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5284:     if(defined($alternateDirectoryRoot)) {
                   5285:         $dirRoot = $alternateDirectoryRoot;
                   5286:         $dirRoot =~ s/\/$//;
1.751     banghart 5287:     }
1.253     stredwic 5288: 
                   5289:     if($udom) {
                   5290:         if($uname) {
1.800     albertel 5291:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5292: 				 &homeserver($uname,$udom));
1.605     matthew  5293:             my @listing_results;
                   5294:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5295:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5296: 				  &homeserver($uname,$udom));
1.605     matthew  5297:                 @listing_results = split(/:/,$listing);
                   5298:             } else {
                   5299:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5300:             }
                   5301:             return @listing_results;
1.253     stredwic 5302:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5303:             my %allusers;
                   5304:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5305:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5306:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5307: 					 $udom, $tryserver);
1.605     matthew  5308:                     my @listing_results;
                   5309:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5310:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5311: 					  $udom, $tryserver);
1.605     matthew  5312:                         @listing_results = split(/:/,$listing);
                   5313:                     } else {
                   5314:                         @listing_results =
                   5315:                             map { &unescape($_); } split(/:/,$listing);
                   5316:                     }
                   5317:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5318:                         $listing_results[0] ne 'empty'       &&
                   5319:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5320:                         foreach my $line (@listing_results) {
                   5321:                             my ($entry) = split(/&/,$line,2);
                   5322:                             $allusers{$entry} = 1;
1.253     stredwic 5323:                         }
                   5324:                     }
1.191     harris41 5325:                 }
1.253     stredwic 5326:             }
                   5327:             my $alluserstr='';
1.800     albertel 5328:             foreach my $user (sort(keys(%allusers))) {
                   5329:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5330:             }
                   5331:             $alluserstr=~s/:$//;
                   5332:             return split(/:/,$alluserstr);
                   5333:         } else {
1.800     albertel 5334:             return ('missing user name');
1.253     stredwic 5335:         }
                   5336:     } elsif(!defined($alternateDirectoryRoot)) {
                   5337:         my $tryserver;
                   5338:         my %alldom=();
1.800     albertel 5339:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5340:             $alldom{$hostdom{$tryserver}}=1;
                   5341:         }
                   5342:         my $alldomstr='';
1.800     albertel 5343:         foreach my $domain (sort(keys(%alldom))) {
                   5344:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5345:         }
                   5346:         $alldomstr=~s/:$//;
                   5347:         return split(/:/,$alldomstr);       
                   5348:     } else {
1.800     albertel 5349:         return ('missing domain');
1.275     stredwic 5350:     }
                   5351: }
                   5352: 
                   5353: # --------------------------------------------- GetFileTimestamp
                   5354: # This function utilizes dirlist and returns the date stamp for
                   5355: # when it was last modified.  It will also return an error of -1
                   5356: # if an error occurs
                   5357: 
1.410     matthew  5358: ##
                   5359: ## FIXME: This subroutine assumes its caller knows something about the
                   5360: ## directory structure of the home server for the student ($root).
                   5361: ## Not a good assumption to make.  Since this is for looking up files
                   5362: ## in user directories, the full path should be constructed by lond, not
                   5363: ## whatever machine we request data from.
                   5364: ##
1.275     stredwic 5365: sub GetFileTimestamp {
                   5366:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5367:     $studentDomain=~s/\W//g;
                   5368:     $studentName=~s/\W//g;
                   5369:     my $subdir=$studentName.'__';
                   5370:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5371:     my $proname="$studentDomain/$subdir/$studentName";
                   5372:     $proname .= '/'.$filename;
1.375     matthew  5373:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5374:                                               $studentName, $root);
1.275     stredwic 5375:     my @stats = split('&', $fileStat);
                   5376:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5377:         # @stats contains first the filename, then the stat output
                   5378:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5379:     } else {
                   5380:         return -1;
1.253     stredwic 5381:     }
1.26      www      5382: }
                   5383: 
1.712     albertel 5384: sub stat_file {
                   5385:     my ($uri) = @_;
1.787     albertel 5386:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5387: 
1.712     albertel 5388:     my ($udom,$uname,$file,$dir);
                   5389:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5390: 	($udom,$uname,$file) =
                   5391: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5392: 	$file = 'userfiles/'.$file;
1.740     www      5393: 	$dir = &propath($udom,$uname);
1.712     albertel 5394:     }
                   5395:     if ($uri =~ m-^/res/-) {
                   5396: 	($udom,$uname) = 
                   5397: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5398: 	$file = $uri;
                   5399:     }
                   5400: 
                   5401:     if (!$udom || !$uname || !$file) {
                   5402: 	# unable to handle the uri
                   5403: 	return ();
                   5404:     }
                   5405: 
                   5406:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5407:     my @stats = split('&', $result);
1.721     banghart 5408:     
1.712     albertel 5409:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5410: 	shift(@stats); #filename is first
                   5411: 	return @stats;
                   5412:     }
                   5413:     return ();
                   5414: }
                   5415: 
1.26      www      5416: # -------------------------------------------------------- Value of a Condition
                   5417: 
1.713     albertel 5418: # gets the value of a specific preevaluated condition
                   5419: #    stored in the string  $env{user.state.<cid>}
                   5420: # or looks up a condition reference in the bighash and if if hasn't
                   5421: # already been evaluated recurses into docondval to get the value of
                   5422: # the condition, then memoizing it to 
                   5423: #   $env{user.state.<cid>.<condition>}
1.40      www      5424: sub directcondval {
                   5425:     my $number=shift;
1.620     albertel 5426:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5427: 	&Apache::lonuserstate::evalstate();
                   5428:     }
1.713     albertel 5429:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5430: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5431:     } elsif ($number =~ /^_/) {
                   5432: 	my $sub_condition;
                   5433: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5434: 		&GDBM_READER(),0640)) {
                   5435: 	    $sub_condition=$bighash{'conditions'.$number};
                   5436: 	    untie(%bighash);
                   5437: 	}
                   5438: 	my $value = &docondval($sub_condition);
                   5439: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5440: 	return $value;
                   5441:     }
1.620     albertel 5442:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5443:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5444:     } else {
                   5445:        return 2;
                   5446:     }
                   5447: }
                   5448: 
1.713     albertel 5449: # get the collection of conditions for this resource
1.26      www      5450: sub condval {
                   5451:     my $condidx=shift;
1.54      www      5452:     my $allpathcond='';
1.713     albertel 5453:     foreach my $cond (split(/\|/,$condidx)) {
                   5454: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5455: 	    $allpathcond.=
                   5456: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5457: 	}
1.191     harris41 5458:     }
1.54      www      5459:     $allpathcond=~s/\|$//;
1.713     albertel 5460:     return &docondval($allpathcond);
                   5461: }
                   5462: 
                   5463: #evaluates an expression of conditions
                   5464: sub docondval {
                   5465:     my ($allpathcond) = @_;
                   5466:     my $result=0;
                   5467:     if ($env{'request.course.id'}
                   5468: 	&& defined($allpathcond)) {
                   5469: 	my $operand='|';
                   5470: 	my @stack;
                   5471: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5472: 	    if ($chunk eq '(') {
                   5473: 		push @stack,($operand,$result);
                   5474: 	    } elsif ($chunk eq ')') {
                   5475: 		my $before=pop @stack;
                   5476: 		if (pop @stack eq '&') {
                   5477: 		    $result=$result>$before?$before:$result;
                   5478: 		} else {
                   5479: 		    $result=$result>$before?$result:$before;
                   5480: 		}
                   5481: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5482: 		$operand=$chunk;
                   5483: 	    } else {
                   5484: 		my $new=directcondval($chunk);
                   5485: 		if ($operand eq '&') {
                   5486: 		    $result=$result>$new?$new:$result;
                   5487: 		} else {
                   5488: 		    $result=$result>$new?$result:$new;
                   5489: 		}
                   5490: 	    }
                   5491: 	}
1.26      www      5492:     }
                   5493:     return $result;
1.421     albertel 5494: }
                   5495: 
                   5496: # ---------------------------------------------------- Devalidate courseresdata
                   5497: 
                   5498: sub devalidatecourseresdata {
                   5499:     my ($coursenum,$coursedomain)=@_;
                   5500:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5501:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5502: }
                   5503: 
1.763     www      5504: 
1.200     www      5505: # --------------------------------------------------- Course Resourcedata Query
                   5506: 
1.624     albertel 5507: sub get_courseresdata {
                   5508:     my ($coursenum,$coursedomain)=@_;
1.200     www      5509:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5510:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5511:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5512:     my %dumpreply;
1.417     albertel 5513:     unless (defined($cached)) {
1.624     albertel 5514: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5515: 	$result=\%dumpreply;
1.251     albertel 5516: 	my ($tmp) = keys(%dumpreply);
                   5517: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5518: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5519: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5520: 	    return $tmp;
1.416     albertel 5521: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5522: 	    $result=undef;
1.599     albertel 5523: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5524: 	}
                   5525:     }
1.624     albertel 5526:     return $result;
                   5527: }
                   5528: 
1.633     albertel 5529: sub devalidateuserresdata {
                   5530:     my ($uname,$udom)=@_;
                   5531:     my $hashid="$udom:$uname";
                   5532:     &devalidate_cache_new('userres',$hashid);
                   5533: }
                   5534: 
1.624     albertel 5535: sub get_userresdata {
                   5536:     my ($uname,$udom)=@_;
                   5537:     #most student don\'t have any data set, check if there is some data
                   5538:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5539: 
                   5540:     my $hashid="$udom:$uname";
                   5541:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5542:     if (!defined($cached)) {
                   5543: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5544: 	$result=\%resourcedata;
                   5545: 	&do_cache_new('userres',$hashid,$result,600);
                   5546:     }
                   5547:     my ($tmp)=keys(%$result);
                   5548:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5549: 	return $result;
                   5550:     }
                   5551:     #error 2 occurs when the .db doesn't exist
                   5552:     if ($tmp!~/error: 2 /) {
1.672     albertel 5553: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5554: 		 " Trying to get resource data for ".
                   5555: 		 $uname." at ".$udom.": ".
                   5556: 		 $tmp."</font>");
                   5557:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5558: 	#&EXT_cache_set($udom,$uname);
                   5559: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5560: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5561:     }
                   5562:     return $tmp;
                   5563: }
                   5564: 
                   5565: sub resdata {
                   5566:     my ($name,$domain,$type,@which)=@_;
                   5567:     my $result;
                   5568:     if ($type eq 'course') {
                   5569: 	$result=&get_courseresdata($name,$domain);
                   5570:     } elsif ($type eq 'user') {
                   5571: 	$result=&get_userresdata($name,$domain);
                   5572:     }
                   5573:     if (!ref($result)) { return $result; }    
1.251     albertel 5574:     foreach my $item (@which) {
1.417     albertel 5575: 	if (defined($result->{$item})) {
                   5576: 	    return $result->{$item};
1.251     albertel 5577: 	}
1.250     albertel 5578:     }
1.291     albertel 5579:     return undef;
1.200     www      5580: }
                   5581: 
1.379     matthew  5582: #
                   5583: # EXT resource caching routines
                   5584: #
                   5585: 
                   5586: sub clear_EXT_cache_status {
1.383     albertel 5587:     &delenv('cache.EXT.');
1.379     matthew  5588: }
                   5589: 
                   5590: sub EXT_cache_status {
                   5591:     my ($target_domain,$target_user) = @_;
1.383     albertel 5592:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5593:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5594:         # We know already the user has no data
                   5595:         return 1;
                   5596:     } else {
                   5597:         return 0;
                   5598:     }
                   5599: }
                   5600: 
                   5601: sub EXT_cache_set {
                   5602:     my ($target_domain,$target_user) = @_;
1.383     albertel 5603:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5604:     #&appenv($cachename => time);
1.379     matthew  5605: }
                   5606: 
1.28      www      5607: # --------------------------------------------------------- Value of a Variable
1.58      www      5608: sub EXT {
1.715     albertel 5609: 
1.395     albertel 5610:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5611:     unless ($varname) { return ''; }
1.218     albertel 5612:     #get real user name/domain, courseid and symb
                   5613:     my $courseid;
1.359     albertel 5614:     my $publicuser;
1.427     www      5615:     if ($symbparm) {
                   5616: 	$symbparm=&get_symb_from_alias($symbparm);
                   5617:     }
1.218     albertel 5618:     if (!($uname && $udom)) {
1.790     albertel 5619:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5620:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5621:     } else {
1.620     albertel 5622: 	$courseid=$env{'request.course.id'};
1.218     albertel 5623:     }
1.48      www      5624:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5625:     my $rest;
1.320     albertel 5626:     if (defined($therest[0])) {
1.48      www      5627:        $rest=join('.',@therest);
                   5628:     } else {
                   5629:        $rest='';
                   5630:     }
1.320     albertel 5631: 
1.57      www      5632:     my $qualifierrest=$qualifier;
                   5633:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5634:     my $spacequalifierrest=$space;
                   5635:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5636:     if ($realm eq 'user') {
1.48      www      5637: # --------------------------------------------------------------- user.resource
                   5638: 	if ($space eq 'resource') {
1.651     albertel 5639: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5640: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5641: 		 &&
1.744     albertel 5642: 		 ($symbparm eq &symbread()) ) {	
                   5643: 		# if we are in the middle of processing the resource the
                   5644: 		# get the value we are planning on committing
                   5645:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5646:                     return $Apache::lonhomework::results{$qualifierrest};
                   5647:                 } else {
                   5648:                     return $Apache::lonhomework::history{$qualifierrest};
                   5649:                 }
1.335     albertel 5650: 	    } else {
1.359     albertel 5651: 		my %restored;
1.620     albertel 5652: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5653: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5654: 		} else {
                   5655: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5656: 		}
1.335     albertel 5657: 		return $restored{$qualifierrest};
                   5658: 	    }
1.48      www      5659: # ----------------------------------------------------------------- user.access
                   5660:         } elsif ($space eq 'access') {
1.218     albertel 5661: 	    # FIXME - not supporting calls for a specific user
1.48      www      5662:             return &allowed($qualifier,$rest);
                   5663: # ------------------------------------------ user.preferences, user.environment
                   5664:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5665: 	    if (($uname eq $env{'user.name'}) &&
                   5666: 		($udom eq $env{'user.domain'})) {
                   5667: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5668: 	    } else {
1.359     albertel 5669: 		my %returnhash;
                   5670: 		if (!$publicuser) {
                   5671: 		    %returnhash=&userenvironment($udom,$uname,
                   5672: 						 $qualifierrest);
                   5673: 		}
1.218     albertel 5674: 		return $returnhash{$qualifierrest};
                   5675: 	    }
1.48      www      5676: # ----------------------------------------------------------------- user.course
                   5677:         } elsif ($space eq 'course') {
1.218     albertel 5678: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5679:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5680: # ------------------------------------------------------------------- user.role
                   5681:         } elsif ($space eq 'role') {
1.218     albertel 5682: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5683:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5684:             if ($qualifier eq 'value') {
                   5685: 		return $role;
                   5686:             } elsif ($qualifier eq 'extent') {
                   5687:                 return $where;
                   5688:             }
                   5689: # ----------------------------------------------------------------- user.domain
                   5690:         } elsif ($space eq 'domain') {
1.218     albertel 5691:             return $udom;
1.48      www      5692: # ------------------------------------------------------------------- user.name
                   5693:         } elsif ($space eq 'name') {
1.218     albertel 5694:             return $uname;
1.48      www      5695: # ---------------------------------------------------- Any other user namespace
1.29      www      5696:         } else {
1.359     albertel 5697: 	    my %reply;
                   5698: 	    if (!$publicuser) {
                   5699: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5700: 	    }
                   5701: 	    return $reply{$qualifierrest};
1.48      www      5702:         }
1.236     www      5703:     } elsif ($realm eq 'query') {
                   5704: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5705:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5706: 						[$spacequalifierrest]);
1.620     albertel 5707: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5708:    } elsif ($realm eq 'request') {
1.48      www      5709: # ------------------------------------------------------------- request.browser
                   5710:         if ($space eq 'browser') {
1.430     www      5711: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5712: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5713: 		    return 1;
                   5714: 		} else {
                   5715: 		    return 0;
                   5716: 		}
                   5717: 	    } else {
1.620     albertel 5718: 		return $env{'browser.'.$qualifier};
1.430     www      5719: 	    }
1.57      www      5720: # ------------------------------------------------------------ request.filename
                   5721:         } else {
1.620     albertel 5722:             return $env{'request.'.$spacequalifierrest};
1.29      www      5723:         }
1.28      www      5724:     } elsif ($realm eq 'course') {
1.48      www      5725: # ---------------------------------------------------------- course.description
1.620     albertel 5726:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5727:     } elsif ($realm eq 'resource') {
1.165     www      5728: 
1.620     albertel 5729: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5730: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5731: 	}
1.693     albertel 5732: 
                   5733: 	if ($space eq 'title') {
                   5734: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5735: 	    return &gettitle($symbparm);
                   5736: 	}
                   5737: 	
                   5738: 	if ($space eq 'map') {
                   5739: 	    my ($map) = &decode_symb($symbparm);
                   5740: 	    return &symbread($map);
                   5741: 	}
                   5742: 
                   5743: 	my ($section, $group, @groups);
1.593     albertel 5744: 	my ($courselevelm,$courselevel);
1.539     albertel 5745: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5746: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5747: 
1.218     albertel 5748: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5749: 
1.60      www      5750: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5751: 	    my $symbp=$symbparm;
1.735     albertel 5752: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5753: 
                   5754: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5755: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5756: 
1.620     albertel 5757: 	    if (($env{'user.name'} eq $uname) &&
                   5758: 		($env{'user.domain'} eq $udom)) {
                   5759: 		$section=$env{'request.course.sec'};
1.733     raeburn  5760:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5761:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5762: 	    } else {
1.539     albertel 5763: 		if (! defined($usection)) {
1.551     albertel 5764: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5765: 		} else {
                   5766: 		    $section = $usection;
                   5767: 		}
1.733     raeburn  5768:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5769: 	    }
                   5770: 
                   5771: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5772: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5773: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5774: 
1.593     albertel 5775: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5776: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5777: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5778: 
1.60      www      5779: # ----------------------------------------------------------- first, check user
1.624     albertel 5780: 
                   5781: 	    my $userreply=&resdata($uname,$udom,'user',
                   5782: 				       ($courselevelr,$courselevelm,
                   5783: 					$courselevel));
                   5784: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5785: 
1.594     albertel 5786: # ------------------------------------------------ second, check some of course
1.684     raeburn  5787:             my $coursereply;
1.691     raeburn  5788:             if (@groups > 0) {
                   5789:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5790:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5791:                 if (defined($coursereply)) { return $coursereply; }
                   5792:             }
1.96      www      5793: 
1.684     raeburn  5794: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5795: 				     $env{'course.'.$courseid.'.domain'},
                   5796: 				     'course',
                   5797: 				     ($seclevelr,$seclevelm,$seclevel,
                   5798: 				      $courselevelr));
1.287     albertel 5799: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5800: 
1.60      www      5801: # ------------------------------------------------------ third, check map parms
1.218     albertel 5802: 	    my %parmhash=();
                   5803: 	    my $thisparm='';
                   5804: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5805: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5806: 		    &GDBM_READER(),0640)) {
1.218     albertel 5807: 		$thisparm=$parmhash{$symbparm};
                   5808: 		untie(%parmhash);
                   5809: 	    }
                   5810: 	    if ($thisparm) { return $thisparm; }
                   5811: 	}
1.594     albertel 5812: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5813: 
1.218     albertel 5814: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5815: 	my $filename;
                   5816: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5817: 	if ($symbparm) {
1.409     www      5818: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5819: 	} else {
1.620     albertel 5820: 	    $filename=$env{'request.filename'};
1.282     albertel 5821: 	}
                   5822: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5823: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5824: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5825: 	if (defined($metadata)) { return $metadata; }
1.142     www      5826: 
1.594     albertel 5827: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5828: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5829: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5830: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5831: 				     $env{'course.'.$courseid.'.domain'},
                   5832: 				     'course',
                   5833: 				     ($courselevelm,$courselevel));
1.593     albertel 5834: 	    if (defined($coursereply)) { return $coursereply; }
                   5835: 	}
1.145     www      5836: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5837: 	unless ($space eq '0') {
1.336     albertel 5838: 	    my @parts=split(/_/,$space);
                   5839: 	    my $id=pop(@parts);
                   5840: 	    my $part=join('_',@parts);
                   5841: 	    if ($part eq '') { $part='0'; }
                   5842: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5843: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5844: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5845: 	}
1.395     albertel 5846: 	if ($recurse) { return undef; }
                   5847: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5848: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5849: 
1.48      www      5850: # ---------------------------------------------------- Any other user namespace
                   5851:     } elsif ($realm eq 'environment') {
                   5852: # ----------------------------------------------------------------- environment
1.620     albertel 5853: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5854: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5855: 	} else {
1.770     albertel 5856: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5857: 		return '';
                   5858: 	    }
1.219     albertel 5859: 	    my %returnhash=&userenvironment($udom,$uname,
                   5860: 					    $spacequalifierrest);
                   5861: 	    return $returnhash{$spacequalifierrest};
                   5862: 	}
1.28      www      5863:     } elsif ($realm eq 'system') {
1.48      www      5864: # ----------------------------------------------------------------- system.time
                   5865: 	if ($space eq 'time') {
                   5866: 	    return time;
                   5867:         }
1.696     albertel 5868:     } elsif ($realm eq 'server') {
                   5869: # ----------------------------------------------------------------- system.time
                   5870: 	if ($space eq 'name') {
                   5871: 	    return $ENV{'SERVER_NAME'};
                   5872:         }
1.28      www      5873:     }
1.48      www      5874:     return '';
1.61      www      5875: }
                   5876: 
1.691     raeburn  5877: sub check_group_parms {
                   5878:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5879:     my @groupitems = ();
                   5880:     my $resultitem;
                   5881:     my @levels = ($symbparm,$mapparm,$what);
                   5882:     foreach my $group (@{$groups}) {
                   5883:         foreach my $level (@levels) {
                   5884:              my $item = $courseid.'.['.$group.'].'.$level;
                   5885:              push(@groupitems,$item);
                   5886:         }
                   5887:     }
                   5888:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5889:                             $env{'course.'.$courseid.'.domain'},
                   5890:                                      'course',@groupitems);
                   5891:     return $coursereply;
                   5892: }
                   5893: 
                   5894: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5895:     my ($courseid,@groups) = @_;
                   5896:     @groups = sort(@groups);
1.691     raeburn  5897:     return @groups;
                   5898: }
                   5899: 
1.395     albertel 5900: sub packages_tab_default {
                   5901:     my ($uri,$varname)=@_;
                   5902:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5903: 
                   5904:     my (@extension,@specifics,$do_default);
                   5905:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5906: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5907: 	if ($pack_type eq 'default') {
                   5908: 	    $do_default=1;
                   5909: 	} elsif ($pack_type eq 'extension') {
                   5910: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5911: 	} else {
                   5912: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5913: 	}
                   5914:     }
                   5915:     # first look for a package that matches the requested part id
                   5916:     foreach my $package (@specifics) {
                   5917: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5918: 	next if ($pack_part ne $part);
                   5919: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5920: 	    return $packagetab{"$pack_type&$name&default"};
                   5921: 	}
                   5922:     }
                   5923:     # look for any possible matching non extension_ package
                   5924:     foreach my $package (@specifics) {
                   5925: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5926: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5927: 	    return $packagetab{"$pack_type&$name&default"};
                   5928: 	}
1.585     albertel 5929: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5930: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5931: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5932: 	}
                   5933:     }
1.738     albertel 5934:     # look for any posible extension_ match
                   5935:     foreach my $package (@extension) {
                   5936: 	my ($package,$pack_type)=@{$package};
                   5937: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5938: 	    return $packagetab{"$pack_type&$name&default"};
                   5939: 	}
                   5940: 	if (defined($packagetab{$package."&$name&default"})) {
                   5941: 	    return $packagetab{$package."&$name&default"};
                   5942: 	}
                   5943:     }
                   5944:     # look for a global default setting
                   5945:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5946: 	return $packagetab{"default&$name&default"};
                   5947:     }
1.395     albertel 5948:     return undef;
                   5949: }
                   5950: 
1.334     albertel 5951: sub add_prefix_and_part {
                   5952:     my ($prefix,$part)=@_;
                   5953:     my $keyroot;
                   5954:     if (defined($prefix) && $prefix !~ /^__/) {
                   5955: 	# prefix that has a part already
                   5956: 	$keyroot=$prefix;
                   5957:     } elsif (defined($prefix)) {
                   5958: 	# prefix that is missing a part
                   5959: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5960:     } else {
                   5961: 	# no prefix at all
                   5962: 	if (defined($part)) { $keyroot='_'.$part; }
                   5963:     }
                   5964:     return $keyroot;
                   5965: }
                   5966: 
1.71      www      5967: # ---------------------------------------------------------------- Get metadata
                   5968: 
1.599     albertel 5969: my %metaentry;
1.71      www      5970: sub metadata {
1.176     www      5971:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5972:     $uri=&declutter($uri);
1.288     albertel 5973:     # if it is a non metadata possible uri return quickly
1.529     albertel 5974:     if (($uri eq '') || 
                   5975: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5976: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5977:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5978: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5979: 	return undef;
1.288     albertel 5980:     }
1.73      www      5981:     my $filename=$uri;
                   5982:     $uri=~s/\.meta$//;
1.172     www      5983: #
                   5984: # Is the metadata already cached?
1.177     www      5985: # Look at timestamp of caching
1.172     www      5986: # Everything is cached by the main uri, libraries are never directly cached
                   5987: #
1.428     albertel 5988:     if (!defined($liburi)) {
1.599     albertel 5989: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5990: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5991:     }
                   5992:     {
1.172     www      5993: #
                   5994: # Is this a recursive call for a library?
                   5995: #
1.599     albertel 5996: #	if (! exists($metacache{$uri})) {
                   5997: #	    $metacache{$uri}={};
                   5998: #	}
1.171     www      5999:         if ($liburi) {
                   6000: 	    $liburi=&declutter($liburi);
                   6001:             $filename=$liburi;
1.401     bowersj2 6002:         } else {
1.599     albertel 6003: 	    &devalidate_cache_new('meta',$uri);
                   6004: 	    undef(%metaentry);
1.401     bowersj2 6005: 	}
1.140     www      6006:         my %metathesekeys=();
1.73      www      6007:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6008: 	my $metastring;
1.768     albertel 6009: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6010: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6011: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6012: 	    $metastring=&getfile($file);
1.489     albertel 6013: 	}
1.208     albertel 6014:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6015:         my $token;
1.140     www      6016:         undef %metathesekeys;
1.71      www      6017:         while ($token=$parser->get_token) {
1.339     albertel 6018: 	    if ($token->[0] eq 'S') {
                   6019: 		if (defined($token->[2]->{'package'})) {
1.172     www      6020: #
                   6021: # This is a package - get package info
                   6022: #
1.339     albertel 6023: 		    my $package=$token->[2]->{'package'};
                   6024: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6025: 		    if (defined($token->[2]->{'id'})) { 
                   6026: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6027: 		    }
1.599     albertel 6028: 		    if ($metaentry{':packages'}) {
                   6029: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6030: 		    } else {
1.599     albertel 6031: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6032: 		    }
1.736     albertel 6033: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6034: 			my $part=$keyroot;
                   6035: 			$part=~s/^\_//;
1.736     albertel 6036: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6037: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6038: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6039: 			    # ignore package.tab specified default values
                   6040:                             # here &package_tab_default() will fetch those
                   6041: 			    if ($subp eq 'default') { next; }
1.736     albertel 6042: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6043: 			    my $unikey;
                   6044: 			    if ($pack =~ /_0$/) {
                   6045: 				$unikey='parameter_0_'.$name;
                   6046: 				$part=0;
                   6047: 			    } else {
                   6048: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6049: 			    }
1.339     albertel 6050: 			    if ($subp eq 'display') {
                   6051: 				$value.=' [Part: '.$part.']';
                   6052: 			    }
1.599     albertel 6053: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6054: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6055: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6056: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6057: 			    }
1.599     albertel 6058: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6059: 				$metaentry{':'.$unikey}=
                   6060: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6061: 			    }
1.339     albertel 6062: 			}
                   6063: 		    }
                   6064: 		} else {
1.172     www      6065: #
                   6066: # This is not a package - some other kind of start tag
1.339     albertel 6067: #
                   6068: 		    my $entry=$token->[1];
                   6069: 		    my $unikey;
                   6070: 		    if ($entry eq 'import') {
                   6071: 			$unikey='';
                   6072: 		    } else {
                   6073: 			$unikey=$entry;
                   6074: 		    }
                   6075: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6076: 
                   6077: 		    if (defined($token->[2]->{'id'})) { 
                   6078: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6079: 		    }
1.175     www      6080: 
1.339     albertel 6081: 		    if ($entry eq 'import') {
1.175     www      6082: #
                   6083: # Importing a library here
1.339     albertel 6084: #
                   6085: 			if ($depthcount<20) {
                   6086: 			    my $location=$parser->get_text('/import');
                   6087: 			    my $dir=$filename;
                   6088: 			    $dir=~s|[^/]*$||;
                   6089: 			    $location=&filelocation($dir,$location);
1.736     albertel 6090: 			    my $metadata = 
                   6091: 				&metadata($uri,'keys', $location,$unikey,
                   6092: 					  $depthcount+1);
                   6093: 			    foreach my $meta (split(',',$metadata)) {
                   6094: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6095: 				$metathesekeys{$meta}=1;
1.339     albertel 6096: 			    }
                   6097: 			}
                   6098: 		    } else { 
                   6099: 			
                   6100: 			if (defined($token->[2]->{'name'})) { 
                   6101: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6102: 			}
                   6103: 			$metathesekeys{$unikey}=1;
1.736     albertel 6104: 			foreach my $param (@{$token->[3]}) {
                   6105: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6106: 				$token->[2]->{$param};
1.339     albertel 6107: 			}
                   6108: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6109: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6110: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6111: 		 # only ws inside the tag, and not in default, so use default
                   6112: 		 # as value
1.599     albertel 6113: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6114: 			} else {
1.321     albertel 6115: 		  # either something interesting inside the tag or default
                   6116:                   # uninteresting
1.599     albertel 6117: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6118: 			}
1.172     www      6119: # end of not-a-package not-a-library import
1.339     albertel 6120: 		    }
1.172     www      6121: # end of not-a-package start tag
1.339     albertel 6122: 		}
1.172     www      6123: # the next is the end of "start tag"
1.339     albertel 6124: 	    }
                   6125: 	}
1.483     albertel 6126: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6127: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6128: 	    #no specific packages #how's our extension
                   6129: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6130: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6131: 					 \%metathesekeys);
                   6132: 	}
1.599     albertel 6133: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6134: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6135: 		#no specific packages well let's get default then
                   6136: 		if ($key!~/^default&/) { next; }
1.488     albertel 6137: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6138: 					     \%metathesekeys);
                   6139: 	    }
                   6140: 	}
1.338     www      6141: # are there custom rights to evaluate
1.599     albertel 6142: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6143: 
1.338     www      6144:     #
                   6145:     # Importing a rights file here
1.339     albertel 6146:     #
                   6147: 	    unless ($depthcount) {
1.599     albertel 6148: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6149: 		my $dir=$filename;
                   6150: 		$dir=~s|[^/]*$||;
                   6151: 		$location=&filelocation($dir,$location);
1.736     albertel 6152: 		my $rights_metadata =
                   6153: 		    &metadata($uri,'keys',$location,'_rights',
                   6154: 			      $depthcount+1);
                   6155: 		foreach my $rights (split(',',$rights_metadata)) {
                   6156: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6157: 		    $metathesekeys{$rights}=1;
1.339     albertel 6158: 		}
                   6159: 	    }
                   6160: 	}
1.737     albertel 6161: 	# uniqifiy package listing
                   6162: 	my %seen;
                   6163: 	my @uniq_packages =
                   6164: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6165: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6166: 
                   6167: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6168: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6169: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6170: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6171: # this is the end of "was not already recently cached
1.71      www      6172:     }
1.599     albertel 6173:     return $metaentry{':'.$what};
1.261     albertel 6174: }
                   6175: 
1.488     albertel 6176: sub metadata_create_package_def {
1.483     albertel 6177:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6178:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6179:     if ($subp eq 'default') { next; }
                   6180:     
1.599     albertel 6181:     if (defined($metaentry{':packages'})) {
                   6182: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6183:     } else {
1.599     albertel 6184: 	$metaentry{':packages'}=$package;
1.483     albertel 6185:     }
                   6186:     my $value=$packagetab{$key};
                   6187:     my $unikey;
                   6188:     $unikey='parameter_0_'.$name;
1.599     albertel 6189:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6190:     $$metathesekeys{$unikey}=1;
1.599     albertel 6191:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6192: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6193:     }
1.599     albertel 6194:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6195: 	$metaentry{':'.$unikey}=
                   6196: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6197:     }
                   6198: }
                   6199: 
1.261     albertel 6200: sub metadata_generate_part0 {
                   6201:     my ($metadata,$metacache,$uri) = @_;
                   6202:     my %allnames;
1.737     albertel 6203:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6204: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6205: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6206: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6207: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6208: 	    $allnames{$name}=$part;
                   6209: 	  }
                   6210: 	}
                   6211:     }
                   6212:     foreach my $name (keys(%allnames)) {
                   6213:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6214:       my $key=":parameter_0_$name";
1.261     albertel 6215:       $$metacache{"$key.part"}='0';
                   6216:       $$metacache{"$key.name"}=$name;
1.428     albertel 6217:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6218: 					   $allnames{$name}.'_'.$name.
                   6219: 					   '.type'};
1.428     albertel 6220:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6221: 			     '.display'};
1.644     www      6222:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6223:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6224:       $$metacache{"$key.display"}=$olddis;
                   6225:     }
1.71      www      6226: }
                   6227: 
1.764     albertel 6228: # ------------------------------------------------------ Devalidate title cache
                   6229: 
                   6230: sub devalidate_title_cache {
                   6231:     my ($url)=@_;
                   6232:     if (!$env{'request.course.id'}) { return; }
                   6233:     my $symb=&symbread($url);
                   6234:     if (!$symb) { return; }
                   6235:     my $key=$env{'request.course.id'}."\0".$symb;
                   6236:     &devalidate_cache_new('title',$key);
                   6237: }
                   6238: 
1.301     www      6239: # ------------------------------------------------- Get the title of a resource
                   6240: 
                   6241: sub gettitle {
                   6242:     my $urlsymb=shift;
                   6243:     my $symb=&symbread($urlsymb);
1.534     albertel 6244:     if ($symb) {
1.620     albertel 6245: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6246: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6247: 	if (defined($cached)) { 
                   6248: 	    return $result;
                   6249: 	}
1.534     albertel 6250: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6251: 	my $title='';
                   6252: 	my %bighash;
1.620     albertel 6253: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6254: 		&GDBM_READER(),0640)) {
                   6255: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6256: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6257: 	    untie %bighash;
                   6258: 	}
                   6259: 	$title=~s/\&colon\;/\:/gs;
                   6260: 	if ($title) {
1.599     albertel 6261: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6262: 	}
                   6263: 	$urlsymb=$url;
                   6264:     }
                   6265:     my $title=&metadata($urlsymb,'title');
                   6266:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6267:     return $title;
1.301     www      6268: }
1.613     albertel 6269: 
1.614     albertel 6270: sub get_slot {
                   6271:     my ($which,$cnum,$cdom)=@_;
                   6272:     if (!$cnum || !$cdom) {
1.790     albertel 6273: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6274: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6275: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6276:     }
1.703     albertel 6277:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6278:     my %slotinfo;
                   6279:     if (exists($remembered{$key})) {
                   6280: 	$slotinfo{$which} = $remembered{$key};
                   6281:     } else {
                   6282: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6283: 	&Apache::lonhomework::showhash(%slotinfo);
                   6284: 	my ($tmp)=keys(%slotinfo);
                   6285: 	if ($tmp=~/^error:/) { return (); }
                   6286: 	$remembered{$key} = $slotinfo{$which};
                   6287:     }
1.616     albertel 6288:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6289: 	return %{$slotinfo{$which}};
                   6290:     }
                   6291:     return $slotinfo{$which};
1.614     albertel 6292: }
1.31      www      6293: # ------------------------------------------------- Update symbolic store links
                   6294: 
                   6295: sub symblist {
                   6296:     my ($mapname,%newhash)=@_;
1.438     www      6297:     $mapname=&deversion(&declutter($mapname));
1.31      www      6298:     my %hash;
1.620     albertel 6299:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6300:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6301:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6302: 	    foreach my $url (keys %newhash) {
                   6303: 		next if ($url eq 'last_known'
                   6304: 			 && $env{'form.no_update_last_known'});
                   6305: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6306: 						    $newhash{$url}->[1],
                   6307: 						    $newhash{$url}->[0]);
1.191     harris41 6308:             }
1.31      www      6309:             if (untie(%hash)) {
                   6310: 		return 'ok';
                   6311:             }
                   6312:         }
                   6313:     }
                   6314:     return 'error';
1.212     www      6315: }
                   6316: 
                   6317: # --------------------------------------------------------------- Verify a symb
                   6318: 
                   6319: sub symbverify {
1.510     www      6320:     my ($symb,$thisurl)=@_;
                   6321:     my $thisfn=$thisurl;
1.439     www      6322:     $thisfn=&declutter($thisfn);
1.215     www      6323: # direct jump to resource in page or to a sequence - will construct own symbs
                   6324:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6325: # check URL part
1.409     www      6326:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6327: 
1.431     www      6328:     unless ($url eq $thisfn) { return 0; }
1.213     www      6329: 
1.216     www      6330:     $symb=&symbclean($symb);
1.510     www      6331:     $thisurl=&deversion($thisurl);
1.439     www      6332:     $thisfn=&deversion($thisfn);
1.213     www      6333: 
                   6334:     my %bighash;
                   6335:     my $okay=0;
1.431     www      6336: 
1.620     albertel 6337:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6338:                             &GDBM_READER(),0640)) {
1.510     www      6339:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6340:         unless ($ids) { 
1.510     www      6341:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6342:         }
                   6343:         if ($ids) {
                   6344: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6345: 	    foreach my $id (split(/\,/,$ids)) {
                   6346: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6347:                if (
                   6348:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6349:    eq $symb) { 
1.620     albertel 6350: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6351: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6352: 		       $okay=1; 
                   6353: 		   }
                   6354: 	       }
1.216     www      6355: 	   }
                   6356:         }
1.213     www      6357: 	untie(%bighash);
                   6358:     }
                   6359:     return $okay;
1.31      www      6360: }
                   6361: 
1.210     www      6362: # --------------------------------------------------------------- Clean-up symb
                   6363: 
                   6364: sub symbclean {
                   6365:     my $symb=shift;
1.568     albertel 6366:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6367: # remove version from map
                   6368:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6369: 
1.210     www      6370: # remove version from URL
                   6371:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6372: 
1.507     www      6373: # remove wrapper
                   6374: 
1.510     www      6375:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6376:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6377:     return $symb;
1.409     www      6378: }
                   6379: 
                   6380: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6381: 
                   6382: sub encode_symb {
                   6383:     my ($map,$resid,$url)=@_;
                   6384:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6385: }
1.409     www      6386: 
                   6387: sub decode_symb {
1.568     albertel 6388:     my $symb=shift;
                   6389:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6390:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6391:     return (&fixversion($map),$resid,&fixversion($url));
                   6392: }
                   6393: 
                   6394: sub fixversion {
                   6395:     my $fn=shift;
1.609     banghart 6396:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6397:     my %bighash;
                   6398:     my $uri=&clutter($fn);
1.620     albertel 6399:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6400: # is this cached?
1.599     albertel 6401:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6402:     if (defined($cached)) { return $result; }
                   6403: # unfortunately not cached, or expired
1.620     albertel 6404:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6405: 	    &GDBM_READER(),0640)) {
                   6406:  	if ($bighash{'version_'.$uri}) {
                   6407:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6408:  	    unless (($version eq 'mostrecent') || 
                   6409: 		    ($version==&getversion($uri))) {
1.440     www      6410:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6411:  	    }
                   6412:  	}
                   6413:  	untie %bighash;
1.413     www      6414:     }
1.599     albertel 6415:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6416: }
                   6417: 
                   6418: sub deversion {
                   6419:     my $url=shift;
                   6420:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6421:     return $url;
1.210     www      6422: }
                   6423: 
1.31      www      6424: # ------------------------------------------------------ Return symb list entry
                   6425: 
                   6426: sub symbread {
1.249     www      6427:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6428:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6429:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6430: # no filename provided? try from environment
1.44      www      6431:     unless ($thisfn) {
1.620     albertel 6432:         if ($env{'request.symb'}) {
                   6433: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6434: 	}
1.620     albertel 6435: 	$thisfn=$env{'request.filename'};
1.44      www      6436:     }
1.569     albertel 6437:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6438: # is that filename actually a symb? Verify, clean, and return
                   6439:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6440: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6441: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6442: 	}
1.242     www      6443:     }
1.44      www      6444:     $thisfn=declutter($thisfn);
1.31      www      6445:     my %hash;
1.37      www      6446:     my %bighash;
                   6447:     my $syval='';
1.620     albertel 6448:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6449:         my $targetfn = $thisfn;
1.609     banghart 6450:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6451:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6452:         }
1.687     albertel 6453: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6454: 	    $targetfn=$1;
                   6455: 	}
1.620     albertel 6456:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6457:                       &GDBM_READER(),0640)) {
1.481     raeburn  6458: 	    $syval=$hash{$targetfn};
1.37      www      6459:             untie(%hash);
                   6460:         }
                   6461: # ---------------------------------------------------------- There was an entry
                   6462:         if ($syval) {
1.601     albertel 6463: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6464: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6465: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6466: 		    #return $env{$cache_str}='';
1.601     albertel 6467: 		#}    
                   6468: 		#$syval.=$1;
                   6469: 	    #}
1.37      www      6470:         } else {
                   6471: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6472:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6473:                             &GDBM_READER(),0640)) {
1.37      www      6474: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6475:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6476:               unless ($ids) { 
                   6477:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6478:               }
                   6479:               unless ($ids) {
                   6480: # alias?
                   6481: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6482:               }
1.37      www      6483:               if ($ids) {
                   6484: # ------------------------------------------------------------------- Has ID(s)
                   6485:                  my @possibilities=split(/\,/,$ids);
1.39      www      6486:                  if ($#possibilities==0) {
                   6487: # ----------------------------------------------- There is only one possibility
1.37      www      6488: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6489: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6490: 						    $resid,$thisfn);
1.249     www      6491:                  } elsif (!$donotrecurse) {
1.39      www      6492: # ------------------------------------------ There is more than one possibility
                   6493:                      my $realpossible=0;
1.800     albertel 6494:                      foreach my $id (@possibilities) {
                   6495: 			 my $file=$bighash{'src_'.$id};
1.39      www      6496:                          if (&allowed('bre',$file)) {
1.800     albertel 6497:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6498:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6499: 				$realpossible++;
1.626     albertel 6500:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6501: 						    $resid,$thisfn);
1.39      www      6502:                             }
                   6503: 			 }
1.191     harris41 6504:                      }
1.39      www      6505: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6506:                  } else {
                   6507:                      $syval='';
1.37      www      6508:                  }
                   6509: 	      }
                   6510:               untie(%bighash)
1.481     raeburn  6511:            }
1.31      www      6512:         }
1.62      www      6513:         if ($syval) {
1.620     albertel 6514: 	    return $env{$cache_str}=$syval;
1.62      www      6515:         }
1.31      www      6516:     }
1.44      www      6517:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6518:     return $env{$cache_str}='';
1.31      www      6519: }
                   6520: 
                   6521: # ---------------------------------------------------------- Return random seed
                   6522: 
1.32      www      6523: sub numval {
                   6524:     my $txt=shift;
                   6525:     $txt=~tr/A-J/0-9/;
                   6526:     $txt=~tr/a-j/0-9/;
                   6527:     $txt=~tr/K-T/0-9/;
                   6528:     $txt=~tr/k-t/0-9/;
                   6529:     $txt=~tr/U-Z/0-5/;
                   6530:     $txt=~tr/u-z/0-5/;
                   6531:     $txt=~s/\D//g;
1.564     albertel 6532:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6533:     return int($txt);
1.368     albertel 6534: }
                   6535: 
1.484     albertel 6536: sub numval2 {
                   6537:     my $txt=shift;
                   6538:     $txt=~tr/A-J/0-9/;
                   6539:     $txt=~tr/a-j/0-9/;
                   6540:     $txt=~tr/K-T/0-9/;
                   6541:     $txt=~tr/k-t/0-9/;
                   6542:     $txt=~tr/U-Z/0-5/;
                   6543:     $txt=~tr/u-z/0-5/;
                   6544:     $txt=~s/\D//g;
                   6545:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6546:     my $total;
                   6547:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6548:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6549:     return int($total);
                   6550: }
                   6551: 
1.575     albertel 6552: sub numval3 {
                   6553:     use integer;
                   6554:     my $txt=shift;
                   6555:     $txt=~tr/A-J/0-9/;
                   6556:     $txt=~tr/a-j/0-9/;
                   6557:     $txt=~tr/K-T/0-9/;
                   6558:     $txt=~tr/k-t/0-9/;
                   6559:     $txt=~tr/U-Z/0-5/;
                   6560:     $txt=~tr/u-z/0-5/;
                   6561:     $txt=~s/\D//g;
                   6562:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6563:     my $total;
                   6564:     foreach my $val (@txts) { $total+=$val; }
                   6565:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6566:     return $total;
                   6567: }
                   6568: 
1.675     albertel 6569: sub digest {
                   6570:     my ($data)=@_;
                   6571:     my $digest=&Digest::MD5::md5($data);
                   6572:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6573:     my ($e,$f);
                   6574:     {
                   6575:         use integer;
                   6576:         $e=($a+$b);
                   6577:         $f=($c+$d);
                   6578:         if ($_64bit) {
                   6579:             $e=(($e<<32)>>32);
                   6580:             $f=(($f<<32)>>32);
                   6581:         }
                   6582:     }
                   6583:     if (wantarray) {
                   6584: 	return ($e,$f);
                   6585:     } else {
                   6586: 	my $g;
                   6587: 	{
                   6588: 	    use integer;
                   6589: 	    $g=($e+$f);
                   6590: 	    if ($_64bit) {
                   6591: 		$g=(($g<<32)>>32);
                   6592: 	    }
                   6593: 	}
                   6594: 	return $g;
                   6595:     }
                   6596: }
                   6597: 
1.368     albertel 6598: sub latest_rnd_algorithm_id {
1.675     albertel 6599:     return '64bit5';
1.366     albertel 6600: }
1.32      www      6601: 
1.503     albertel 6602: sub get_rand_alg {
                   6603:     my ($courseid)=@_;
1.790     albertel 6604:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6605:     if ($courseid) {
1.620     albertel 6606: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6607:     }
                   6608:     return &latest_rnd_algorithm_id();
                   6609: }
                   6610: 
1.562     albertel 6611: sub validCODE {
                   6612:     my ($CODE)=@_;
                   6613:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6614:     return 0;
                   6615: }
                   6616: 
1.491     albertel 6617: sub getCODE {
1.620     albertel 6618:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6619:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6620: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6621: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6622: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6623:     }
                   6624:     return undef;
                   6625: }
                   6626: 
1.31      www      6627: sub rndseed {
1.155     albertel 6628:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6629: 
1.790     albertel 6630:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6631:     if (!$symb) {
1.366     albertel 6632: 	unless ($symb=$wsymb) { return time; }
                   6633:     }
                   6634:     if (!$courseid) { $courseid=$wcourseid; }
                   6635:     if (!$domain) { $domain=$wdomain; }
                   6636:     if (!$username) { $username=$wusername }
1.503     albertel 6637:     my $which=&get_rand_alg();
1.803     albertel 6638: 
1.491     albertel 6639:     if (defined(&getCODE())) {
1.675     albertel 6640: 	if ($which eq '64bit5') {
                   6641: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6642: 	} elsif ($which eq '64bit4') {
1.575     albertel 6643: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6644: 	} else {
                   6645: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6646: 	}
1.675     albertel 6647:     } elsif ($which eq '64bit5') {
                   6648: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6649:     } elsif ($which eq '64bit4') {
                   6650: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6651:     } elsif ($which eq '64bit3') {
                   6652: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6653:     } elsif ($which eq '64bit2') {
                   6654: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6655:     } elsif ($which eq '64bit') {
                   6656: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6657:     }
                   6658:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6659: }
                   6660: 
                   6661: sub rndseed_32bit {
                   6662:     my ($symb,$courseid,$domain,$username)=@_;
                   6663:     {
                   6664: 	use integer;
                   6665: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6666: 	my $symbseed=numval($symb) << 22;
                   6667: 	my $namechck=unpack("%32C*",$username) << 17;
                   6668: 	my $nameseed=numval($username) << 12;
                   6669: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6670: 	my $courseseed=unpack("%32C*",$courseid);
                   6671: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6672: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6673: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6674: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6675: 	return $num;
                   6676:     }
                   6677: }
                   6678: 
                   6679: sub rndseed_64bit {
                   6680:     my ($symb,$courseid,$domain,$username)=@_;
                   6681:     {
                   6682: 	use integer;
                   6683: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6684: 	my $symbseed=numval($symb) << 10;
                   6685: 	my $namechck=unpack("%32S*",$username);
                   6686: 	
                   6687: 	my $nameseed=numval($username) << 21;
                   6688: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6689: 	my $courseseed=unpack("%32S*",$courseid);
                   6690: 	
                   6691: 	my $num1=$symbchck+$symbseed+$namechck;
                   6692: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6693: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6694: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6695: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6696: 	return "$num1,$num2";
1.155     albertel 6697:     }
1.366     albertel 6698: }
                   6699: 
1.443     albertel 6700: sub rndseed_64bit2 {
                   6701:     my ($symb,$courseid,$domain,$username)=@_;
                   6702:     {
                   6703: 	use integer;
                   6704: 	# strings need to be an even # of cahracters long, it it is odd the
                   6705:         # last characters gets thrown away
                   6706: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6707: 	my $symbseed=numval($symb) << 10;
                   6708: 	my $namechck=unpack("%32S*",$username.' ');
                   6709: 	
                   6710: 	my $nameseed=numval($username) << 21;
1.501     albertel 6711: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6712: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6713: 	
                   6714: 	my $num1=$symbchck+$symbseed+$namechck;
                   6715: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6716: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6717: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6718: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6719: 	return "$num1,$num2";
                   6720:     }
                   6721: }
                   6722: 
                   6723: sub rndseed_64bit3 {
                   6724:     my ($symb,$courseid,$domain,$username)=@_;
                   6725:     {
                   6726: 	use integer;
                   6727: 	# strings need to be an even # of cahracters long, it it is odd the
                   6728:         # last characters gets thrown away
                   6729: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6730: 	my $symbseed=numval2($symb) << 10;
                   6731: 	my $namechck=unpack("%32S*",$username.' ');
                   6732: 	
                   6733: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6734: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6735: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6736: 	
                   6737: 	my $num1=$symbchck+$symbseed+$namechck;
                   6738: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6739: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6740: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6741: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6742: 	
1.503     albertel 6743: 	return "$num1:$num2";
1.443     albertel 6744:     }
                   6745: }
                   6746: 
1.575     albertel 6747: sub rndseed_64bit4 {
                   6748:     my ($symb,$courseid,$domain,$username)=@_;
                   6749:     {
                   6750: 	use integer;
                   6751: 	# strings need to be an even # of cahracters long, it it is odd the
                   6752:         # last characters gets thrown away
                   6753: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6754: 	my $symbseed=numval3($symb) << 10;
                   6755: 	my $namechck=unpack("%32S*",$username.' ');
                   6756: 	
                   6757: 	my $nameseed=numval3($username) << 21;
                   6758: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6759: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6760: 	
                   6761: 	my $num1=$symbchck+$symbseed+$namechck;
                   6762: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6763: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6764: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6765: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6766: 	
                   6767: 	return "$num1:$num2";
                   6768:     }
                   6769: }
                   6770: 
1.675     albertel 6771: sub rndseed_64bit5 {
                   6772:     my ($symb,$courseid,$domain,$username)=@_;
                   6773:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6774:     return "$num1:$num2";
                   6775: }
                   6776: 
1.366     albertel 6777: sub rndseed_CODE_64bit {
                   6778:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6779:     {
1.366     albertel 6780: 	use integer;
1.443     albertel 6781: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6782: 	my $symbseed=numval2($symb);
1.491     albertel 6783: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6784: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6785: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6786: 	my $num1=$symbseed+$CODEchck;
                   6787: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6788: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6789: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6790: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6791: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6792: 	return "$num1:$num2";
1.366     albertel 6793:     }
                   6794: }
                   6795: 
1.575     albertel 6796: sub rndseed_CODE_64bit4 {
                   6797:     my ($symb,$courseid,$domain,$username)=@_;
                   6798:     {
                   6799: 	use integer;
                   6800: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6801: 	my $symbseed=numval3($symb);
                   6802: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6803: 	my $CODEseed=numval3(&getCODE());
                   6804: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6805: 	my $num1=$symbseed+$CODEchck;
                   6806: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6807: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6808: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6809: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6810: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6811: 	return "$num1:$num2";
                   6812:     }
                   6813: }
                   6814: 
1.675     albertel 6815: sub rndseed_CODE_64bit5 {
                   6816:     my ($symb,$courseid,$domain,$username)=@_;
                   6817:     my $code = &getCODE();
                   6818:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6819:     return "$num1:$num2";
                   6820: }
                   6821: 
1.366     albertel 6822: sub setup_random_from_rndseed {
                   6823:     my ($rndseed)=@_;
1.503     albertel 6824:     if ($rndseed =~/([,:])/) {
                   6825: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6826: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6827:     } else {
                   6828: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6829:     }
1.36      albertel 6830: }
                   6831: 
1.474     albertel 6832: sub latest_receipt_algorithm_id {
                   6833:     return 'receipt2';
                   6834: }
                   6835: 
1.480     www      6836: sub recunique {
                   6837:     my $fucourseid=shift;
                   6838:     my $unique;
1.620     albertel 6839:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6840: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6841:     } else {
                   6842: 	$unique=$perlvar{'lonReceipt'};
                   6843:     }
                   6844:     return unpack("%32C*",$unique);
                   6845: }
                   6846: 
                   6847: sub recprefix {
                   6848:     my $fucourseid=shift;
                   6849:     my $prefix;
1.620     albertel 6850:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6851: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6852:     } else {
                   6853: 	$prefix=$perlvar{'lonHostID'};
                   6854:     }
                   6855:     return unpack("%32C*",$prefix);
                   6856: }
                   6857: 
1.76      www      6858: sub ireceipt {
1.474     albertel 6859:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6860:     my $cuname=unpack("%32C*",$funame);
                   6861:     my $cudom=unpack("%32C*",$fudom);
                   6862:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6863:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6864:     my $cunique=&recunique($fucourseid);
1.474     albertel 6865:     my $cpart=unpack("%32S*",$part);
1.480     www      6866:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6867:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6868: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6869: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6870: 			       
                   6871: 	$return.= ($cunique%$cuname+
                   6872: 		   $cunique%$cudom+
                   6873: 		   $cusymb%$cuname+
                   6874: 		   $cusymb%$cudom+
                   6875: 		   $cucourseid%$cuname+
                   6876: 		   $cucourseid%$cudom+
                   6877: 		   $cpart%$cuname+
                   6878: 		   $cpart%$cudom);
                   6879:     } else {
                   6880: 	$return.= ($cunique%$cuname+
                   6881: 		   $cunique%$cudom+
                   6882: 		   $cusymb%$cuname+
                   6883: 		   $cusymb%$cudom+
                   6884: 		   $cucourseid%$cuname+
                   6885: 		   $cucourseid%$cudom);
                   6886:     }
                   6887:     return $return;
1.76      www      6888: }
                   6889: 
                   6890: sub receipt {
1.474     albertel 6891:     my ($part)=@_;
1.790     albertel 6892:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6893:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6894: }
1.260     ng       6895: 
1.790     albertel 6896: sub whichuser {
                   6897:     my ($passedsymb)=@_;
                   6898:     my ($symb,$courseid,$domain,$name,$publicuser);
                   6899:     if (defined($env{'form.grade_symb'})) {
                   6900: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   6901: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   6902: 	if (!$allowed &&
                   6903: 	    exists($env{'request.course.sec'}) &&
                   6904: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   6905: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   6906: 			      '/'.$env{'request.course.sec'});
                   6907: 	}
                   6908: 	if ($allowed) {
                   6909: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   6910: 	    $courseid=$tmp_courseid;
                   6911: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   6912: 	    ($name)=&get_env_multiple('form.grade_username');
                   6913: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   6914: 	}
                   6915:     }
                   6916:     if (!$passedsymb) {
                   6917: 	$symb=&symbread();
                   6918:     } else {
                   6919: 	$symb=$passedsymb;
                   6920:     }
                   6921:     $courseid=$env{'request.course.id'};
                   6922:     $domain=$env{'user.domain'};
                   6923:     $name=$env{'user.name'};
                   6924:     if ($name eq 'public' && $domain eq 'public') {
                   6925: 	if (!defined($env{'form.username'})) {
                   6926: 	    $env{'form.username'}.=time.rand(10000000);
                   6927: 	}
                   6928: 	$name.=$env{'form.username'};
                   6929:     }
                   6930:     return ($symb,$courseid,$domain,$name,$publicuser);
                   6931: 
                   6932: }
                   6933: 
1.36      albertel 6934: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6935: # returns either the contents of the file or 
                   6936: # -1 if the file doesn't exist
1.481     raeburn  6937: #
                   6938: # if the target is a file that was uploaded via DOCS, 
                   6939: # a check will be made to see if a current copy exists on the local server,
                   6940: # if it does this will be served, otherwise a copy will be retrieved from
                   6941: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6942: # the local server.   
1.472     albertel 6943: 
1.36      albertel 6944: sub getfile {
1.538     albertel 6945:     my ($file) = @_;
1.609     banghart 6946:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6947:     &repcopy($file);
                   6948:     return &readfile($file);
                   6949: }
                   6950: 
                   6951: sub repcopy_userfile {
                   6952:     my ($file)=@_;
1.609     banghart 6953:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6954:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6955:     my ($cdom,$cnum,$filename) = 
                   6956: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6957:     my ($info,$rtncode);
                   6958:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6959:     if (-e "$file") {
                   6960: 	my @fileinfo = stat($file);
                   6961: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6962: 	if ($lwpresp ne 'ok') {
                   6963: 	    if ($rtncode eq '404') {
1.538     albertel 6964: 		unlink($file);
1.482     albertel 6965: 	    }
1.517     albertel 6966: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6967: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6968: 	    #my $response=$ua->request($request);
                   6969: 	    #if ($response->is_success()) {
                   6970: 	#	return $response->content;
                   6971: 	#    } else {
                   6972: 	#	return -1;
                   6973: 	#    }
1.482     albertel 6974: 	    return -1;
                   6975: 	}
                   6976: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6977: 	    return 'ok';
1.482     albertel 6978: 	}
                   6979: 	$info = '';
1.538     albertel 6980: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6981: 	if ($lwpresp ne 'ok') {
                   6982: 	    return -1;
                   6983: 	}
                   6984:     } else {
1.538     albertel 6985: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6986: 	if ($lwpresp ne 'ok') {
1.517     albertel 6987: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6988: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6989: 	    my $response=$ua->request($request);
                   6990: 	    if ($response->is_success()) {
1.538     albertel 6991: 		$info=$response->content;
1.517     albertel 6992: 	    } else {
                   6993: 		return -1;
                   6994: 	    }
1.482     albertel 6995: 	}
                   6996: 	my @parts = ($cdom,$cnum); 
                   6997: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6998: 	    push @parts, split(/\//,$1);
1.518     albertel 6999: 	}
1.538     albertel 7000: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7001: 	foreach my $part (@parts) {
                   7002: 	    $path .= '/'.$part;
                   7003: 	    if (!-e $path) {
                   7004: 		mkdir($path,0770);
                   7005: 	    }
                   7006: 	}
                   7007:     }
1.538     albertel 7008:     open(FILE,">$file");
1.482     albertel 7009:     print FILE $info;
                   7010:     close(FILE);
1.607     raeburn  7011:     return 'ok';
1.481     raeburn  7012: }
                   7013: 
1.517     albertel 7014: sub tokenwrapper {
                   7015:     my $uri=shift;
1.552     albertel 7016:     $uri=~s|^http\://([^/]+)||;
                   7017:     $uri=~s|^/||;
1.620     albertel 7018:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7019:     my $token=$1;
1.552     albertel 7020:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7021:     if ($udom && $uname && $file) {
                   7022: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7023:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7024:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7025:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7026:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7027:     } else {
                   7028:         return '/adm/notfound.html';
                   7029:     }
                   7030: }
                   7031: 
1.481     raeburn  7032: sub getuploaded {
                   7033:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7034:     $uri=~s/^\///;
                   7035:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7036:     my $ua=new LWP::UserAgent;
                   7037:     my $request=new HTTP::Request($reqtype,$uri);
                   7038:     my $response=$ua->request($request);
                   7039:     $$rtncode = $response->code;
1.482     albertel 7040:     if (! $response->is_success()) {
                   7041: 	return 'failed';
                   7042:     }      
                   7043:     if ($reqtype eq 'HEAD') {
1.486     www      7044: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7045:     } elsif ($reqtype eq 'GET') {
                   7046: 	$$info = $response->content;
1.472     albertel 7047:     }
1.482     albertel 7048:     return 'ok';
1.36      albertel 7049: }
                   7050: 
1.481     raeburn  7051: sub readfile {
                   7052:     my $file = shift;
                   7053:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7054:     my $fh;
                   7055:     open($fh,"<$file");
                   7056:     my $a='';
1.800     albertel 7057:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7058:     return $a;
                   7059: }
                   7060: 
1.36      albertel 7061: sub filelocation {
1.590     banghart 7062:     my ($dir,$file) = @_;
                   7063:     my $location;
                   7064:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7065: 
                   7066:     if ($file =~ m-^/adm/-) {
                   7067: 	$file=~s-^/adm/wrapper/-/-;
                   7068: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7069:     }
1.590     banghart 7070:     if ($file=~m:^/~:) { # is a contruction space reference
                   7071:         $location = $file;
                   7072:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 7073:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   7074: 	# is a correct contruction space reference
                   7075:         $location = $file;
1.609     banghart 7076:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7077:         my ($udom,$uname,$filename)=
1.609     banghart 7078:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 7079:         my $home=&homeserver($uname,$udom);
                   7080:         my $is_me=0;
                   7081:         my @ids=&current_machine_ids();
                   7082:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7083:         if ($is_me) {
1.740     www      7084:   	    $location=&propath($udom,$uname).
1.590     banghart 7085:   	      '/userfiles/'.$filename;
                   7086:         } else {
                   7087:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7088:   	      $udom.'/'.$uname.'/'.$filename;
                   7089:         }
                   7090:     } else {
                   7091:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7092:         $file=~s:^/res/:/:;
                   7093:         if ( !( $file =~ m:^/:) ) {
                   7094:             $location = $dir. '/'.$file;
                   7095:         } else {
                   7096:             $location = '/home/httpd/html/res'.$file;
                   7097:         }
1.59      albertel 7098:     }
1.590     banghart 7099:     $location=~s://+:/:g; # remove duplicate /
                   7100:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7101:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7102:     return $location;
1.46      www      7103: }
1.36      albertel 7104: 
1.46      www      7105: sub hreflocation {
                   7106:     my ($dir,$file)=@_;
1.460     albertel 7107:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7108: 	$file=filelocation($dir,$file);
1.700     albertel 7109:     } elsif ($file=~m-^/adm/-) {
                   7110: 	$file=~s-^/adm/wrapper/-/-;
                   7111: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7112:     }
                   7113:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7114: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   7115:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 7116: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 7117:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   7118: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7119: 	    -/uploaded/$1/$2/-x;
1.46      www      7120:     }
1.462     albertel 7121:     return $file;
1.465     albertel 7122: }
                   7123: 
                   7124: sub current_machine_domains {
                   7125:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7126:     my @domains;
                   7127:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7128: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7129: 	if ($hostname eq $name) {
                   7130: 	    push(@domains,$hostdom{$id});
                   7131: 	}
                   7132:     }
                   7133:     return @domains;
                   7134: }
                   7135: 
                   7136: sub current_machine_ids {
                   7137:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7138:     my @ids;
                   7139:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7140: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7141: 	if ($hostname eq $name) {
                   7142: 	    push(@ids,$id);
                   7143: 	}
                   7144:     }
                   7145:     return @ids;
1.31      www      7146: }
                   7147: 
                   7148: # ------------------------------------------------------------- Declutters URLs
                   7149: 
                   7150: sub declutter {
                   7151:     my $thisfn=shift;
1.569     albertel 7152:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7153:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7154:     $thisfn=~s/^\///;
1.697     albertel 7155:     $thisfn=~s|^adm/wrapper/||;
                   7156:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7157:     $thisfn=~s/^res\///;
1.235     www      7158:     $thisfn=~s/\?.+$//;
1.268     www      7159:     return $thisfn;
                   7160: }
                   7161: 
                   7162: # ------------------------------------------------------------- Clutter up URLs
                   7163: 
                   7164: sub clutter {
                   7165:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7166:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7167:        $thisfn='/res'.$thisfn; 
                   7168:     }
1.694     albertel 7169:     if ($thisfn !~m|/adm|) {
1.695     albertel 7170: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7171: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7172: 	} else {
                   7173: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7174: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7175: 	    if ($embstyle eq 'ssi'
                   7176: 		|| ($embstyle eq 'hdn')
                   7177: 		|| ($embstyle eq 'rat')
                   7178: 		|| ($embstyle eq 'prv')
                   7179: 		|| ($embstyle eq 'ign')) {
                   7180: 		#do nothing with these
                   7181: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7182: 		|| ($embstyle eq 'emb')
                   7183: 		|| ($embstyle eq 'wrp')) {
                   7184: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7185: 	    } elsif ($embstyle eq 'unk'
                   7186: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7187: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7188: 	    } else {
1.718     www      7189: #		&logthis("Got a blank emb style");
1.695     albertel 7190: 	    }
1.694     albertel 7191: 	}
                   7192:     }
1.31      www      7193:     return $thisfn;
1.12      www      7194: }
                   7195: 
1.787     albertel 7196: sub clutter_with_no_wrapper {
                   7197:     my $uri = &clutter(shift);
                   7198:     if ($uri =~ m-^/adm/-) {
                   7199: 	$uri =~ s-^/adm/wrapper/-/-;
                   7200: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7201:     }
                   7202:     return $uri;
                   7203: }
                   7204: 
1.557     albertel 7205: sub freeze_escape {
                   7206:     my ($value)=@_;
                   7207:     if (ref($value)) {
                   7208: 	$value=&nfreeze($value);
                   7209: 	return '__FROZEN__'.&escape($value);
                   7210:     }
                   7211:     return &escape($value);
                   7212: }
                   7213: 
1.11      www      7214: 
1.557     albertel 7215: sub thaw_unescape {
                   7216:     my ($value)=@_;
                   7217:     if ($value =~ /^__FROZEN__/) {
                   7218: 	substr($value,0,10,undef);
                   7219: 	$value=&unescape($value);
                   7220: 	return &thaw($value);
                   7221:     }
                   7222:     return &unescape($value);
                   7223: }
                   7224: 
1.436     albertel 7225: sub correct_line_ends {
                   7226:     my ($result)=@_;
                   7227:     $$result =~s/\r\n/\n/mg;
                   7228:     $$result =~s/\r/\n/mg;
1.415     albertel 7229: }
1.1       albertel 7230: # ================================================================ Main Program
                   7231: 
1.184     www      7232: sub goodbye {
1.204     albertel 7233:    &logthis("Starting Shut down");
1.443     albertel 7234: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7235:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7236: #converted
1.599     albertel 7237: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7238:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7239: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7240: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7241: #1.1 only
1.599     albertel 7242: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7243: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7244: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7245: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7246:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7247:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7248:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7249:    &flushcourselogs();
                   7250:    &logthis("Shutting down");
                   7251: }
                   7252: 
1.179     www      7253: BEGIN {
1.228     harris41 7254: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7255:     unless ($readit) {
1.217     harris41 7256: {
1.781     raeburn  7257:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7258:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7259: }
1.1       albertel 7260: 
1.327     albertel 7261: # ------------------------------------------------------------ Read domain file
                   7262: {
                   7263:     %domaindescription = ();
                   7264:     %domain_auth_def = ();
                   7265:     %domain_auth_arg_def = ();
1.448     albertel 7266:     my $fh;
                   7267:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7268: 	while (my $line = <$fh>) {
                   7269:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7270: #           next if /^\#/;
1.801     foxr     7271:            chomp $line;
1.403     www      7272:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7273: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7274: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7275:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7276: 	   $domaindescription{$domain}=$domain_description;
                   7277: 	   $domain_lang_def{$domain}=$def_lang;
                   7278: 	   $domain_city{$domain}=$city;
                   7279: 	   $domain_longi{$domain}=$longi;
                   7280: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7281:            $domain_primary{$domain}=$primary;
1.403     www      7282: 
1.448     albertel 7283:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7284: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7285: 	}
1.327     albertel 7286:     }
1.448     albertel 7287:     close ($fh);
1.327     albertel 7288: }
                   7289: 
                   7290: 
1.1       albertel 7291: # ------------------------------------------------------------- Read hosts file
                   7292: {
1.448     albertel 7293:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7294: 
                   7295:     while (my $configline=<$config>) {
1.303     matthew  7296:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7297:        chomp($configline);
1.595     albertel 7298:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7299:        $name=~s/\s//g;
1.595     albertel 7300:        if ($id && $domain && $role && $name) {
1.252     albertel 7301: 	 $hostname{$id}=$name;
                   7302: 	 $hostdom{$id}=$domain;
                   7303: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7304:        }
1.1       albertel 7305:     }
1.448     albertel 7306:     close($config);
1.619     albertel 7307:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7308:     #&get_iphost();
1.1       albertel 7309: }
                   7310: 
1.598     albertel 7311: sub get_iphost {
                   7312:     if (%iphost) { return %iphost; }
1.653     albertel 7313:     my %name_to_ip;
1.598     albertel 7314:     foreach my $id (keys(%hostname)) {
                   7315: 	my $name=$hostname{$id};
1.653     albertel 7316: 	my $ip;
                   7317: 	if (!exists($name_to_ip{$name})) {
                   7318: 	    $ip = gethostbyname($name);
                   7319: 	    if (!$ip || length($ip) ne 4) {
                   7320: 		&logthis("Skipping host $id name $name no IP found\n");
                   7321: 		next;
                   7322: 	    }
                   7323: 	    $ip=inet_ntoa($ip);
                   7324: 	    $name_to_ip{$name} = $ip;
                   7325: 	} else {
                   7326: 	    $ip = $name_to_ip{$name};
1.598     albertel 7327: 	}
                   7328: 	push(@{$iphost{$ip}},$id);
                   7329:     }
                   7330:     return %iphost;
                   7331: }
                   7332: 
1.1       albertel 7333: # ------------------------------------------------------ Read spare server file
                   7334: {
1.448     albertel 7335:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7336: 
                   7337:     while (my $configline=<$config>) {
                   7338:        chomp($configline);
1.284     matthew  7339:        if ($configline) {
1.784     albertel 7340: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7341: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7342: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7343:        }
                   7344:     }
1.448     albertel 7345:     close($config);
1.1       albertel 7346: }
1.11      www      7347: # ------------------------------------------------------------ Read permissions
                   7348: {
1.448     albertel 7349:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7350: 
                   7351:     while (my $configline=<$config>) {
1.448     albertel 7352: 	chomp($configline);
                   7353: 	if ($configline) {
                   7354: 	    my ($role,$perm)=split(/ /,$configline);
                   7355: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7356: 	}
1.11      www      7357:     }
1.448     albertel 7358:     close($config);
1.11      www      7359: }
                   7360: 
                   7361: # -------------------------------------------- Read plain texts for permissions
                   7362: {
1.448     albertel 7363:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7364: 
                   7365:     while (my $configline=<$config>) {
1.448     albertel 7366: 	chomp($configline);
                   7367: 	if ($configline) {
1.742     raeburn  7368: 	    my ($short,@plain)=split(/:/,$configline);
                   7369:             %{$prp{$short}} = ();
                   7370: 	    if (@plain > 0) {
                   7371:                 $prp{$short}{'std'} = $plain[0];
                   7372:                 for (my $i=1; $i<@plain; $i++) {
                   7373:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7374:                 }
                   7375:             }
1.448     albertel 7376: 	}
1.135     www      7377:     }
1.448     albertel 7378:     close($config);
1.135     www      7379: }
                   7380: 
                   7381: # ---------------------------------------------------------- Read package table
                   7382: {
1.448     albertel 7383:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7384: 
                   7385:     while (my $configline=<$config>) {
1.483     albertel 7386: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7387: 	chomp($configline);
                   7388: 	my ($short,$plain)=split(/:/,$configline);
                   7389: 	my ($pack,$name)=split(/\&/,$short);
                   7390: 	if ($plain ne '') {
                   7391: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7392: 	    $packagetab{$short}=$plain; 
                   7393: 	}
1.11      www      7394:     }
1.448     albertel 7395:     close($config);
1.329     matthew  7396: }
                   7397: 
                   7398: # ------------- set up temporary directory
                   7399: {
                   7400:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7401: 
1.11      www      7402: }
                   7403: 
1.794     albertel 7404: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7405: 				'compress_threshold'=> 20_000,
                   7406:  			        });
1.185     www      7407: 
1.281     www      7408: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7409: $dumpcount=0;
1.22      www      7410: 
1.163     harris41 7411: &logtouch();
1.672     albertel 7412: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7413: $readit=1;
1.564     albertel 7414:     {
                   7415: 	use integer;
                   7416: 	my $test=(2**32)+1;
1.568     albertel 7417: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7418: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7419:     }
1.195     www      7420: }
1.1       albertel 7421: }
1.179     www      7422: 
1.1       albertel 7423: 1;
1.191     harris41 7424: __END__
                   7425: 
1.243     albertel 7426: =pod
                   7427: 
1.191     harris41 7428: =head1 NAME
                   7429: 
1.243     albertel 7430: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7431: 
                   7432: =head1 SYNOPSIS
                   7433: 
1.243     albertel 7434: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7435: 
                   7436:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7437: 
1.243     albertel 7438: Common parameters:
                   7439: 
                   7440: =over 4
                   7441: 
                   7442: =item *
                   7443: 
                   7444: $uname : an internal username (if $cname expecting a course Id specifically)
                   7445: 
                   7446: =item *
                   7447: 
                   7448: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7449: 
                   7450: =item *
                   7451: 
                   7452: $symb : a resource instance identifier
                   7453: 
                   7454: =item *
                   7455: 
                   7456: $namespace : the name of a .db file that contains the data needed or
                   7457: being set.
                   7458: 
                   7459: =back
                   7460: 
1.394     bowersj2 7461: =head1 OVERVIEW
1.191     harris41 7462: 
1.394     bowersj2 7463: lonnet provides subroutines which interact with the
                   7464: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7465: about classes, users, and resources.
1.243     albertel 7466: 
                   7467: For many of these objects you can also use this to store data about
                   7468: them or modify them in various ways.
1.191     harris41 7469: 
1.394     bowersj2 7470: =head2 Symbs
1.191     harris41 7471: 
1.394     bowersj2 7472: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7473: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7474: map, the resource number of the resource in the map, and the URL of
                   7475: the resource itself. The latter is somewhat redundant, but might help
                   7476: if maps change.
                   7477: 
                   7478: An example is
                   7479: 
                   7480:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7481: 
                   7482: The respective map entry is
                   7483: 
                   7484:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7485:   title="Problem 2">
                   7486:  </resource>
                   7487: 
                   7488: Symbs are used by the random number generator, as well as to store and
                   7489: restore data specific to a certain instance of for example a problem.
                   7490: 
                   7491: =head2 Storing And Retrieving Data
                   7492: 
                   7493: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7494: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7495: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7496: is is the non-critical message twin of cstore. These functions are for
                   7497: handlers to store a perl hash to a user's permanent data space in an
                   7498: easy manner, and to retrieve it again on another call. It is expected
                   7499: that a handler would use this once at the beginning to retrieve data,
                   7500: and then again once at the end to send only the new data back.
                   7501: 
                   7502: The data is stored in the user's data directory on the user's
                   7503: homeserver under the ID of the course.
                   7504: 
                   7505: The hash that is returned by restore will have all of the previous
                   7506: value for all of the elements of the hash.
                   7507: 
                   7508: Example:
                   7509: 
                   7510:  #creating a hash
                   7511:  my %hash;
                   7512:  $hash{'foo'}='bar';
                   7513: 
                   7514:  #storing it
                   7515:  &Apache::lonnet::cstore(\%hash);
                   7516: 
                   7517:  #changing a value
                   7518:  $hash{'foo'}='notbar';
                   7519: 
                   7520:  #adding a new value
                   7521:  $hash{'bar'}='foo';
                   7522:  &Apache::lonnet::cstore(\%hash);
                   7523: 
                   7524:  #retrieving the hash
                   7525:  my %history=&Apache::lonnet::restore();
                   7526: 
                   7527:  #print the hash
                   7528:  foreach my $key (sort(keys(%history))) {
                   7529:    print("\%history{$key} = $history{$key}");
                   7530:  }
                   7531: 
                   7532: Will print out:
1.191     harris41 7533: 
1.394     bowersj2 7534:  %history{1:foo} = bar
                   7535:  %history{1:keys} = foo:timestamp
                   7536:  %history{1:timestamp} = 990455579
                   7537:  %history{2:bar} = foo
                   7538:  %history{2:foo} = notbar
                   7539:  %history{2:keys} = foo:bar:timestamp
                   7540:  %history{2:timestamp} = 990455580
                   7541:  %history{bar} = foo
                   7542:  %history{foo} = notbar
                   7543:  %history{timestamp} = 990455580
                   7544:  %history{version} = 2
                   7545: 
                   7546: Note that the special hash entries C<keys>, C<version> and
                   7547: C<timestamp> were added to the hash. C<version> will be equal to the
                   7548: total number of versions of the data that have been stored. The
                   7549: C<timestamp> attribute will be the UNIX time the hash was
                   7550: stored. C<keys> is available in every historical section to list which
                   7551: keys were added or changed at a specific historical revision of a
                   7552: hash.
                   7553: 
                   7554: B<Warning>: do not store the hash that restore returns directly. This
                   7555: will cause a mess since it will restore the historical keys as if the
                   7556: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7557: 
1.394     bowersj2 7558: Calling convention:
1.191     harris41 7559: 
1.394     bowersj2 7560:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7561:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7562: 
1.394     bowersj2 7563: For more detailed information, see lonnet specific documentation.
1.191     harris41 7564: 
1.394     bowersj2 7565: =head1 RETURN MESSAGES
1.191     harris41 7566: 
1.394     bowersj2 7567: =over 4
1.191     harris41 7568: 
1.394     bowersj2 7569: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7570: 
1.394     bowersj2 7571: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7572: when the connection is brought back up
1.191     harris41 7573: 
1.394     bowersj2 7574: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7575: for later delivery
1.191     harris41 7576: 
1.394     bowersj2 7577: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7578: 
1.394     bowersj2 7579: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7580: that was requested
1.191     harris41 7581: 
1.243     albertel 7582: =back
1.191     harris41 7583: 
1.243     albertel 7584: =head1 PUBLIC SUBROUTINES
1.191     harris41 7585: 
1.243     albertel 7586: =head2 Session Environment Functions
1.191     harris41 7587: 
1.243     albertel 7588: =over 4
1.191     harris41 7589: 
1.394     bowersj2 7590: =item * 
                   7591: X<appenv()>
                   7592: B<appenv(%hash)>: the value of %hash is written to
                   7593: the user envirnoment file, and will be restored for each access this
1.620     albertel 7594: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7595: process
1.191     harris41 7596: 
                   7597: =item *
1.394     bowersj2 7598: X<delenv()>
                   7599: B<delenv($regexp)>: removes all items from the session
                   7600: environment file that matches the regular expression in $regexp. The
1.620     albertel 7601: values are also delted from the current processes %env.
1.191     harris41 7602: 
1.795     albertel 7603: =item * get_env_multiple($name) 
                   7604: 
                   7605: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7606: values may be defined and end up as an array ref.
                   7607: 
                   7608: returns an array of values
                   7609: 
1.243     albertel 7610: =back
                   7611: 
                   7612: =head2 User Information
1.191     harris41 7613: 
1.243     albertel 7614: =over 4
1.191     harris41 7615: 
                   7616: =item *
1.394     bowersj2 7617: X<queryauthenticate()>
                   7618: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7619: authentication scheme
                   7620: 
                   7621: =item *
1.394     bowersj2 7622: X<authenticate()>
                   7623: B<authenticate($uname,$upass,$udom)>: try to
                   7624: authenticate user from domain's lib servers (first use the current
                   7625: one). C<$upass> should be the users password.
1.191     harris41 7626: 
                   7627: =item *
1.394     bowersj2 7628: X<homeserver()>
                   7629: B<homeserver($uname,$udom)>: find the server which has
                   7630: the user's directory and files (there must be only one), this caches
                   7631: the answer, and also caches if there is a borken connection.
1.191     harris41 7632: 
                   7633: =item *
1.394     bowersj2 7634: X<idget()>
                   7635: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7636: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7637: username, and only 1 username per ID in a specific domain) (returns
                   7638: hash: id=>name,id=>name)
1.191     harris41 7639: 
                   7640: =item *
1.394     bowersj2 7641: X<idrget()>
                   7642: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7643: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7644: 
                   7645: =item *
1.394     bowersj2 7646: X<idput()>
                   7647: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7648: 
                   7649: =item *
1.394     bowersj2 7650: X<rolesinit()>
                   7651: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7652: 
                   7653: =item *
1.551     albertel 7654: X<getsection()>
                   7655: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7656: course $cname, return section name/number or '' for "not in course"
                   7657: and '-1' for "no section"
                   7658: 
                   7659: =item *
1.394     bowersj2 7660: X<userenvironment()>
                   7661: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7662: passed in @what from the requested user's environment, returns a hash
                   7663: 
                   7664: =back
                   7665: 
                   7666: =head2 User Roles
                   7667: 
                   7668: =over 4
                   7669: 
                   7670: =item *
                   7671: 
                   7672: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7673: actions
                   7674:  F: full access
                   7675:  U,I,K: authentication modes (cxx only)
                   7676:  '': forbidden
                   7677:  1: user needs to choose course
                   7678:  2: browse allowed
1.766     albertel 7679:  A: passphrase authentication needed
1.243     albertel 7680: 
                   7681: =item *
                   7682: 
                   7683: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7684: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7685: and course level
                   7686: 
                   7687: =item *
                   7688: 
                   7689: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7690: explanation of a user role term
                   7691: 
                   7692: =back
                   7693: 
                   7694: =head2 User Modification
                   7695: 
                   7696: =over 4
                   7697: 
                   7698: =item *
                   7699: 
                   7700: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7701: user for the level given by URL.  Optional start and end dates (leave empty
                   7702: string or zero for "no date")
1.191     harris41 7703: 
                   7704: =item *
                   7705: 
1.243     albertel 7706: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7707: change a users, password, possible return values are: ok,
                   7708: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7709: refused
1.191     harris41 7710: 
                   7711: =item *
                   7712: 
1.243     albertel 7713: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7714: 
                   7715: =item *
                   7716: 
1.243     albertel 7717: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7718: modify user
1.191     harris41 7719: 
                   7720: =item *
                   7721: 
1.286     matthew  7722: modifystudent
                   7723: 
                   7724: modify a students enrollment and identification information.
                   7725: The course id is resolved based on the current users environment.  
                   7726: This means the envoking user must be a course coordinator or otherwise
                   7727: associated with a course.
                   7728: 
1.297     matthew  7729: This call is essentially a wrapper for lonnet::modifyuser and
                   7730: lonnet::modify_student_enrollment
1.286     matthew  7731: 
                   7732: Inputs: 
                   7733: 
                   7734: =over 4
                   7735: 
                   7736: =item B<$udom> Students loncapa domain
                   7737: 
                   7738: =item B<$uname> Students loncapa login name
                   7739: 
                   7740: =item B<$uid> Students id/student number
                   7741: 
                   7742: =item B<$umode> Students authentication mode
                   7743: 
                   7744: =item B<$upass> Students password
                   7745: 
                   7746: =item B<$first> Students first name
                   7747: 
                   7748: =item B<$middle> Students middle name
                   7749: 
                   7750: =item B<$last> Students last name
                   7751: 
                   7752: =item B<$gene> Students generation
                   7753: 
                   7754: =item B<$usec> Students section in course
                   7755: 
                   7756: =item B<$end> Unix time of the roles expiration
                   7757: 
                   7758: =item B<$start> Unix time of the roles start date
                   7759: 
                   7760: =item B<$forceid> If defined, allow $uid to be changed
                   7761: 
                   7762: =item B<$desiredhome> server to use as home server for student
                   7763: 
                   7764: =back
1.297     matthew  7765: 
                   7766: =item *
                   7767: 
                   7768: modify_student_enrollment
                   7769: 
                   7770: Change a students enrollment status in a class.  The environment variable
                   7771: 'role.request.course' must be defined for this function to proceed.
                   7772: 
                   7773: Inputs:
                   7774: 
                   7775: =over 4
                   7776: 
                   7777: =item $udom, students domain
                   7778: 
                   7779: =item $uname, students name
                   7780: 
                   7781: =item $uid, students user id
                   7782: 
                   7783: =item $first, students first name
                   7784: 
                   7785: =item $middle
                   7786: 
                   7787: =item $last
                   7788: 
                   7789: =item $gene
                   7790: 
                   7791: =item $usec
                   7792: 
                   7793: =item $end
                   7794: 
                   7795: =item $start
                   7796: 
                   7797: =back
                   7798: 
1.191     harris41 7799: 
                   7800: =item *
                   7801: 
1.243     albertel 7802: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7803: custom role; give a custom role to a user for the level given by URL.  Specify
                   7804: name and domain of role author, and role name
1.191     harris41 7805: 
                   7806: =item *
                   7807: 
1.243     albertel 7808: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7809: 
                   7810: =item *
                   7811: 
1.243     albertel 7812: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7813: 
                   7814: =back
                   7815: 
                   7816: =head2 Course Infomation
                   7817: 
                   7818: =over 4
1.191     harris41 7819: 
                   7820: =item *
                   7821: 
1.631     albertel 7822: coursedescription($courseid) : returns a hash of information about the
                   7823: specified course id, including all environment settings for the
                   7824: course, the description of the course will be in the hash under the
                   7825: key 'description'
1.191     harris41 7826: 
                   7827: =item *
                   7828: 
1.624     albertel 7829: resdata($name,$domain,$type,@which) : request for current parameter
                   7830: setting for a specific $type, where $type is either 'course' or 'user',
                   7831: @what should be a list of parameters to ask about. This routine caches
                   7832: answers for 5 minutes.
1.243     albertel 7833: 
                   7834: =back
                   7835: 
                   7836: =head2 Course Modification
                   7837: 
                   7838: =over 4
1.191     harris41 7839: 
                   7840: =item *
                   7841: 
1.243     albertel 7842: writecoursepref($courseid,%prefs) : write preferences (environment
                   7843: database) for a course
1.191     harris41 7844: 
                   7845: =item *
                   7846: 
1.243     albertel 7847: createcourse($udom,$description,$url) : make/modify course
                   7848: 
                   7849: =back
                   7850: 
                   7851: =head2 Resource Subroutines
                   7852: 
                   7853: =over 4
1.191     harris41 7854: 
                   7855: =item *
                   7856: 
1.243     albertel 7857: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7858: 
                   7859: =item *
                   7860: 
1.243     albertel 7861: repcopy($filename) : subscribes to the requested file, and attempts to
                   7862: replicate from the owning library server, Might return
1.607     raeburn  7863: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7864: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7865: resource. Expects the local filesystem pathname
                   7866: (/home/httpd/html/res/....)
                   7867: 
                   7868: =back
                   7869: 
                   7870: =head2 Resource Information
                   7871: 
                   7872: =over 4
1.191     harris41 7873: 
                   7874: =item *
                   7875: 
1.243     albertel 7876: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7877: a vairety of different possible values, $varname should be a request
                   7878: string, and the other parameters can be used to specify who and what
                   7879: one is asking about.
                   7880: 
                   7881: Possible values for $varname are environment.lastname (or other item
                   7882: from the envirnment hash), user.name (or someother aspect about the
                   7883: user), resource.0.maxtries (or some other part and parameter of a
                   7884: resource)
1.204     albertel 7885: 
                   7886: =item *
                   7887: 
1.243     albertel 7888: directcondval($number) : get current value of a condition; reads from a state
                   7889: string
1.204     albertel 7890: 
                   7891: =item *
                   7892: 
1.243     albertel 7893: condval($condidx) : value of condition index based on state
1.204     albertel 7894: 
                   7895: =item *
                   7896: 
1.243     albertel 7897: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7898: resource's metadata, $what should be either a specific key, or either
                   7899: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7900: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7901: 
                   7902: this function automatically caches all requests
1.191     harris41 7903: 
                   7904: =item *
                   7905: 
1.243     albertel 7906: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7907: network of library servers; returns file handle of where SQL and regex results
                   7908: will be stored for query
1.191     harris41 7909: 
                   7910: =item *
                   7911: 
1.243     albertel 7912: symbread($filename) : return symbolic list entry (filename argument optional);
                   7913: returns the data handle
1.191     harris41 7914: 
                   7915: =item *
                   7916: 
1.243     albertel 7917: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7918: a possible symb for the URL in $thisfn, and if is an encryypted
                   7919: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7920: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7921: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7922: 
1.191     harris41 7923: 
                   7924: =item *
                   7925: 
1.243     albertel 7926: symbclean($symb) : removes versions numbers from a symb, returns the
                   7927: cleaned symb
1.191     harris41 7928: 
                   7929: =item *
                   7930: 
1.243     albertel 7931: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7932: course map, user must be in a course for it to work.
1.191     harris41 7933: 
                   7934: =item *
                   7935: 
1.243     albertel 7936: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7937: 
                   7938: =item *
                   7939: 
1.243     albertel 7940: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7941: a random seed, all arguments are optional, if they aren't sent it uses the
                   7942: environment to derive them. Note: if symb isn't sent and it can't get one
                   7943: from &symbread it will use the current time as its return value
1.191     harris41 7944: 
                   7945: =item *
                   7946: 
1.243     albertel 7947: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7948: unfakeable, receipt
1.191     harris41 7949: 
                   7950: =item *
                   7951: 
1.620     albertel 7952: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7953: 
                   7954: =item *
                   7955: 
1.243     albertel 7956: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7957: 
                   7958: =item *
                   7959: 
1.243     albertel 7960: 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 7961: 
                   7962: =item *
                   7963: 
1.243     albertel 7964: 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 7965: 
                   7966: =item *
                   7967: 
1.243     albertel 7968: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7969: 
                   7970: =item *
                   7971: 
1.243     albertel 7972: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7973: forcing spreadsheet to reevaluate the resource scores next time.
                   7974: 
                   7975: =back
                   7976: 
                   7977: =head2 Storing/Retreiving Data
                   7978: 
                   7979: =over 4
1.191     harris41 7980: 
                   7981: =item *
                   7982: 
1.243     albertel 7983: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7984: for this url; hashref needs to be given and should be a \%hashname; the
                   7985: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7986: be derived from the env
1.191     harris41 7987: 
                   7988: =item *
                   7989: 
1.243     albertel 7990: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7991: uses critical subroutine
1.191     harris41 7992: 
                   7993: =item *
                   7994: 
1.243     albertel 7995: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7996: all args are optional
1.191     harris41 7997: 
                   7998: =item *
                   7999: 
1.717     albertel 8000: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8001: dumps the complete (or key matching regexp) namespace into a hash
                   8002: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8003: normally &store()ed into
                   8004: 
                   8005: $range should be either an integer '100' (give me the first 100
                   8006:                                            matching records)
                   8007:               or be  two integers sperated by a - with no spaces
                   8008:                  '30-50' (give me the 30th through the 50th matching
                   8009:                           records)
                   8010: 
                   8011: 
                   8012: =item *
                   8013: 
                   8014: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8015: replaces a &store() version of data with a replacement set of data
                   8016: for a particular resource in a namespace passed in the $storehash hash 
                   8017: reference
                   8018: 
                   8019: =item *
                   8020: 
1.243     albertel 8021: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8022: works very similar to store/cstore, but all data is stored in a
                   8023: temporary location and can be reset using tmpreset, $storehash should
                   8024: be a hash reference, returns nothing on success
1.191     harris41 8025: 
                   8026: =item *
                   8027: 
1.243     albertel 8028: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8029: similar to restore, but all data is stored in a temporary location and
                   8030: can be reset using tmpreset. Returns a hash of values on success,
                   8031: error string otherwise.
1.191     harris41 8032: 
                   8033: =item *
                   8034: 
1.243     albertel 8035: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8036: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8037: 
                   8038: =item *
                   8039: 
1.243     albertel 8040: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8041: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8042: 
                   8043: =item *
                   8044: 
1.243     albertel 8045: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8046: namesp ($udom and $uname are optional)
1.191     harris41 8047: 
                   8048: =item *
                   8049: 
1.702     albertel 8050: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8051: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8052: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8053: 
1.702     albertel 8054: $range should be either an integer '100' (give me the first 100
                   8055:                                            matching records)
                   8056:               or be  two integers sperated by a - with no spaces
                   8057:                  '30-50' (give me the 30th through the 50th matching
                   8058:                           records)
1.449     matthew  8059: =item *
                   8060: 
                   8061: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8062: $store can be a scalar, an array reference, or if the amount to be 
                   8063: incremented is > 1, a hash reference.
                   8064: 
                   8065: ($udom and $uname are optional)
1.191     harris41 8066: 
                   8067: =item *
                   8068: 
1.243     albertel 8069: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8070: ($udom and $uname are optional)
1.191     harris41 8071: 
                   8072: =item *
                   8073: 
1.243     albertel 8074: cput($namespace,$storehash,$udom,$uname) : critical put
                   8075: ($udom and $uname are optional)
1.191     harris41 8076: 
                   8077: =item *
                   8078: 
1.748     albertel 8079: newput($namespace,$storehash,$udom,$uname) :
                   8080: 
                   8081: Attempts to store the items in the $storehash, but only if they don't
                   8082: currently exist, if this succeeds you can be certain that you have 
                   8083: successfully created a new key value pair in the $namespace db.
                   8084: 
                   8085: 
                   8086: Args:
                   8087:  $namespace: name of database to store values to
                   8088:  $storehash: hashref to store to the db
                   8089:  $udom: (optional) domain of user containing the db
                   8090:  $uname: (optional) name of user caontaining the db
                   8091: 
                   8092: Returns:
                   8093:  'ok' -> succeeded in storing all keys of $storehash
                   8094:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8095:                         least <key> already existed in the db (other
                   8096:                         requested keys may also already exist)
                   8097:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8098:  'con_lost' -> unable to contact request server
                   8099:  'refused' -> action was not allowed by remote machine
                   8100: 
                   8101: 
                   8102: =item *
                   8103: 
1.243     albertel 8104: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8105: reference filled in from namesp (encrypts the return communication)
                   8106: ($udom and $uname are optional)
1.191     harris41 8107: 
                   8108: =item *
                   8109: 
1.243     albertel 8110: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8111: critical subroutine
                   8112: 
                   8113: =back
                   8114: 
                   8115: =head2 Network Status Functions
                   8116: 
                   8117: =over 4
1.191     harris41 8118: 
                   8119: =item *
                   8120: 
                   8121: dirlist($uri) : return directory list based on URI
                   8122: 
                   8123: =item *
                   8124: 
1.243     albertel 8125: spareserver() : find server with least workload from spare.tab
                   8126: 
                   8127: =back
                   8128: 
                   8129: =head2 Apache Request
                   8130: 
                   8131: =over 4
1.191     harris41 8132: 
                   8133: =item *
                   8134: 
1.243     albertel 8135: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8136: localhost, posts hash
                   8137: 
                   8138: =back
                   8139: 
                   8140: =head2 Data to String to Data
                   8141: 
                   8142: =over 4
1.191     harris41 8143: 
                   8144: =item *
                   8145: 
1.243     albertel 8146: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8147: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8148: 
                   8149: =item *
                   8150: 
1.243     albertel 8151: hashref2str($hashref) : convert a hashref into a string complete with
                   8152: escaping and '=' and '&' separators, supports elements that are
                   8153: arrayrefs and hashrefs
1.191     harris41 8154: 
                   8155: =item *
                   8156: 
1.243     albertel 8157: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8158: with escaping and '&' separators, supports elements that are arrayrefs
                   8159: and hashrefs
1.191     harris41 8160: 
                   8161: =item *
                   8162: 
1.243     albertel 8163: str2hash($string) : convert string to hash using unescaping and
                   8164: splitting on '=' and '&', supports elements that are arrayrefs and
                   8165: hashrefs
1.191     harris41 8166: 
                   8167: =item *
                   8168: 
1.243     albertel 8169: str2array($string) : convert string to hash using unescaping and
                   8170: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8171: 
                   8172: =back
                   8173: 
                   8174: =head2 Logging Routines
                   8175: 
                   8176: =over 4
                   8177: 
                   8178: These routines allow one to make log messages in the lonnet.log and
                   8179: lonnet.perm logfiles.
1.191     harris41 8180: 
                   8181: =item *
                   8182: 
1.243     albertel 8183: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8184: 
                   8185: =item *
                   8186: 
1.243     albertel 8187: logthis() : append message to the normal lonnet.log file, it gets
                   8188: preiodically rolled over and deleted.
1.191     harris41 8189: 
                   8190: =item *
                   8191: 
1.243     albertel 8192: logperm() : append a permanent message to lonnet.perm.log, this log
                   8193: file never gets deleted by any automated portion of the system, only
                   8194: messages of critical importance should go in here.
                   8195: 
                   8196: =back
                   8197: 
                   8198: =head2 General File Helper Routines
                   8199: 
                   8200: =over 4
1.191     harris41 8201: 
                   8202: =item *
                   8203: 
1.481     raeburn  8204: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8205: (a) files in /uploaded
                   8206:   (i) If a local copy of the file exists - 
                   8207:       compares modification date of local copy with last-modified date for 
                   8208:       definitive version stored on home server for course. If local copy is 
                   8209:       stale, requests a new version from the home server and stores it. 
                   8210:       If the original has been removed from the home server, then local copy 
                   8211:       is unlinked.
                   8212:   (ii) If local copy does not exist -
                   8213:       requests the file from the home server and stores it. 
                   8214:   
                   8215:   If $caller is 'uploadrep':  
                   8216:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8217:     for request for files originally uploaded via DOCS. 
                   8218:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8219:   
                   8220:   Otherwise:
                   8221:      This indicates a call from the content generation phase of the request.
                   8222:      -  returns the entire contents of the file or -1.
                   8223:      
                   8224: (b) files in /res
                   8225:    - returns the entire contents of a file or -1; 
                   8226:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8227: 
1.712     albertel 8228: 
                   8229: =item *
                   8230: 
                   8231: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8232:                   reference
                   8233: 
                   8234: returns either a stat() list of data about the file or an empty list
                   8235: if the file doesn't exist or couldn't find out about it (connection
                   8236: problems or user unknown)
                   8237: 
1.191     harris41 8238: =item *
                   8239: 
1.243     albertel 8240: filelocation($dir,$file) : returns file system location of a file
                   8241: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8242: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8243: and a file of ../bob will become /a/bob)
1.191     harris41 8244: 
                   8245: =item *
                   8246: 
                   8247: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8248: filelocation except for hrefs
                   8249: 
                   8250: =item *
                   8251: 
                   8252: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8253: 
1.243     albertel 8254: =back
                   8255: 
1.608     albertel 8256: =head2 Usererfile file routines (/uploaded*)
                   8257: 
                   8258: =over 4
                   8259: 
                   8260: =item *
                   8261: 
                   8262: userfileupload(): main rotine for putting a file in a user or course's
                   8263:                   filespace, arguments are,
                   8264: 
1.620     albertel 8265:  formname - required - this is the name of the element in $env where the
1.608     albertel 8266:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8267:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8268:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8269:  coursedoc - if true, store the file in the course of the active role
                   8270:              of the current user
                   8271:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8272:          if undefined, it will be placed in "unknown"
                   8273: 
                   8274:  (This routine calls clean_filename() to remove any dangerous
                   8275:  characters from the filename, and then calls finuserfileupload() to
                   8276:  complete the transaction)
                   8277: 
                   8278:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8279:  and /adm/notfound.html if unsuccessful
                   8280: 
                   8281: =item *
                   8282: 
                   8283: clean_filename(): routine for cleaing a filename up for storage in
                   8284:                  userfile space, argument is:
                   8285: 
                   8286:  filename - proposed filename
                   8287: 
                   8288: returns: the new clean filename
                   8289: 
                   8290: =item *
                   8291: 
                   8292: finishuserfileupload(): routine that creaes and sends the file to
                   8293: userspace, probably shouldn't be called directly
                   8294: 
                   8295:   docuname: username or courseid of destination for the file
                   8296:   docudom: domain of user/course of destination for the file
                   8297:   formname: same as for userfileupload()
                   8298:   fname: filename (inculding subdirectories) for the file
                   8299: 
                   8300:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8301:  and /adm/notfound.html if unsuccessful
                   8302: 
                   8303: =item *
                   8304: 
                   8305: renameuserfile(): renames an existing userfile to a new name
                   8306: 
                   8307:   Args:
                   8308:    docuname: username or courseid of destination for the file
                   8309:    docudom: domain of user/course of destination for the file
                   8310:    old: current file name (including any subdirs under userfiles)
                   8311:    new: desired file name (including any subdirs under userfiles)
                   8312: 
                   8313: =item *
                   8314: 
                   8315: mkdiruserfile(): creates a directory is a userfiles dir
                   8316: 
                   8317:   Args:
                   8318:    docuname: username or courseid of destination for the file
                   8319:    docudom: domain of user/course of destination for the file
                   8320:    dir: dir to create (including any subdirs under userfiles)
                   8321: 
                   8322: =item *
                   8323: 
                   8324: removeuserfile(): removes a file that exists in userfiles
                   8325: 
                   8326:   Args:
                   8327:    docuname: username or courseid of destination for the file
                   8328:    docudom: domain of user/course of destination for the file
                   8329:    fname: filname to delete (including any subdirs under userfiles)
                   8330: 
                   8331: =item *
                   8332: 
                   8333: removeuploadedurl(): convience function for removeuserfile()
                   8334: 
                   8335:   Args:
                   8336:    url:  a full /uploaded/... url to delete
                   8337: 
1.747     albertel 8338: =item * 
                   8339: 
                   8340: get_portfile_permissions():
                   8341:   Args:
                   8342:     domain: domain of user or course contain the portfolio files
                   8343:     user: name of user or num of course contain the portfolio files
                   8344:   Returns:
                   8345:     hashref of a dump of the proper file_permissions.db
                   8346:    
                   8347: 
                   8348: =item * 
                   8349: 
                   8350: get_access_controls():
                   8351: 
                   8352: Args:
                   8353:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8354:   group: (optional) the group you want the files associated with
                   8355:   file: (optional) the file you want access info on
                   8356: 
                   8357: Returns:
1.749     raeburn  8358:     a hash (keys are file names) of hashes containing
                   8359:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8360:         values are XML containing access control settings (see below) 
1.747     albertel 8361: 
                   8362: Internal notes:
                   8363: 
1.749     raeburn  8364:  access controls are stored in file_permissions.db as key=value pairs.
                   8365:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8366:         where scope -> public,guest,course,group,domains or users.
                   8367:               end -> UNIX time for end of access (0 -> no end date)
                   8368:               start -> UNIX time for start of access
                   8369: 
                   8370:     value -> XML description of access control
                   8371:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8372:             <start></start>
                   8373:             <end></end>
                   8374: 
                   8375:             <password></password>  for scope type = guest
                   8376: 
                   8377:             <domain></domain>     for scope type = course or group
                   8378:             <number></number>
                   8379:             <roles id="">
                   8380:              <role></role>
                   8381:              <access></access>
                   8382:              <section></section>
                   8383:              <group></group>
                   8384:             </roles>
                   8385: 
                   8386:             <dom></dom>         for scope type = domains
                   8387: 
                   8388:             <users>             for scope type = users
                   8389:              <user>
                   8390:               <uname></uname>
                   8391:               <udom></udom>
                   8392:              </user>
                   8393:             </users>
                   8394:            </scope> 
                   8395:               
                   8396:  Access data is also aggregated for each file in an additional key=value pair:
                   8397:  key -> path to file/file_name\0accesscontrol 
                   8398:  value -> reference to hash
                   8399:           hash contains key = value pairs
                   8400:           where key = uniqueID:scope_end_start
                   8401:                 value = UNIX time record was last updated
                   8402: 
                   8403:           Used to improve speed of look-ups of access controls for each file.  
                   8404:  
                   8405:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8406: 
                   8407: modify_access_controls():
                   8408: 
                   8409: Modifies access controls for a portfolio file
                   8410: Args
                   8411: 1. file name
                   8412: 2. reference to hash of required changes,
                   8413: 3. domain
                   8414: 4. username
                   8415:   where domain,username are the domain of the portfolio owner 
                   8416:   (either a user or a course) 
                   8417: 
                   8418: Returns:
                   8419: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8420: 2. result of deletions ('ok' or 'error', with error message).
                   8421: 3. reference to hash of any new or updated access controls.
                   8422: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8423:    key = integer (inbound ID)
                   8424:    value = uniqueID  
1.747     albertel 8425: 
1.608     albertel 8426: =back
                   8427: 
1.243     albertel 8428: =head2 HTTP Helper Routines
                   8429: 
                   8430: =over 4
                   8431: 
1.191     harris41 8432: =item *
                   8433: 
                   8434: escape() : unpack non-word characters into CGI-compatible hex codes
                   8435: 
                   8436: =item *
                   8437: 
                   8438: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8439: 
1.243     albertel 8440: =back
                   8441: 
                   8442: =head1 PRIVATE SUBROUTINES
                   8443: 
                   8444: =head2 Underlying communication routines (Shouldn't call)
                   8445: 
                   8446: =over 4
                   8447: 
                   8448: =item *
                   8449: 
                   8450: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8451: 
                   8452: =item *
                   8453: 
                   8454: reply() : uses subreply to send a message to remote machine, logs all failures
                   8455: 
                   8456: =item *
                   8457: 
                   8458: critical() : passes a critical message to another server; if cannot
                   8459: get through then place message in connection buffer directory and
                   8460: returns con_delayed, if incapable of saving message, returns
                   8461: con_failed
                   8462: 
                   8463: =item *
                   8464: 
                   8465: reconlonc() : tries to reconnect lonc client processes.
                   8466: 
                   8467: =back
                   8468: 
                   8469: =head2 Resource Access Logging
                   8470: 
                   8471: =over 4
                   8472: 
                   8473: =item *
                   8474: 
                   8475: flushcourselogs() : flush (save) buffer logs and access logs
                   8476: 
                   8477: =item *
                   8478: 
                   8479: courselog($what) : save message for course in hash
                   8480: 
                   8481: =item *
                   8482: 
                   8483: courseacclog($what) : save message for course using &courselog().  Perform
                   8484: special processing for specific resource types (problems, exams, quizzes, etc).
                   8485: 
1.191     harris41 8486: =item *
                   8487: 
                   8488: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8489: as a PerlChildExitHandler
1.243     albertel 8490: 
                   8491: =back
                   8492: 
                   8493: =head2 Other
                   8494: 
                   8495: =over 4
                   8496: 
                   8497: =item *
                   8498: 
                   8499: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8500: 
                   8501: =back
                   8502: 
                   8503: =cut

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