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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.800   ! albertel    4: # $Id: lonnet.pm,v 1.799 2006/10/23 21:22:44 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 {
                   3222:     my ($storehash,$server)=@_;
                   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/\&$//;
                   3228:     return &reply("tmpput:$items",$server);
                   3229: }
                   3230: 
                   3231: # ------------------------------------------------------------ tmpget interface
                   3232: sub tmpget {
1.688     albertel 3233:     my ($token,$server)=@_;
                   3234:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3235:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3236:     my %returnhash;
                   3237:     foreach my $item (split(/\&/,$rep)) {
                   3238: 	my ($key,$value)=split(/=/,$item);
                   3239: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3240:     }
                   3241:     return %returnhash;
                   3242: }
                   3243: 
1.688     albertel 3244: # ------------------------------------------------------------ tmpget interface
                   3245: sub tmpdel {
                   3246:     my ($token,$server)=@_;
                   3247:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3248:     return &reply("tmpdel:$token",$server);
                   3249: }
                   3250: 
1.765     albertel 3251: # -------------------------------------------------- portfolio access checking
                   3252: 
                   3253: sub portfolio_access {
1.766     albertel 3254:     my ($requrl) = @_;
1.765     albertel 3255:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3256:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3257:     if ($result eq 'ok') {
1.766     albertel 3258:        return 'F';
1.765     albertel 3259:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3260:        return 'A';
1.765     albertel 3261:     }
1.766     albertel 3262:     return '';
1.765     albertel 3263: }
                   3264: 
                   3265: sub get_portfolio_access {
1.767     albertel 3266:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3267: 
                   3268:     if (!ref($access_hash)) {
                   3269: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3270: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3271: 						   $file_name);
                   3272: 	$access_hash = $access_controls{$file_name};
                   3273:     }
                   3274: 
1.765     albertel 3275:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3276:     my $now = time;
                   3277:     if (ref($access_hash) eq 'HASH') {
                   3278:         foreach my $key (keys(%{$access_hash})) {
                   3279:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3280:             if ($start > $now) {
                   3281:                 next;
                   3282:             }
                   3283:             if ($end && $end<$now) {
                   3284:                 next;
                   3285:             }
                   3286:             if ($scope eq 'public') {
                   3287:                 $public = $key;
                   3288:                 last;
                   3289:             } elsif ($scope eq 'guest') {
                   3290:                 $guest = $key;
                   3291:             } elsif ($scope eq 'domains') {
                   3292:                 push(@domains,$key);
                   3293:             } elsif ($scope eq 'users') {
                   3294:                 push(@users,$key);
                   3295:             } elsif ($scope eq 'course') {
                   3296:                 push(@courses,$key);
                   3297:             } elsif ($scope eq 'group') {
                   3298:                 push(@groups,$key);
                   3299:             }
                   3300:         }
                   3301:         if ($public) {
                   3302:             return 'ok';
                   3303:         }
                   3304:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3305:             if ($guest) {
                   3306:                 return $guest;
                   3307:             }
                   3308:         } else {
                   3309:             if (@domains > 0) {
                   3310:                 foreach my $domkey (@domains) {
                   3311:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3312:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3313:                             return 'ok';
                   3314:                         }
                   3315:                     }
                   3316:                 }
                   3317:             }
                   3318:             if (@users > 0) {
                   3319:                 foreach my $userkey (@users) {
                   3320:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3321:                         return 'ok';
                   3322:                     }
                   3323:                 }
                   3324:             }
                   3325:             my %roleshash;
                   3326:             my @courses_and_groups = @courses;
                   3327:             push(@courses_and_groups,@groups); 
                   3328:             if (@courses_and_groups > 0) {
                   3329:                 my (%allgroups,%allroles); 
                   3330:                 my ($start,$end,$role,$sec,$group);
                   3331:                 foreach my $envkey (%env) {
                   3332:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3333:                         my $cid = $2.'_'.$3; 
                   3334:                         if ($1 eq 'gr') {
                   3335:                             $group = $4;
                   3336:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3337:                         } else {
                   3338:                             if ($4 eq '') {
                   3339:                                 $sec = 'none';
                   3340:                             } else {
                   3341:                                 $sec = $4;
                   3342:                             }
                   3343:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3344:                         }
                   3345:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3346:                         my $cid = $2.'_'.$3;
                   3347:                         if ($4 eq '') {
                   3348:                             $sec = 'none';
                   3349:                         } else {
                   3350:                             $sec = $4;
                   3351:                         }
                   3352:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3353:                     }
                   3354:                 }
                   3355:                 if (keys(%allroles) == 0) {
                   3356:                     return;
                   3357:                 }
                   3358:                 foreach my $key (@courses_and_groups) {
                   3359:                     my %content = %{$$access_hash{$key}};
                   3360:                     my $cnum = $content{'number'};
                   3361:                     my $cdom = $content{'domain'};
                   3362:                     my $cid = $cdom.'_'.$cnum;
                   3363:                     if (!exists($allroles{$cid})) {
                   3364:                         next;
                   3365:                     }    
                   3366:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3367:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3368:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3369:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3370:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3371:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3372:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3373:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3374:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3375:                                         if (grep/^all$/,@sections) {
                   3376:                                             return 'ok';
                   3377:                                         } else {
                   3378:                                             if (grep/^$sec$/,@sections) {
                   3379:                                                 return 'ok';
                   3380:                                             }
                   3381:                                         }
                   3382:                                     }
                   3383:                                 }
                   3384:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3385:                                     if (grep/^none$/,@groups) {
                   3386:                                         return 'ok';
                   3387:                                     }
                   3388:                                 } else {
                   3389:                                     if (grep/^all$/,@groups) {
                   3390:                                         return 'ok';
                   3391:                                     } 
                   3392:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3393:                                         if (grep/^$group$/,@groups) {
                   3394:                                             return 'ok';
                   3395:                                         }
                   3396:                                     }
                   3397:                                 } 
                   3398:                             }
                   3399:                         }
                   3400:                     }
                   3401:                 }
                   3402:             }
                   3403:             if ($guest) {
                   3404:                 return $guest;
                   3405:             }
                   3406:         }
                   3407:     }
                   3408:     return;
                   3409: }
                   3410: 
                   3411: sub course_group_datechecker {
                   3412:     my ($dates,$now,$status) = @_;
                   3413:     my ($start,$end) = split(/\./,$dates);
                   3414:     if (!$start && !$end) {
                   3415:         return 'ok';
                   3416:     }
                   3417:     if (grep/^active$/,@{$status}) {
                   3418:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3419:             return 'ok';
                   3420:         }
                   3421:     }
                   3422:     if (grep/^previous$/,@{$status}) {
                   3423:         if ($end > $now ) {
                   3424:             return 'ok';
                   3425:         }
                   3426:     }
                   3427:     if (grep/^future$/,@{$status}) {
                   3428:         if ($start > $now) {
                   3429:             return 'ok';
                   3430:         }
                   3431:     }
                   3432:     return; 
                   3433: }
                   3434: 
                   3435: sub parse_portfolio_url {
                   3436:     my ($url) = @_;
                   3437: 
                   3438:     my ($type,$udom,$unum,$group,$file_name);
                   3439:     
                   3440:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3441: 	$type = 1;
                   3442:         $udom = $1;
                   3443:         $unum = $2;
                   3444:         $file_name = $3;
                   3445:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3446: 	$type = 2;
                   3447:         $udom = $1;
                   3448:         $unum = $2;
                   3449:         $group = $3;
                   3450:         $file_name = $3.'/'.$4;
                   3451:     }
                   3452:     if (wantarray) {
                   3453: 	return ($type,$udom,$unum,$file_name,$group);
                   3454:     }
                   3455:     return $type;
                   3456: }
                   3457: 
                   3458: sub is_portfolio_url {
                   3459:     my ($url) = @_;
                   3460:     return scalar(&parse_portfolio_url($url));
                   3461: }
                   3462: 
1.798     raeburn  3463: sub is_portfolio_file {
                   3464:     my ($file) = @_;
                   3465:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
                   3466:         return 1;
                   3467:     }
                   3468:     return;
                   3469: }
                   3470: 
                   3471: 
1.341     www      3472: # ---------------------------------------------- Custom access rule evaluation
                   3473: 
                   3474: sub customaccess {
                   3475:     my ($priv,$uri)=@_;
1.620     albertel 3476:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3477:     $urealm=~s/^\W//;
                   3478:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3479:     my $access=0;
1.800   ! albertel 3480:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
        !          3481: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3482:         if ($role) {
                   3483: 	   if ($role ne $urole) { next; }
                   3484:         }
1.800   ! albertel 3485:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
        !          3486:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3487:             if ($tdom) {
                   3488: 		if ($tdom ne $udom) { next; }
                   3489:             }
                   3490:             if ($tcrs) {
                   3491: 		if ($tcrs ne $ucrs) { next; }
                   3492:             }
                   3493:             if ($tsec) {
                   3494: 		if ($tsec ne $usec) { next; }
                   3495:             }
                   3496:             $access=($effect eq 'allow');
                   3497:             last;
1.342     www      3498:         }
1.402     bowersj2 3499: 	if ($realm eq '' && $role eq '') {
                   3500:             $access=($effect eq 'allow');
                   3501: 	}
1.341     www      3502:     }
                   3503:     return $access;
                   3504: }
                   3505: 
1.103     harris41 3506: # ------------------------------------------------- Check for a user privilege
1.12      www      3507: 
                   3508: sub allowed {
1.579     albertel 3509:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3510:     my $ver_orguri=$uri;
1.439     www      3511:     $uri=&deversion($uri);
1.152     www      3512:     my $orguri=$uri;
1.52      www      3513:     $uri=&declutter($uri);
1.545     banghart 3514:     
1.620     albertel 3515:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3516: # Free bre access to adm and meta resources
1.775     albertel 3517:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3518: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3519: 	&& ($priv eq 'bre')) {
1.14      www      3520: 	return 'F';
1.159     www      3521:     }
                   3522: 
1.545     banghart 3523: # Free bre access to user's own portfolio contents
1.714     raeburn  3524:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3525:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3526: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3527:         return 'F';
                   3528:     }
                   3529: 
1.762     raeburn  3530: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3531:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3532:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3533:         if (exists($env{'request.course.id'})) {
                   3534:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3535:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3536:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3537:                 my $courseprivid=$env{'request.course.id'};
                   3538:                 $courseprivid=~s/\_/\//;
                   3539:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3540:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3541:                     return $1; 
1.762     raeburn  3542:                 } else {
                   3543:                     if ($env{'request.course.sec'}) {
                   3544:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3545:                     }
                   3546:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3547:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3548:                         return $2;
                   3549:                     }
1.714     raeburn  3550:                 }
                   3551:             }
                   3552:         }
                   3553:     }
                   3554: 
1.159     www      3555: # Free bre to public access
                   3556: 
                   3557:     if ($priv eq 'bre') {
1.238     www      3558:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3559: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3560:            return 'F'; 
                   3561:         }
1.238     www      3562:         if ($copyright eq 'priv') {
                   3563:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3564: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3565: 		return '';
                   3566:             }
                   3567:         }
                   3568:         if ($copyright eq 'domain') {
                   3569:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3570: 	    unless (($env{'user.domain'} eq $1) ||
                   3571:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3572: 		return '';
                   3573:             }
1.262     matthew  3574:         }
1.620     albertel 3575:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3576:             # Library role, so allow browsing of resources in this domain.
                   3577:             return 'F';
1.238     www      3578:         }
1.341     www      3579:         if ($copyright eq 'custom') {
                   3580: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3581:         }
1.14      www      3582:     }
1.264     matthew  3583:     # Domain coordinator is trying to create a course
1.620     albertel 3584:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3585:         # uri is the requested domain in this case.
                   3586:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3587:         # a role of dc for the domain in question.
1.620     albertel 3588:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3589:     }
1.29      www      3590: 
1.52      www      3591:     my $thisallowed='';
                   3592:     my $statecond=0;
                   3593:     my $courseprivid='';
                   3594: 
                   3595: # Course
                   3596: 
1.620     albertel 3597:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3598:        $thisallowed.=$1;
                   3599:     }
1.29      www      3600: 
1.52      www      3601: # Domain
                   3602: 
1.620     albertel 3603:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3604:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3605:        $thisallowed.=$1;
                   3606:     }
1.52      www      3607: 
                   3608: # Course: uri itself is a course
1.66      www      3609:     my $courseuri=$uri;
                   3610:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3611:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3612: 
1.620     albertel 3613:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3614:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3615:        $thisallowed.=$1;
                   3616:     }
1.29      www      3617: 
1.665     albertel 3618: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3619: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3620:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3621: 	$thisallowed='';
1.671     raeburn  3622:         my ($match)=&is_on_map($uri);
                   3623:         if ($match) {
                   3624:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3625:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3626:                 $thisallowed.=$1;
                   3627:             }
                   3628:         } else {
1.705     albertel 3629:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3630:             if ($refuri) {
                   3631:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3632:                     $thisallowed='F';
1.671     raeburn  3633:                 } else {
                   3634:                     $refuri=&declutter($refuri);
                   3635:                     my ($match) = &is_on_map($refuri);
                   3636:                     if ($match) {
                   3637:                         $thisallowed='F';
                   3638:                     }
1.669     raeburn  3639:                 }
1.671     raeburn  3640:             }
                   3641:         }
1.314     www      3642:     }
1.492     albertel 3643: 
1.766     albertel 3644:     if ($priv eq 'bre'
                   3645: 	&& $thisallowed ne 'F' 
                   3646: 	&& $thisallowed ne '2'
                   3647: 	&& &is_portfolio_url($uri)) {
                   3648: 	$thisallowed = &portfolio_access($uri);
                   3649:     }
                   3650:     
1.52      www      3651: # Full access at system, domain or course-wide level? Exit.
1.29      www      3652: 
                   3653:     if ($thisallowed=~/F/) {
                   3654: 	return 'F';
                   3655:     }
                   3656: 
1.52      www      3657: # If this is generating or modifying users, exit with special codes
1.29      www      3658: 
1.643     www      3659:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3660: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3661: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3662: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3663: 	    unless ($auname) { return $thisallowed; }
                   3664: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3665: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3666: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3667: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3668: 	}
1.52      www      3669: 	return $thisallowed;
                   3670:     }
                   3671: #
1.103     harris41 3672: # Gathered so far: system, domain and course wide privileges
1.52      www      3673: #
                   3674: # Course: See if uri or referer is an individual resource that is part of 
                   3675: # the course
                   3676: 
1.620     albertel 3677:     if ($env{'request.course.id'}) {
1.232     www      3678: 
1.620     albertel 3679:        $courseprivid=$env{'request.course.id'};
                   3680:        if ($env{'request.course.sec'}) {
                   3681:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3682:        }
                   3683:        $courseprivid=~s/\_/\//;
                   3684:        my $checkreferer=1;
1.232     www      3685:        my ($match,$cond)=&is_on_map($uri);
                   3686:        if ($match) {
                   3687:            $statecond=$cond;
1.620     albertel 3688:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3689:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3690:                $thisallowed.=$1;
                   3691:                $checkreferer=0;
                   3692:            }
1.29      www      3693:        }
1.83      www      3694:        
1.148     www      3695:        if ($checkreferer) {
1.620     albertel 3696: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3697:             unless ($refuri) {
1.800   ! albertel 3698:                 foreach my $key (keys(%env)) {
        !          3699: 		    if ($key=~/^httpref\..*\*/) {
        !          3700: 			my $pattern=$key;
1.156     www      3701:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3702:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3703:                         $pattern=~s/\//\\\//g;
1.152     www      3704:                         if ($orguri=~/$pattern/) {
1.800   ! albertel 3705: 			    $refuri=$env{$key};
1.148     www      3706:                         }
                   3707:                     }
1.191     harris41 3708:                 }
1.148     www      3709:             }
1.232     www      3710: 
1.148     www      3711:          if ($refuri) { 
1.152     www      3712: 	  $refuri=&declutter($refuri);
1.232     www      3713:           my ($match,$cond)=&is_on_map($refuri);
                   3714:             if ($match) {
                   3715:               my $refstatecond=$cond;
1.620     albertel 3716:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3717:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3718:                   $thisallowed.=$1;
1.53      www      3719:                   $uri=$refuri;
                   3720:                   $statecond=$refstatecond;
1.52      www      3721:               }
                   3722:           }
1.148     www      3723:         }
1.29      www      3724:        }
1.52      www      3725:    }
1.29      www      3726: 
1.52      www      3727: #
1.103     harris41 3728: # Gathered now: all privileges that could apply, and condition number
1.52      www      3729: # 
                   3730: #
                   3731: # Full or no access?
                   3732: #
1.29      www      3733: 
1.52      www      3734:     if ($thisallowed=~/F/) {
                   3735: 	return 'F';
                   3736:     }
1.29      www      3737: 
1.52      www      3738:     unless ($thisallowed) {
                   3739:         return '';
                   3740:     }
1.29      www      3741: 
1.52      www      3742: # Restrictions exist, deal with them
                   3743: #
                   3744: #   C:according to course preferences
                   3745: #   R:according to resource settings
                   3746: #   L:unless locked
                   3747: #   X:according to user session state
                   3748: #
                   3749: 
                   3750: # Possibly locked functionality, check all courses
1.54      www      3751: # Locks might take effect only after 10 minutes cache expiration for other
                   3752: # courses, and 2 minutes for current course
1.52      www      3753: 
                   3754:     my $envkey;
                   3755:     if ($thisallowed=~/L/) {
1.620     albertel 3756:         foreach $envkey (keys %env) {
1.54      www      3757:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3758:                my $courseid=$2;
                   3759:                my $roleid=$1.'.'.$2;
1.92      www      3760:                $courseid=~s/^\///;
1.54      www      3761:                my $expiretime=600;
1.620     albertel 3762:                if ($env{'request.role'} eq $roleid) {
1.54      www      3763: 		  $expiretime=120;
                   3764:                }
                   3765: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3766:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3767:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3768: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3769:                }
1.620     albertel 3770:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3771:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3772: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3773:                        &log($env{'user.domain'},$env{'user.name'},
                   3774:                             $env{'user.home'},
1.57      www      3775:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3776:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3777:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3778: 		       return '';
                   3779:                    }
                   3780:                }
1.620     albertel 3781:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3782:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3783: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3784:                        &log($env{'user.domain'},$env{'user.name'},
                   3785:                             $env{'user.home'},
1.57      www      3786:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3787:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3788:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3789: 		       return '';
                   3790:                    }
                   3791:                }
                   3792: 	   }
1.29      www      3793:        }
1.52      www      3794:     }
                   3795:    
                   3796: #
                   3797: # Rest of the restrictions depend on selected course
                   3798: #
                   3799: 
1.620     albertel 3800:     unless ($env{'request.course.id'}) {
1.766     albertel 3801: 	if ($thisallowed eq 'A') {
                   3802: 	    return 'A';
                   3803: 	} else {
                   3804: 	    return '1';
                   3805: 	}
1.52      www      3806:     }
1.29      www      3807: 
1.52      www      3808: #
                   3809: # Now user is definitely in a course
                   3810: #
1.53      www      3811: 
                   3812: 
                   3813: # Course preferences
                   3814: 
                   3815:    if ($thisallowed=~/C/) {
1.620     albertel 3816:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3817:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3818:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3819: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3820: 	   if ($priv ne 'pch') { 
                   3821: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3822: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3823: 			$env{'request.course.id'});
                   3824: 	   }
1.237     www      3825:            return '';
                   3826:        }
                   3827: 
1.620     albertel 3828:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3829: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3830: 	   if ($priv ne 'pch') { 
                   3831: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3832: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3833: 			$env{'request.course.id'});
                   3834: 	   }
1.54      www      3835:            return '';
                   3836:        }
1.53      www      3837:    }
                   3838: 
                   3839: # Resource preferences
                   3840: 
                   3841:    if ($thisallowed=~/R/) {
1.620     albertel 3842:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3843:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3844: 	   if ($priv ne 'pch') { 
                   3845: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3846: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3847: 	   }
                   3848: 	   return '';
1.54      www      3849:        }
1.53      www      3850:    }
1.30      www      3851: 
1.246     www      3852: # Restricted by state or randomout?
1.30      www      3853: 
1.52      www      3854:    if ($thisallowed=~/X/) {
1.620     albertel 3855:       if ($env{'acc.randomout'}) {
1.579     albertel 3856: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3857:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3858:             return ''; 
                   3859:          }
1.247     www      3860:       }
                   3861:       if (&condval($statecond)) {
1.52      www      3862: 	 return '2';
                   3863:       } else {
                   3864:          return '';
                   3865:       }
                   3866:    }
1.30      www      3867: 
1.766     albertel 3868:     if ($thisallowed eq 'A') {
                   3869: 	return 'A';
                   3870:     }
1.52      www      3871:    return 'F';
1.232     www      3872: }
                   3873: 
1.710     albertel 3874: sub split_uri_for_cond {
                   3875:     my $uri=&deversion(&declutter(shift));
                   3876:     my @uriparts=split(/\//,$uri);
                   3877:     my $filename=pop(@uriparts);
                   3878:     my $pathname=join('/',@uriparts);
                   3879:     return ($pathname,$filename);
                   3880: }
1.232     www      3881: # --------------------------------------------------- Is a resource on the map?
                   3882: 
                   3883: sub is_on_map {
1.710     albertel 3884:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3885:     #Trying to find the conditional for the file
1.620     albertel 3886:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3887: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3888:     if ($match) {
1.289     bowersj2 3889: 	return (1,$1);
                   3890:     } else {
1.434     www      3891: 	return (0,0);
1.289     bowersj2 3892:     }
1.12      www      3893: }
                   3894: 
1.427     www      3895: # --------------------------------------------------------- Get symb from alias
                   3896: 
                   3897: sub get_symb_from_alias {
                   3898:     my $symb=shift;
                   3899:     my ($map,$resid,$url)=&decode_symb($symb);
                   3900: # Already is a symb
                   3901:     if ($url) { return $symb; }
                   3902: # Must be an alias
                   3903:     my $aliassymb='';
                   3904:     my %bighash;
1.620     albertel 3905:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3906:                             &GDBM_READER(),0640)) {
                   3907:         my $rid=$bighash{'mapalias_'.$symb};
                   3908: 	if ($rid) {
                   3909: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3910: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3911: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3912: 	}
                   3913:         untie %bighash;
                   3914:     }
                   3915:     return $aliassymb;
                   3916: }
                   3917: 
1.12      www      3918: # ----------------------------------------------------------------- Define Role
                   3919: 
                   3920: sub definerole {
                   3921:   if (allowed('mcr','/')) {
                   3922:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800   ! albertel 3923:     foreach my $role (split(':',$sysrole)) {
        !          3924: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3925:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3926:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3927: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3928:                return "refused:s:$crole&$cqual"; 
                   3929:             }
                   3930:         }
1.191     harris41 3931:     }
1.800   ! albertel 3932:     foreach my $role (split(':',$domrole)) {
        !          3933: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3934:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3935:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3936: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3937:                return "refused:d:$crole&$cqual"; 
                   3938:             }
                   3939:         }
1.191     harris41 3940:     }
1.800   ! albertel 3941:     foreach my $role (split(':',$courole)) {
        !          3942: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3943:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3944:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3945: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3946:                return "refused:c:$crole&$cqual"; 
                   3947:             }
                   3948:         }
1.191     harris41 3949:     }
1.620     albertel 3950:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3951:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3952: 	        "rolesdef_$rolename=".
                   3953:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3954:     return reply($command,$env{'user.home'});
1.12      www      3955:   } else {
                   3956:     return 'refused';
                   3957:   }
1.105     harris41 3958: }
                   3959: 
                   3960: # ---------------- Make a metadata query against the network of library servers
                   3961: 
                   3962: sub metadata_query {
1.244     matthew  3963:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3964:     my %rhash;
1.244     matthew  3965:     my @server_list = (defined($server_array) ? @$server_array
                   3966:                                               : keys(%libserv) );
                   3967:     for my $server (@server_list) {
1.118     harris41 3968: 	unless ($custom or $customshow) {
                   3969: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3970: 	    $rhash{$server}=$reply;
                   3971: 	}
                   3972: 	else {
                   3973: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3974: 			     &escape($custom).':'.&escape($customshow),
                   3975: 			     $server);
                   3976: 	    $rhash{$server}=$reply;
                   3977: 	}
1.112     harris41 3978:     }
1.118     harris41 3979:     return \%rhash;
1.240     www      3980: }
                   3981: 
                   3982: # ----------------------------------------- Send log queries and wait for reply
                   3983: 
                   3984: sub log_query {
                   3985:     my ($uname,$udom,$query,%filters)=@_;
                   3986:     my $uhome=&homeserver($uname,$udom);
                   3987:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3988:     my $uhost=$hostname{$uhome};
1.800   ! albertel 3989:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      3990:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3991:                        $uhome);
1.479     albertel 3992:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3993:     return get_query_reply($queryid);
                   3994: }
                   3995: 
1.508     raeburn  3996: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3997: 
                   3998: sub fetch_enrollment_query {
1.511     raeburn  3999:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4000:     my $homeserver;
1.547     raeburn  4001:     my $maxtries = 1;
1.508     raeburn  4002:     if ($context eq 'automated') {
                   4003:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4004:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4005:     } else {
                   4006:         $homeserver = &homeserver($cnum,$dom);
                   4007:     }
1.506     raeburn  4008:     my $host=$hostname{$homeserver};
                   4009:     my $cmd = '';
1.800   ! albertel 4010:     foreach my $affiliate (keys %{$affiliatesref}) {
        !          4011:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4012:     }
                   4013:     $cmd =~ s/%%$//;
                   4014:     $cmd = &escape($cmd);
                   4015:     my $query = 'fetchenrollment';
1.620     albertel 4016:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4017:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4018:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4019:         return 'error: '.$queryid;
                   4020:     }
1.506     raeburn  4021:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4022:     my $tries = 1;
                   4023:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4024:         $reply = &get_query_reply($queryid);
                   4025:         $tries ++;
                   4026:     }
1.526     raeburn  4027:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4028:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4029:     } else {
1.515     raeburn  4030:         my @responses = split/:/,$reply;
                   4031:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800   ! albertel 4032:             foreach my $line (@responses) {
        !          4033:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4034:                 $$replyref{$key} = $value;
                   4035:             }
                   4036:         } else {
1.506     raeburn  4037:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800   ! albertel 4038:             foreach my $line (@responses) {
        !          4039:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4040:                 $$replyref{$key} = $value;
                   4041:                 if ($value > 0) {
1.800   ! albertel 4042:                     foreach my $item (@{$$affiliatesref{$key}}) {
        !          4043:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4044:                         my $destname = $pathname.'/'.$filename;
                   4045:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4046:                         if ($xml_classlist =~ /^error/) {
                   4047:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4048:                         } else {
1.506     raeburn  4049:                             if ( open(FILE,">$destname") ) {
                   4050:                                 print FILE &unescape($xml_classlist);
                   4051:                                 close(FILE);
1.526     raeburn  4052:                             } else {
                   4053:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4054:                             }
                   4055:                         }
                   4056:                     }
                   4057:                 }
                   4058:             }
                   4059:         }
                   4060:         return 'ok';
                   4061:     }
                   4062:     return 'error';
                   4063: }
                   4064: 
1.242     www      4065: sub get_query_reply {
                   4066:     my $queryid=shift;
1.240     www      4067:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4068:     my $reply='';
                   4069:     for (1..100) {
                   4070: 	sleep 2;
                   4071:         if (-e $replyfile.'.end') {
1.448     albertel 4072: 	    if (open(my $fh,$replyfile)) {
1.240     www      4073:                $reply.=<$fh>;
1.448     albertel 4074:                close($fh);
1.240     www      4075: 	   } else { return 'error: reply_file_error'; }
1.242     www      4076:            return &unescape($reply);
                   4077: 	}
1.240     www      4078:     }
1.242     www      4079:     return 'timeout:'.$queryid;
1.240     www      4080: }
                   4081: 
                   4082: sub courselog_query {
1.241     www      4083: #
                   4084: # possible filters:
                   4085: # url: url or symb
                   4086: # username
                   4087: # domain
                   4088: # action: view, submit, grade
                   4089: # start: timestamp
                   4090: # end: timestamp
                   4091: #
1.240     www      4092:     my (%filters)=@_;
1.620     albertel 4093:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4094:     if ($filters{'url'}) {
                   4095: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4096:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4097:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4098:     }
1.620     albertel 4099:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4100:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4101:     return &log_query($cname,$cdom,'courselog',%filters);
                   4102: }
                   4103: 
                   4104: sub userlog_query {
                   4105:     my ($uname,$udom,%filters)=@_;
                   4106:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4107: }
                   4108: 
1.506     raeburn  4109: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4110: 
                   4111: sub auto_run {
1.508     raeburn  4112:     my ($cnum,$cdom) = @_;
                   4113:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4114:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4115:     return $response;
                   4116: }
1.776     albertel 4117: 
1.506     raeburn  4118: sub auto_get_sections {
1.508     raeburn  4119:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4120:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4121:     my @secs = ();
1.511     raeburn  4122:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4123:     unless ($response eq 'refused') {
                   4124:         @secs = split/:/,$response;
                   4125:     }
                   4126:     return @secs;
                   4127: }
1.776     albertel 4128: 
1.506     raeburn  4129: sub auto_new_course {
1.508     raeburn  4130:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4131:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4132:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4133:     return $response;
                   4134: }
1.776     albertel 4135: 
1.506     raeburn  4136: sub auto_validate_courseID {
1.508     raeburn  4137:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4138:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4139:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4140:     return $response;
                   4141: }
1.776     albertel 4142: 
1.506     raeburn  4143: sub auto_create_password {
1.508     raeburn  4144:     my ($cnum,$cdom,$authparam) = @_;
                   4145:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4146:     my $create_passwd = 0;
                   4147:     my $authchk = '';
1.511     raeburn  4148:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4149:     if ($response eq 'refused') {
                   4150:         $authchk = 'refused';
                   4151:     } else {
                   4152:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4153:     }
                   4154:     return ($authparam,$create_passwd,$authchk);
                   4155: }
                   4156: 
1.706     raeburn  4157: sub auto_photo_permission {
                   4158:     my ($cnum,$cdom,$students) = @_;
                   4159:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4160:     my ($outcome,$perm_reqd,$conditions) = 
                   4161: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4162:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4163: 	return (undef,undef);
                   4164:     }
1.706     raeburn  4165:     return ($outcome,$perm_reqd,$conditions);
                   4166: }
                   4167: 
                   4168: sub auto_checkphotos {
                   4169:     my ($uname,$udom,$pid) = @_;
                   4170:     my $homeserver = &homeserver($uname,$udom);
                   4171:     my ($result,$resulttype);
                   4172:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4173: 				   &escape($uname).':'.&escape($pid),
                   4174: 				   $homeserver));
1.709     albertel 4175:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4176: 	return (undef,undef);
                   4177:     }
1.706     raeburn  4178:     if ($outcome) {
                   4179:         ($result,$resulttype) = split(/:/,$outcome);
                   4180:     } 
                   4181:     return ($result,$resulttype);
                   4182: }
                   4183: 
                   4184: sub auto_photochoice {
                   4185:     my ($cnum,$cdom) = @_;
                   4186:     my $homeserver = &homeserver($cnum,$cdom);
                   4187:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4188: 						       &escape($cdom),
                   4189: 						       $homeserver)));
1.709     albertel 4190:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4191: 	return (undef,undef);
                   4192:     }
1.706     raeburn  4193:     return ($update,$comment);
                   4194: }
                   4195: 
                   4196: sub auto_photoupdate {
                   4197:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4198:     my $homeserver = &homeserver($cnum,$dom);
                   4199:     my $host=$hostname{$homeserver};
                   4200:     my $cmd = '';
                   4201:     my $maxtries = 1;
1.800   ! albertel 4202:     foreach my $affiliate (keys(%{$affiliatesref})) {
        !          4203:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4204:     }
                   4205:     $cmd =~ s/%%$//;
                   4206:     $cmd = &escape($cmd);
                   4207:     my $query = 'institutionalphotos';
                   4208:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4209:     unless ($queryid=~/^\Q$host\E\_/) {
                   4210:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4211:         return 'error: '.$queryid;
                   4212:     }
                   4213:     my $reply = &get_query_reply($queryid);
                   4214:     my $tries = 1;
                   4215:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4216:         $reply = &get_query_reply($queryid);
                   4217:         $tries ++;
                   4218:     }
                   4219:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4220:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4221:     } else {
                   4222:         my @responses = split(/:/,$reply);
                   4223:         my $outcome = shift(@responses); 
                   4224:         foreach my $item (@responses) {
                   4225:             my ($key,$value) = split(/=/,$item);
                   4226:             $$photo{$key} = $value;
                   4227:         }
                   4228:         return $outcome;
                   4229:     }
                   4230:     return 'error';
                   4231: }
                   4232: 
1.521     raeburn  4233: sub auto_instcode_format {
1.793     albertel 4234:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4235: 	$cat_order) = @_;
1.521     raeburn  4236:     my $courses = '';
1.772     raeburn  4237:     my @homeservers;
1.521     raeburn  4238:     if ($caller eq 'global') {
1.793     albertel 4239:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4240:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4241:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4242:                     push(@homeservers,$tryserver);
                   4243:                 }
1.584     raeburn  4244:             }
                   4245:         }
1.521     raeburn  4246:     } else {
1.772     raeburn  4247:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4248:     }
1.793     albertel 4249:     foreach my $code (keys(%{$instcodes})) {
                   4250:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4251:     }
                   4252:     chop($courses);
1.772     raeburn  4253:     my $ok_response = 0;
                   4254:     my $response;
                   4255:     while (@homeservers > 0 && $ok_response == 0) {
                   4256:         my $server = shift(@homeservers); 
                   4257:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4258:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4259:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4260: 		split/:/,$response;
1.772     raeburn  4261:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4262:             push(@{$codetitles},&str2array($codetitles_str));
                   4263:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4264:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4265:             $ok_response = 1;
                   4266:         }
                   4267:     }
                   4268:     if ($ok_response) {
1.521     raeburn  4269:         return 'ok';
1.772     raeburn  4270:     } else {
                   4271:         return $response;
1.521     raeburn  4272:     }
                   4273: }
                   4274: 
1.792     raeburn  4275: sub auto_instcode_defaults {
                   4276:     my ($domain,$returnhash,$code_order) = @_;
                   4277:     my @homeservers;
1.793     albertel 4278:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4279:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4280:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4281:                 push(@homeservers,$tryserver);
                   4282:             }
                   4283:         }
                   4284:     }
                   4285:     my $ok_response = 0;
                   4286:     my $response;
                   4287:     while (@homeservers > 0 && $ok_response == 0) {
                   4288:         my $server = shift(@homeservers);
                   4289:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4290:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4291:             foreach my $pair (split(/\&/,$response)) {
                   4292:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4293:                 if ($name eq 'code_order') {
1.796     raeburn  4294:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4295:                 } else {
1.796     raeburn  4296:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4297:                 }
                   4298:             }
                   4299:         }
                   4300:         $ok_response = 1;
                   4301:     }
                   4302:     if ($ok_response) {
                   4303:         return 'ok';
                   4304:     } else {
                   4305:         return $response;
                   4306:     }
                   4307: } 
                   4308: 
1.777     albertel 4309: sub auto_validate_class_sec {
1.773     raeburn  4310:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4311:     my $homeserver = &homeserver($cnum,$cdom);
                   4312:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4313:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4314:     return $response;
                   4315: }
                   4316: 
1.679     raeburn  4317: # ------------------------------------------------------- Course Group routines
                   4318: 
                   4319: sub get_coursegroups {
1.683     raeburn  4320:     my ($cdom,$cnum,$group) = @_;
                   4321:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4322: }
                   4323: 
                   4324: sub modify_coursegroup {
                   4325:     my ($cdom,$cnum,$groupsettings) = @_;
                   4326:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4327: }
                   4328: 
                   4329: sub modify_group_roles {
                   4330:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4331:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4332:     my $role = 'gr/'.&escape($userprivs);
                   4333:     my ($uname,$udom) = split(/:/,$user);
                   4334:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4335:     if ($result eq 'ok') {
                   4336:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4337:     }
1.679     raeburn  4338:     return $result;
                   4339: }
                   4340: 
                   4341: sub modify_coursegroup_membership {
                   4342:     my ($cdom,$cnum,$membership) = @_;
                   4343:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4344:     return $result;
                   4345: }
                   4346: 
1.682     raeburn  4347: sub get_active_groups {
                   4348:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4349:     my $now = time;
                   4350:     my %groups = ();
                   4351:     foreach my $key (keys(%env)) {
                   4352:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4353:             my ($start,$end) = split(/\./,$env{$key});
                   4354:             if (($end!=0) && ($end<$now)) { next; }
                   4355:             if (($start!=0) && ($start>$now)) { next; }
                   4356:             if ($1 eq $cdom && $2 eq $cnum) {
                   4357:                 $groups{$3} = $env{$key} ;
                   4358:             }
                   4359:         }
                   4360:     }
                   4361:     return %groups;
                   4362: }
                   4363: 
1.683     raeburn  4364: sub get_group_membership {
                   4365:     my ($cdom,$cnum,$group) = @_;
                   4366:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4367: }
                   4368: 
                   4369: sub get_users_groups {
                   4370:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4371:     my @usersgroups;
1.683     raeburn  4372:     my $cachetime=1800;
                   4373:     $courseid=~s/\_/\//g;
                   4374:     $courseid=~s/^(\w)/\/$1/;
                   4375: 
                   4376:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4377:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4378:     if (defined($cached)) {
1.734     albertel 4379:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4380:     } else {  
                   4381:         $grouplist = '';
                   4382:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4383:         my ($tmp) = keys(%roleshash);
                   4384:         if ($tmp=~/^error:/) {
                   4385:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4386:         } else {
                   4387:             my $access_end = $env{'course.'.$courseid.
                   4388:                                   '.default_enrollment_end_date'};
                   4389:             my $now = time;
1.734     albertel 4390:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4391:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4392:                     my $group = $1;
                   4393:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4394:                         my $start = $2;
                   4395:                         my $end = $1;
                   4396:                         if ($start == -1) { next; } # deleted from group
                   4397:                         if (($start!=0) && ($start>$now)) { next; }
                   4398:                         if (($end!=0) && ($end<$now)) {
                   4399:                             if ($access_end && $access_end < $now) {
                   4400:                                 if ($access_end - $end < 86400) {
                   4401:                                     push(@usersgroups,$group);
                   4402:                                 }
                   4403:                             }
                   4404:                             next;
                   4405:                         }
                   4406:                         push(@usersgroups,$group);
                   4407:                     }
1.683     raeburn  4408:                 }
                   4409:             }
1.733     raeburn  4410:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4411:             $grouplist = join(':',@usersgroups);
                   4412:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4413:         }
                   4414:     }
1.733     raeburn  4415:     return @usersgroups;
1.683     raeburn  4416: }
                   4417: 
                   4418: sub devalidate_getgroups_cache {
                   4419:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4420:     my $courseid = $cdom.'_'.$cnum;
                   4421:     $courseid=~s/\_/\//g;
                   4422:     $courseid=~s/^(\w)/\/$1/;
                   4423:     my $hashid="$udom:$uname:$courseid";
                   4424:     &devalidate_cache_new('getgroups',$hashid);
                   4425: }
                   4426: 
1.12      www      4427: # ------------------------------------------------------------------ Plain Text
                   4428: 
                   4429: sub plaintext {
1.742     raeburn  4430:     my ($short,$type,$cid) = @_;
1.758     albertel 4431:     if ($short =~ /^cr/) {
                   4432: 	return (split('/',$short))[-1];
                   4433:     }
1.742     raeburn  4434:     if (!defined($cid)) {
                   4435:         $cid = $env{'request.course.id'};
                   4436:     }
                   4437:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4438:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4439:                                           '.plaintext'});
                   4440:     }
                   4441:     my %rolenames = (
                   4442:                       Course => 'std',
                   4443:                       Group => 'alt1',
                   4444:                     );
                   4445:     if (defined($type) && 
                   4446:          defined($rolenames{$type}) && 
                   4447:          defined($prp{$short}{$rolenames{$type}})) {
                   4448:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4449:     } else {
                   4450:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4451:     }
1.12      www      4452: }
                   4453: 
                   4454: # ----------------------------------------------------------------- Assign Role
                   4455: 
                   4456: sub assignrole {
1.357     www      4457:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4458:     my $mrole;
                   4459:     if ($role =~ /^cr\//) {
1.393     www      4460:         my $cwosec=$url;
                   4461:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4462: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4463:            &logthis('Refused custom assignrole: '.
                   4464:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4465: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4466:            return 'refused'; 
                   4467:         }
1.21      www      4468:         $mrole='cr';
1.678     raeburn  4469:     } elsif ($role =~ /^gr\//) {
                   4470:         my $cwogrp=$url;
                   4471:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4472:         unless (&allowed('mdg',$cwogrp)) {
                   4473:             &logthis('Refused group assignrole: '.
                   4474:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4475:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4476:             return 'refused';
                   4477:         }
                   4478:         $mrole='gr';
1.21      www      4479:     } else {
1.82      www      4480:         my $cwosec=$url;
1.83      www      4481:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4482:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4483:            &logthis('Refused assignrole: '.
                   4484:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4485: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4486:            return 'refused'; 
                   4487:         }
1.21      www      4488:         $mrole=$role;
                   4489:     }
1.620     albertel 4490:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4491:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4492:     if ($end) { $command.='_'.$end; }
1.21      www      4493:     if ($start) {
                   4494: 	if ($end) { 
1.81      www      4495:            $command.='_'.$start; 
1.21      www      4496:         } else {
1.81      www      4497:            $command.='_0_'.$start;
1.21      www      4498:         }
                   4499:     }
1.739     raeburn  4500:     my $origstart = $start;
                   4501:     my $origend = $end;
1.357     www      4502: # actually delete
                   4503:     if ($deleteflag) {
1.373     www      4504: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4505: # modify command to delete the role
1.620     albertel 4506:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4507:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4508: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4509: # set start and finish to negative values for userrolelog
                   4510:            $start=-1;
                   4511:            $end=-1;
                   4512:         }
                   4513:     }
                   4514: # send command
1.349     www      4515:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4516: # log new user role if status is ok
1.349     www      4517:     if ($answer eq 'ok') {
1.663     raeburn  4518: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4519: # for course roles, perform group memberships changes triggered by role change.
                   4520:         unless ($role =~ /^gr/) {
                   4521:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4522:                                              $origstart);
                   4523:         }
1.349     www      4524:     }
                   4525:     return $answer;
1.169     harris41 4526: }
                   4527: 
                   4528: # -------------------------------------------------- Modify user authentication
1.197     www      4529: # Overrides without validation
                   4530: 
1.169     harris41 4531: sub modifyuserauth {
                   4532:     my ($udom,$uname,$umode,$upass)=@_;
                   4533:     my $uhome=&homeserver($uname,$udom);
1.197     www      4534:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4535:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4536:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4537:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4538:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4539: 		     &escape($upass),$uhome);
1.620     albertel 4540:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4541:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4542:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4543:     &log($udom,,$uname,$uhome,
1.620     albertel 4544:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4545:                                      $env{'user.name'}.', '.$umode.
1.197     www      4546:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4547:     unless ($reply eq 'ok') {
1.197     www      4548:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4549: 	return 'error: '.$reply;
                   4550:     }   
1.170     harris41 4551:     return 'ok';
1.80      www      4552: }
                   4553: 
1.81      www      4554: # --------------------------------------------------------------- Modify a user
1.80      www      4555: 
1.81      www      4556: sub modifyuser {
1.206     matthew  4557:     my ($udom,    $uname, $uid,
                   4558:         $umode,   $upass, $first,
                   4559:         $middle,  $last,  $gene,
1.387     www      4560:         $forceid, $desiredhome, $email)=@_;
1.198     www      4561:     $udom=~s/\W//g;
                   4562:     $uname=~s/\W//g;
1.81      www      4563:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4564:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4565: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4566:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4567:                                      ' desiredhome not specified'). 
1.620     albertel 4568:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4569:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4570:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4571: # ----------------------------------------------------------------- Create User
1.406     albertel 4572:     if (($uhome eq 'no_host') && 
                   4573: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4574:         my $unhome='';
1.209     matthew  4575:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4576:             $unhome = $desiredhome;
1.620     albertel 4577: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4578: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4579:         } else { # load balancing routine for determining $unhome
1.80      www      4580:             my $tryserver;
1.81      www      4581:             my $loadm=10000000;
1.80      www      4582:             foreach $tryserver (keys %libserv) {
                   4583: 	       if ($hostdom{$tryserver} eq $udom) {
                   4584:                   my $answer=reply('load',$tryserver);
                   4585:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4586: 		      $loadm=$answer;
                   4587:                       $unhome=$tryserver;
                   4588:                   }
                   4589: 	       }
                   4590: 	    }
                   4591:         }
                   4592:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4593: 	    return 'error: unable to find a home server for '.$uname.
                   4594:                    ' in domain '.$udom;
1.80      www      4595:         }
                   4596:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4597:                          &escape($upass),$unhome);
                   4598: 	unless ($reply eq 'ok') {
                   4599:             return 'error: '.$reply;
                   4600:         }   
1.230     stredwic 4601:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4602:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4603: 	    return 'error: unable verify users home machine.';
1.80      www      4604:         }
1.209     matthew  4605:     }   # End of creation of new user
1.80      www      4606: # ---------------------------------------------------------------------- Add ID
                   4607:     if ($uid) {
                   4608:        $uid=~tr/A-Z/a-z/;
                   4609:        my %uidhash=&idrget($udom,$uname);
1.196     www      4610:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4611:          && (!$forceid)) {
1.80      www      4612: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4613: 	      return 'error: user id "'.$uid.'" does not match '.
                   4614:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4615:           }
                   4616:        } else {
                   4617: 	  &idput($udom,($uname => $uid));
                   4618:        }
                   4619:     }
                   4620: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4621:     my @tmp=&get('environment',
1.134     albertel 4622: 		   ['firstname','middlename','lastname','generation'],
                   4623: 		   $udom,$uname);
1.313     matthew  4624:     my %names;
                   4625:     if ($tmp[0] =~ m/^error:.*/) { 
                   4626:         %names=(); 
                   4627:     } else {
                   4628:         %names = @tmp;
                   4629:     }
1.388     www      4630: #
                   4631: # Make sure to not trash student environment if instructor does not bother
                   4632: # to supply name and email information
                   4633: #
                   4634:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4635:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4636:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4637:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4638:     if ($email) {
                   4639:        $email=~s/[^\w\@\.\-\,]//gs;
                   4640:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4641: 			   $names{'critnotification'} = $email;
                   4642: 			   $names{'permanentemail'} = $email; }
                   4643:     }
1.134     albertel 4644:     my $reply = &put('environment', \%names, $udom,$uname);
                   4645:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4646:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4647:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4648:              $umode.', '.$first.', '.$middle.', '.
                   4649: 	     $last.', '.$gene.' by '.
1.620     albertel 4650:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4651:     return 'ok';
1.80      www      4652: }
                   4653: 
1.81      www      4654: # -------------------------------------------------------------- Modify student
1.80      www      4655: 
1.81      www      4656: sub modifystudent {
                   4657:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4658:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4659:     if (!$cid) {
1.620     albertel 4660: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4661: 	    return 'not_in_class';
                   4662: 	}
1.80      www      4663:     }
                   4664: # --------------------------------------------------------------- Make the user
1.81      www      4665:     my $reply=&modifyuser
1.209     matthew  4666: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4667:          $desiredhome,$email);
1.80      www      4668:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4669:     # This will cause &modify_student_enrollment to get the uid from the
                   4670:     # students environment
                   4671:     $uid = undef if (!$forceid);
1.455     albertel 4672:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4673: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4674:     return $reply;
                   4675: }
                   4676: 
                   4677: sub modify_student_enrollment {
1.515     raeburn  4678:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4679:     my ($cdom,$cnum,$chome);
                   4680:     if (!$cid) {
1.620     albertel 4681: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4682: 	    return 'not_in_class';
                   4683: 	}
1.620     albertel 4684: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4685: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4686:     } else {
                   4687: 	($cdom,$cnum)=split(/_/,$cid);
                   4688:     }
1.620     albertel 4689:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4690:     if (!$chome) {
1.457     raeburn  4691: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4692:     }
1.455     albertel 4693:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4694:     # Make sure the user exists
1.81      www      4695:     my $uhome=&homeserver($uname,$udom);
                   4696:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4697: 	return 'error: no such user';
                   4698:     }
1.297     matthew  4699:     # Get student data if we were not given enough information
                   4700:     if (!defined($first)  || $first  eq '' || 
                   4701:         !defined($last)   || $last   eq '' || 
                   4702:         !defined($uid)    || $uid    eq '' || 
                   4703:         !defined($middle) || $middle eq '' || 
                   4704:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4705:         # They did not supply us with enough data to enroll the student, so
                   4706:         # we need to pick up more information.
1.297     matthew  4707:         my %tmp = &get('environment',
1.294     matthew  4708:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4709:                        ,$udom,$uname);
                   4710: 
1.800   ! albertel 4711:         #foreach my $key (keys(%tmp)) {
        !          4712:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4713:         #}
1.294     matthew  4714:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4715:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4716:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4717:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4718:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4719:     }
1.556     albertel 4720:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4721:     my $reply=cput('classlist',
                   4722: 		   {"$uname:$udom" => 
1.515     raeburn  4723: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4724: 		   $cdom,$cnum);
1.81      www      4725:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4726: 	return 'error: '.$reply;
1.652     albertel 4727:     } else {
                   4728: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4729:     }
1.297     matthew  4730:     # Add student role to user
1.83      www      4731:     my $uurl='/'.$cid;
1.81      www      4732:     $uurl=~s/\_/\//g;
                   4733:     if ($usec) {
                   4734: 	$uurl.='/'.$usec;
                   4735:     }
                   4736:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4737: }
                   4738: 
1.556     albertel 4739: sub format_name {
                   4740:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4741:     my $name;
                   4742:     if ($first ne 'lastname') {
                   4743: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4744:     } else {
                   4745: 	if ($lastname=~/\S/) {
                   4746: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4747: 	    $name=~s/\s+,/,/;
                   4748: 	} else {
                   4749: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4750: 	}
                   4751:     }
                   4752:     $name=~s/^\s+//;
                   4753:     $name=~s/\s+$//;
                   4754:     $name=~s/\s+/ /g;
                   4755:     return $name;
                   4756: }
                   4757: 
1.84      www      4758: # ------------------------------------------------- Write to course preferences
                   4759: 
                   4760: sub writecoursepref {
                   4761:     my ($courseid,%prefs)=@_;
                   4762:     $courseid=~s/^\///;
                   4763:     $courseid=~s/\_/\//g;
                   4764:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4765:     my $chome=homeserver($cnum,$cdomain);
                   4766:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4767: 	return 'error: no such course';
                   4768:     }
                   4769:     my $cstring='';
1.800   ! albertel 4770:     foreach my $pref (keys(%prefs)) {
        !          4771: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4772:     }
1.84      www      4773:     $cstring=~s/\&$//;
                   4774:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4775: }
                   4776: 
                   4777: # ---------------------------------------------------------- Make/modify course
                   4778: 
                   4779: sub createcourse {
1.741     raeburn  4780:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4781:         $course_owner,$crstype)=@_;
1.84      www      4782:     $url=&declutter($url);
                   4783:     my $cid='';
1.264     matthew  4784:     unless (&allowed('ccc',$udom)) {
1.84      www      4785:         return 'refused';
                   4786:     }
                   4787: # ------------------------------------------------------------------- Create ID
1.674     www      4788:    my $uname=int(1+rand(9)).
                   4789:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4790:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4791:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4792: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4793:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4794:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4795:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4796:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4797:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4798:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4799:            return 'error: unable to generate unique course-ID';
                   4800:        } 
                   4801:    }
1.264     matthew  4802: # ------------------------------------------------ Check supplied server name
1.620     albertel 4803:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4804:     if (! exists($libserv{$course_server})) {
                   4805:         return 'error:bad server name '.$course_server;
                   4806:     }
1.84      www      4807: # ------------------------------------------------------------- Make the course
                   4808:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4809:                       $course_server);
1.84      www      4810:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4811:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4812:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4813: 	return 'error: no such course';
                   4814:     }
1.271     www      4815: # ----------------------------------------------------------------- Course made
1.516     raeburn  4816: # log existence
                   4817:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4818:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4819:                   &escape($crstype),$uhome);
1.358     www      4820:     &flushcourselogs();
                   4821: # set toplevel url
1.271     www      4822:     my $topurl=$url;
                   4823:     unless ($nonstandard) {
                   4824: # ------------------------------------------ For standard courses, make top url
                   4825:         my $mapurl=&clutter($url);
1.278     www      4826:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4827:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4828: <map>
                   4829: <resource id="1" type="start"></resource>
                   4830: <resource id="2" src="$mapurl"></resource>
                   4831: <resource id="3" type="finish"></resource>
                   4832: <link index="1" from="1" to="2"></link>
                   4833: <link index="2" from="2" to="3"></link>
                   4834: </map>
                   4835: ENDINITMAP
                   4836:         $topurl=&declutter(
1.638     albertel 4837:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4838:                           );
                   4839:     }
                   4840: # ----------------------------------------------------------- Write preferences
1.84      www      4841:     &writecoursepref($udom.'_'.$uname,
                   4842:                      ('description' => $description,
1.271     www      4843:                       'url'         => $topurl));
1.84      www      4844:     return '/'.$udom.'/'.$uname;
                   4845: }
                   4846: 
1.21      www      4847: # ---------------------------------------------------------- Assign Custom Role
                   4848: 
                   4849: sub assigncustomrole {
1.357     www      4850:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4851:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4852:                        $end,$start,$deleteflag);
1.21      www      4853: }
                   4854: 
                   4855: # ----------------------------------------------------------------- Revoke Role
                   4856: 
                   4857: sub revokerole {
1.357     www      4858:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4859:     my $now=time;
1.357     www      4860:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4861: }
                   4862: 
                   4863: # ---------------------------------------------------------- Revoke Custom Role
                   4864: 
                   4865: sub revokecustomrole {
1.357     www      4866:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4867:     my $now=time;
1.357     www      4868:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4869:            $deleteflag);
1.17      www      4870: }
                   4871: 
1.533     banghart 4872: # ------------------------------------------------------------ Disk usage
1.535     albertel 4873: sub diskusage {
1.533     banghart 4874:     my ($udom,$uname,$directoryRoot)=@_;
                   4875:     $directoryRoot =~ s/\/$//;
1.535     albertel 4876:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4877:     return $listing;
1.512     banghart 4878: }
                   4879: 
1.566     banghart 4880: sub is_locked {
                   4881:     my ($file_name, $domain, $user) = @_;
                   4882:     my @check;
                   4883:     my $is_locked;
                   4884:     push @check, $file_name;
1.613     albertel 4885:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4886: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4887:     my ($tmp)=keys(%locked);
                   4888:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4889:     
1.566     banghart 4890:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4891:         $is_locked = 'false';
                   4892:         foreach my $entry (@{$locked{$file_name}}) {
                   4893:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4894:                $is_locked = 'true';
                   4895:                last;
1.745     raeburn  4896:            }
                   4897:        }
1.566     banghart 4898:     } else {
                   4899:         $is_locked = 'false';
                   4900:     }
                   4901: }
                   4902: 
1.759     albertel 4903: sub declutter_portfile {
                   4904:     my ($file) = @_;
                   4905:     &logthis("got $file");
                   4906:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4907:     &logthis("ret $file");
                   4908:     return $file;
                   4909: }
                   4910: 
1.559     banghart 4911: # ------------------------------------------------------------- Mark as Read Only
                   4912: 
                   4913: sub mark_as_readonly {
                   4914:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4915:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4916:     my ($tmp)=keys(%current_permissions);
                   4917:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4918:     foreach my $file (@{$files}) {
1.759     albertel 4919: 	$file = &declutter_portfile($file);
1.561     banghart 4920:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4921:     }
1.613     albertel 4922:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4923:     return;
                   4924: }
                   4925: 
1.572     banghart 4926: # ------------------------------------------------------------Save Selected Files
                   4927: 
                   4928: sub save_selected_files {
                   4929:     my ($user, $path, @files) = @_;
                   4930:     my $filename = $user."savedfiles";
1.573     banghart 4931:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4932:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4933:     foreach my $file (@files) {
1.620     albertel 4934:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4935:     }
                   4936:     foreach my $file (@other_files) {
1.574     banghart 4937:         print (OUT $file."\n");
1.572     banghart 4938:     }
1.574     banghart 4939:     close (OUT);
1.572     banghart 4940:     return 'ok';
                   4941: }
                   4942: 
1.574     banghart 4943: sub clear_selected_files {
                   4944:     my ($user) = @_;
                   4945:     my $filename = $user."savedfiles";
                   4946:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4947:     print (OUT undef);
                   4948:     close (OUT);
                   4949:     return ("ok");    
                   4950: }
                   4951: 
1.572     banghart 4952: sub files_in_path {
                   4953:     my ($user, $path) = @_;
                   4954:     my $filename = $user."savedfiles";
                   4955:     my %return_files;
1.574     banghart 4956:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4957:     while (my $line_in = <IN>) {
1.574     banghart 4958:         chomp ($line_in);
                   4959:         my @paths_and_file = split (m!/!, $line_in);
                   4960:         my $file_part = pop (@paths_and_file);
                   4961:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4962:         $path_part.='/';
                   4963:         my $path_and_file = $path_part.$file_part;
                   4964:         if ($path_part eq $path) {
                   4965:             $return_files{$file_part}= 'selected';
                   4966:         }
                   4967:     }
1.574     banghart 4968:     close (IN);
                   4969:     return (\%return_files);
1.572     banghart 4970: }
                   4971: 
                   4972: # called in portfolio select mode, to show files selected NOT in current directory
                   4973: sub files_not_in_path {
                   4974:     my ($user, $path) = @_;
                   4975:     my $filename = $user."savedfiles";
                   4976:     my @return_files;
                   4977:     my $path_part;
1.800   ! albertel 4978:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
        !          4979:     while (my $line = <IN>) {
1.572     banghart 4980:         #ok, I know it's clunky, but I want it to work
1.800   ! albertel 4981:         my @paths_and_file = split(m|/|, $line);
        !          4982:         my $file_part = pop(@paths_and_file);
        !          4983:         chomp($file_part);
        !          4984:         my $path_part = join('/', @paths_and_file);
1.572     banghart 4985:         $path_part .= '/';
                   4986:         my $path_and_file = $path_part.$file_part;
                   4987:         if ($path_part ne $path) {
1.800   ! albertel 4988:             push(@return_files, ($path_and_file));
1.572     banghart 4989:         }
                   4990:     }
1.800   ! albertel 4991:     close(OUT);
1.574     banghart 4992:     return (@return_files);
1.572     banghart 4993: }
                   4994: 
1.745     raeburn  4995: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4996: 
1.745     raeburn  4997: sub get_portfile_permissions {
                   4998:     my ($domain,$user) = @_;
1.613     albertel 4999:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5000:     my ($tmp)=keys(%current_permissions);
                   5001:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5002:     return \%current_permissions;
                   5003: }
                   5004: 
                   5005: #---------------------------------------------Get portfolio file access controls
                   5006: 
1.749     raeburn  5007: sub get_access_controls {
1.745     raeburn  5008:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5009:     my %access;
                   5010:     my $real_file = $file;
                   5011:     $file =~ s/\.meta$//;
1.745     raeburn  5012:     if (defined($file)) {
1.749     raeburn  5013:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5014:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5015:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5016:             }
                   5017:         }
1.745     raeburn  5018:     } else {
1.749     raeburn  5019:         foreach my $key (keys(%{$current_permissions})) {
                   5020:             if ($key =~ /\0accesscontrol$/) {
                   5021:                 if (defined($group)) {
                   5022:                     if ($key !~ m-^\Q$group\E/-) {
                   5023:                         next;
                   5024:                     }
                   5025:                 }
                   5026:                 my ($fullpath) = split(/\0/,$key);
                   5027:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5028:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5029:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5030:                     }
                   5031:                 }
                   5032:             }
                   5033:         }
                   5034:     }
                   5035:     return %access;
                   5036: }
                   5037: 
                   5038: sub modify_access_controls {
                   5039:     my ($file_name,$changes,$domain,$user)=@_;
                   5040:     my ($outcome,$deloutcome);
                   5041:     my %store_permissions;
                   5042:     my %new_values;
                   5043:     my %new_control;
                   5044:     my %translation;
                   5045:     my @deletions = ();
                   5046:     my $now = time;
                   5047:     if (exists($$changes{'activate'})) {
                   5048:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5049:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5050:             my $numnew = scalar(@newitems);
                   5051:             for (my $i=0; $i<$numnew; $i++) {
                   5052:                 my $newkey = $newitems[$i];
                   5053:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5054:                 if ($newkey =~ /^\d+:/) { 
                   5055:                     $newkey =~ s/^(\d+)/$newid/;
                   5056:                     $translation{$1} = $newid;
                   5057:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5058:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5059:                     $translation{$1} = $newid;
                   5060:                 }
1.749     raeburn  5061:                 $new_values{$file_name."\0".$newkey} = 
                   5062:                                           $$changes{'activate'}{$newitems[$i]};
                   5063:                 $new_control{$newkey} = $now;
                   5064:             }
                   5065:         }
                   5066:     }
                   5067:     my %todelete;
                   5068:     my %changed_items;
                   5069:     foreach my $action ('delete','update') {
                   5070:         if (exists($$changes{$action})) {
                   5071:             if (ref($$changes{$action}) eq 'HASH') {
                   5072:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5073:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5074:                     if ($action eq 'delete') { 
                   5075:                         $todelete{$itemnum} = 1;
                   5076:                     } else {
                   5077:                         $changed_items{$itemnum} = $key;
                   5078:                     }
                   5079:                 }
1.745     raeburn  5080:             }
                   5081:         }
1.749     raeburn  5082:     }
                   5083:     # get lock on access controls for file.
                   5084:     my $lockhash = {
                   5085:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5086:                                                        ':'.$env{'user.domain'},
                   5087:                    }; 
                   5088:     my $tries = 0;
                   5089:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5090:    
                   5091:     while (($gotlock ne 'ok') && $tries <3) {
                   5092:         $tries ++;
                   5093:         sleep 1;
                   5094:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5095:     }
                   5096:     if ($gotlock eq 'ok') {
                   5097:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5098:         my ($tmp)=keys(%curr_permissions);
                   5099:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5100:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5101:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5102:             if (ref($curr_controls) eq 'HASH') {
                   5103:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5104:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5105:                     if (defined($todelete{$itemnum})) {
                   5106:                         push(@deletions,$file_name."\0".$control_item);
                   5107:                     } else {
                   5108:                         if (defined($changed_items{$itemnum})) {
                   5109:                             $new_control{$changed_items{$itemnum}} = $now;
                   5110:                             push(@deletions,$file_name."\0".$control_item);
                   5111:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5112:                         } else {
                   5113:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5114:                         }
                   5115:                     }
1.745     raeburn  5116:                 }
                   5117:             }
                   5118:         }
1.749     raeburn  5119:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5120:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5121:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5122:         #  remove lock
                   5123:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5124:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5125:     } else {
                   5126:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5127:     }
1.749     raeburn  5128:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5129: }
                   5130: 
                   5131: #------------------------------------------------------Get Marked as Read Only
                   5132: 
                   5133: sub get_marked_as_readonly {
                   5134:     my ($domain,$user,$what,$group) = @_;
                   5135:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5136:     my @readonly_files;
1.629     banghart 5137:     my $cmp1=$what;
                   5138:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5139:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5140:         if (defined($group)) {
                   5141:             if ($file_name !~ m-^\Q$group\E/-) {
                   5142:                 next;
                   5143:             }
                   5144:         }
1.561     banghart 5145:         if (ref($value) eq "ARRAY"){
                   5146:             foreach my $stored_what (@{$value}) {
1.629     banghart 5147:                 my $cmp2=$stored_what;
1.759     albertel 5148:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5149:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5150:                 }
1.629     banghart 5151:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5152:                     push(@readonly_files, $file_name);
1.745     raeburn  5153:                     last;
1.563     banghart 5154:                 } elsif (!defined($what)) {
                   5155:                     push(@readonly_files, $file_name);
1.745     raeburn  5156:                     last;
1.561     banghart 5157:                 }
                   5158:             }
1.745     raeburn  5159:         }
1.561     banghart 5160:     }
                   5161:     return @readonly_files;
                   5162: }
1.577     banghart 5163: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5164: 
1.577     banghart 5165: sub get_marked_as_readonly_hash {
1.745     raeburn  5166:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5167:     my %readonly_files;
1.745     raeburn  5168:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5169:         if (defined($group)) {
                   5170:             if ($file_name !~ m-^\Q$group\E/-) {
                   5171:                 next;
                   5172:             }
                   5173:         }
1.577     banghart 5174:         if (ref($value) eq "ARRAY"){
                   5175:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5176:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5177:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5178:                         if ($lock_descriptor eq 'graded') {
                   5179:                             $readonly_files{$file_name} = 'graded';
                   5180:                         } elsif ($lock_descriptor eq 'handback') {
                   5181:                             $readonly_files{$file_name} = 'handback';
                   5182:                         } else {
                   5183:                             if (!exists($readonly_files{$file_name})) {
                   5184:                                 $readonly_files{$file_name} = 'locked';
                   5185:                             }
                   5186:                         }
1.745     raeburn  5187:                     }
1.750     banghart 5188:                 } 
1.577     banghart 5189:             }
                   5190:         } 
                   5191:     }
                   5192:     return %readonly_files;
                   5193: }
1.559     banghart 5194: # ------------------------------------------------------------ Unmark as Read Only
                   5195: 
                   5196: sub unmark_as_readonly {
1.629     banghart 5197:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5198:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5199:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5200:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5201:     my $symb_crs = $what;
                   5202:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5203:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5204:     my ($tmp)=keys(%current_permissions);
                   5205:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5206:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5207:     foreach my $file (@readonly_files) {
1.759     albertel 5208: 	my $clean_file = &declutter_portfile($file);
                   5209: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5210: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5211:         my @new_locks;
                   5212:         my @del_keys;
                   5213:         if (ref($current_locks) eq "ARRAY"){
                   5214:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5215:                 my $compare=$locker;
1.749     raeburn  5216:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5217:                     $compare=join('',@{$locker});
1.746     raeburn  5218:                     if ($compare ne $symb_crs) {
                   5219:                         push(@new_locks, $locker);
                   5220:                     }
1.563     banghart 5221:                 }
                   5222:             }
1.650     albertel 5223:             if (scalar(@new_locks) > 0) {
1.563     banghart 5224:                 $current_permissions{$file} = \@new_locks;
                   5225:             } else {
                   5226:                 push(@del_keys, $file);
1.613     albertel 5227:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5228:                 delete($current_permissions{$file});
1.563     banghart 5229:             }
                   5230:         }
1.561     banghart 5231:     }
1.613     albertel 5232:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5233:     return;
                   5234: }
1.512     banghart 5235: 
1.17      www      5236: # ------------------------------------------------------------ Directory lister
                   5237: 
                   5238: sub dirlist {
1.253     stredwic 5239:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5240: 
1.18      www      5241:     $uri=~s/^\///;
                   5242:     $uri=~s/\/$//;
1.253     stredwic 5243:     my ($udom, $uname);
                   5244:     (undef,$udom,$uname)=split(/\//,$uri);
                   5245:     if(defined($userdomain)) {
                   5246:         $udom = $userdomain;
                   5247:     }
                   5248:     if(defined($username)) {
                   5249:         $uname = $username;
                   5250:     }
                   5251: 
                   5252:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5253:     if(defined($alternateDirectoryRoot)) {
                   5254:         $dirRoot = $alternateDirectoryRoot;
                   5255:         $dirRoot =~ s/\/$//;
1.751     banghart 5256:     }
1.253     stredwic 5257: 
                   5258:     if($udom) {
                   5259:         if($uname) {
1.800   ! albertel 5260:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
        !          5261: 				 &homeserver($uname,$udom));
1.605     matthew  5262:             my @listing_results;
                   5263:             if ($listing eq 'unknown_cmd') {
1.800   ! albertel 5264:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
        !          5265: 				  &homeserver($uname,$udom));
1.605     matthew  5266:                 @listing_results = split(/:/,$listing);
                   5267:             } else {
                   5268:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5269:             }
                   5270:             return @listing_results;
1.253     stredwic 5271:         } elsif(!defined($alternateDirectoryRoot)) {
1.800   ! albertel 5272:             my %allusers;
        !          5273:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5274:                 if($hostdom{$tryserver} eq $udom) {
1.800   ! albertel 5275:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
        !          5276: 					 $udom, $tryserver);
1.605     matthew  5277:                     my @listing_results;
                   5278:                     if ($listing eq 'unknown_cmd') {
1.800   ! albertel 5279:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
        !          5280: 					  $udom, $tryserver);
1.605     matthew  5281:                         @listing_results = split(/:/,$listing);
                   5282:                     } else {
                   5283:                         @listing_results =
                   5284:                             map { &unescape($_); } split(/:/,$listing);
                   5285:                     }
                   5286:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5287:                         $listing_results[0] ne 'empty'       &&
                   5288:                         $listing_results[0] ne 'con_lost') {
1.800   ! albertel 5289:                         foreach my $line (@listing_results) {
        !          5290:                             my ($entry) = split(/&/,$line,2);
        !          5291:                             $allusers{$entry} = 1;
1.253     stredwic 5292:                         }
                   5293:                     }
1.191     harris41 5294:                 }
1.253     stredwic 5295:             }
                   5296:             my $alluserstr='';
1.800   ! albertel 5297:             foreach my $user (sort(keys(%allusers))) {
        !          5298:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5299:             }
                   5300:             $alluserstr=~s/:$//;
                   5301:             return split(/:/,$alluserstr);
                   5302:         } else {
1.800   ! albertel 5303:             return ('missing user name');
1.253     stredwic 5304:         }
                   5305:     } elsif(!defined($alternateDirectoryRoot)) {
                   5306:         my $tryserver;
                   5307:         my %alldom=();
1.800   ! albertel 5308:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5309:             $alldom{$hostdom{$tryserver}}=1;
                   5310:         }
                   5311:         my $alldomstr='';
1.800   ! albertel 5312:         foreach my $domain (sort(keys(%alldom))) {
        !          5313:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5314:         }
                   5315:         $alldomstr=~s/:$//;
                   5316:         return split(/:/,$alldomstr);       
                   5317:     } else {
1.800   ! albertel 5318:         return ('missing domain');
1.275     stredwic 5319:     }
                   5320: }
                   5321: 
                   5322: # --------------------------------------------- GetFileTimestamp
                   5323: # This function utilizes dirlist and returns the date stamp for
                   5324: # when it was last modified.  It will also return an error of -1
                   5325: # if an error occurs
                   5326: 
1.410     matthew  5327: ##
                   5328: ## FIXME: This subroutine assumes its caller knows something about the
                   5329: ## directory structure of the home server for the student ($root).
                   5330: ## Not a good assumption to make.  Since this is for looking up files
                   5331: ## in user directories, the full path should be constructed by lond, not
                   5332: ## whatever machine we request data from.
                   5333: ##
1.275     stredwic 5334: sub GetFileTimestamp {
                   5335:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5336:     $studentDomain=~s/\W//g;
                   5337:     $studentName=~s/\W//g;
                   5338:     my $subdir=$studentName.'__';
                   5339:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5340:     my $proname="$studentDomain/$subdir/$studentName";
                   5341:     $proname .= '/'.$filename;
1.375     matthew  5342:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5343:                                               $studentName, $root);
1.275     stredwic 5344:     my @stats = split('&', $fileStat);
                   5345:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5346:         # @stats contains first the filename, then the stat output
                   5347:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5348:     } else {
                   5349:         return -1;
1.253     stredwic 5350:     }
1.26      www      5351: }
                   5352: 
1.712     albertel 5353: sub stat_file {
                   5354:     my ($uri) = @_;
1.787     albertel 5355:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5356: 
1.712     albertel 5357:     my ($udom,$uname,$file,$dir);
                   5358:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5359: 	($udom,$uname,$file) =
                   5360: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5361: 	$file = 'userfiles/'.$file;
1.740     www      5362: 	$dir = &propath($udom,$uname);
1.712     albertel 5363:     }
                   5364:     if ($uri =~ m-^/res/-) {
                   5365: 	($udom,$uname) = 
                   5366: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5367: 	$file = $uri;
                   5368:     }
                   5369: 
                   5370:     if (!$udom || !$uname || !$file) {
                   5371: 	# unable to handle the uri
                   5372: 	return ();
                   5373:     }
                   5374: 
                   5375:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5376:     my @stats = split('&', $result);
1.721     banghart 5377:     
1.712     albertel 5378:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5379: 	shift(@stats); #filename is first
                   5380: 	return @stats;
                   5381:     }
                   5382:     return ();
                   5383: }
                   5384: 
1.26      www      5385: # -------------------------------------------------------- Value of a Condition
                   5386: 
1.713     albertel 5387: # gets the value of a specific preevaluated condition
                   5388: #    stored in the string  $env{user.state.<cid>}
                   5389: # or looks up a condition reference in the bighash and if if hasn't
                   5390: # already been evaluated recurses into docondval to get the value of
                   5391: # the condition, then memoizing it to 
                   5392: #   $env{user.state.<cid>.<condition>}
1.40      www      5393: sub directcondval {
                   5394:     my $number=shift;
1.620     albertel 5395:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5396: 	&Apache::lonuserstate::evalstate();
                   5397:     }
1.713     albertel 5398:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5399: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5400:     } elsif ($number =~ /^_/) {
                   5401: 	my $sub_condition;
                   5402: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5403: 		&GDBM_READER(),0640)) {
                   5404: 	    $sub_condition=$bighash{'conditions'.$number};
                   5405: 	    untie(%bighash);
                   5406: 	}
                   5407: 	my $value = &docondval($sub_condition);
                   5408: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5409: 	return $value;
                   5410:     }
1.620     albertel 5411:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5412:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5413:     } else {
                   5414:        return 2;
                   5415:     }
                   5416: }
                   5417: 
1.713     albertel 5418: # get the collection of conditions for this resource
1.26      www      5419: sub condval {
                   5420:     my $condidx=shift;
1.54      www      5421:     my $allpathcond='';
1.713     albertel 5422:     foreach my $cond (split(/\|/,$condidx)) {
                   5423: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5424: 	    $allpathcond.=
                   5425: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5426: 	}
1.191     harris41 5427:     }
1.54      www      5428:     $allpathcond=~s/\|$//;
1.713     albertel 5429:     return &docondval($allpathcond);
                   5430: }
                   5431: 
                   5432: #evaluates an expression of conditions
                   5433: sub docondval {
                   5434:     my ($allpathcond) = @_;
                   5435:     my $result=0;
                   5436:     if ($env{'request.course.id'}
                   5437: 	&& defined($allpathcond)) {
                   5438: 	my $operand='|';
                   5439: 	my @stack;
                   5440: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5441: 	    if ($chunk eq '(') {
                   5442: 		push @stack,($operand,$result);
                   5443: 	    } elsif ($chunk eq ')') {
                   5444: 		my $before=pop @stack;
                   5445: 		if (pop @stack eq '&') {
                   5446: 		    $result=$result>$before?$before:$result;
                   5447: 		} else {
                   5448: 		    $result=$result>$before?$result:$before;
                   5449: 		}
                   5450: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5451: 		$operand=$chunk;
                   5452: 	    } else {
                   5453: 		my $new=directcondval($chunk);
                   5454: 		if ($operand eq '&') {
                   5455: 		    $result=$result>$new?$new:$result;
                   5456: 		} else {
                   5457: 		    $result=$result>$new?$result:$new;
                   5458: 		}
                   5459: 	    }
                   5460: 	}
1.26      www      5461:     }
                   5462:     return $result;
1.421     albertel 5463: }
                   5464: 
                   5465: # ---------------------------------------------------- Devalidate courseresdata
                   5466: 
                   5467: sub devalidatecourseresdata {
                   5468:     my ($coursenum,$coursedomain)=@_;
                   5469:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5470:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5471: }
                   5472: 
1.763     www      5473: 
1.200     www      5474: # --------------------------------------------------- Course Resourcedata Query
                   5475: 
1.624     albertel 5476: sub get_courseresdata {
                   5477:     my ($coursenum,$coursedomain)=@_;
1.200     www      5478:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5479:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5480:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5481:     my %dumpreply;
1.417     albertel 5482:     unless (defined($cached)) {
1.624     albertel 5483: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5484: 	$result=\%dumpreply;
1.251     albertel 5485: 	my ($tmp) = keys(%dumpreply);
                   5486: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5487: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5488: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5489: 	    return $tmp;
1.416     albertel 5490: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5491: 	    $result=undef;
1.599     albertel 5492: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5493: 	}
                   5494:     }
1.624     albertel 5495:     return $result;
                   5496: }
                   5497: 
1.633     albertel 5498: sub devalidateuserresdata {
                   5499:     my ($uname,$udom)=@_;
                   5500:     my $hashid="$udom:$uname";
                   5501:     &devalidate_cache_new('userres',$hashid);
                   5502: }
                   5503: 
1.624     albertel 5504: sub get_userresdata {
                   5505:     my ($uname,$udom)=@_;
                   5506:     #most student don\'t have any data set, check if there is some data
                   5507:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5508: 
                   5509:     my $hashid="$udom:$uname";
                   5510:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5511:     if (!defined($cached)) {
                   5512: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5513: 	$result=\%resourcedata;
                   5514: 	&do_cache_new('userres',$hashid,$result,600);
                   5515:     }
                   5516:     my ($tmp)=keys(%$result);
                   5517:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5518: 	return $result;
                   5519:     }
                   5520:     #error 2 occurs when the .db doesn't exist
                   5521:     if ($tmp!~/error: 2 /) {
1.672     albertel 5522: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5523: 		 " Trying to get resource data for ".
                   5524: 		 $uname." at ".$udom.": ".
                   5525: 		 $tmp."</font>");
                   5526:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5527: 	#&EXT_cache_set($udom,$uname);
                   5528: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5529: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5530:     }
                   5531:     return $tmp;
                   5532: }
                   5533: 
                   5534: sub resdata {
                   5535:     my ($name,$domain,$type,@which)=@_;
                   5536:     my $result;
                   5537:     if ($type eq 'course') {
                   5538: 	$result=&get_courseresdata($name,$domain);
                   5539:     } elsif ($type eq 'user') {
                   5540: 	$result=&get_userresdata($name,$domain);
                   5541:     }
                   5542:     if (!ref($result)) { return $result; }    
1.251     albertel 5543:     foreach my $item (@which) {
1.417     albertel 5544: 	if (defined($result->{$item})) {
                   5545: 	    return $result->{$item};
1.251     albertel 5546: 	}
1.250     albertel 5547:     }
1.291     albertel 5548:     return undef;
1.200     www      5549: }
                   5550: 
1.379     matthew  5551: #
                   5552: # EXT resource caching routines
                   5553: #
                   5554: 
                   5555: sub clear_EXT_cache_status {
1.383     albertel 5556:     &delenv('cache.EXT.');
1.379     matthew  5557: }
                   5558: 
                   5559: sub EXT_cache_status {
                   5560:     my ($target_domain,$target_user) = @_;
1.383     albertel 5561:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5562:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5563:         # We know already the user has no data
                   5564:         return 1;
                   5565:     } else {
                   5566:         return 0;
                   5567:     }
                   5568: }
                   5569: 
                   5570: sub EXT_cache_set {
                   5571:     my ($target_domain,$target_user) = @_;
1.383     albertel 5572:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5573:     #&appenv($cachename => time);
1.379     matthew  5574: }
                   5575: 
1.28      www      5576: # --------------------------------------------------------- Value of a Variable
1.58      www      5577: sub EXT {
1.715     albertel 5578: 
1.395     albertel 5579:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5580:     unless ($varname) { return ''; }
1.218     albertel 5581:     #get real user name/domain, courseid and symb
                   5582:     my $courseid;
1.359     albertel 5583:     my $publicuser;
1.427     www      5584:     if ($symbparm) {
                   5585: 	$symbparm=&get_symb_from_alias($symbparm);
                   5586:     }
1.218     albertel 5587:     if (!($uname && $udom)) {
1.790     albertel 5588:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5589:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5590:     } else {
1.620     albertel 5591: 	$courseid=$env{'request.course.id'};
1.218     albertel 5592:     }
1.48      www      5593:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5594:     my $rest;
1.320     albertel 5595:     if (defined($therest[0])) {
1.48      www      5596:        $rest=join('.',@therest);
                   5597:     } else {
                   5598:        $rest='';
                   5599:     }
1.320     albertel 5600: 
1.57      www      5601:     my $qualifierrest=$qualifier;
                   5602:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5603:     my $spacequalifierrest=$space;
                   5604:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5605:     if ($realm eq 'user') {
1.48      www      5606: # --------------------------------------------------------------- user.resource
                   5607: 	if ($space eq 'resource') {
1.651     albertel 5608: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5609: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5610: 		 &&
1.744     albertel 5611: 		 ($symbparm eq &symbread()) ) {	
                   5612: 		# if we are in the middle of processing the resource the
                   5613: 		# get the value we are planning on committing
                   5614:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5615:                     return $Apache::lonhomework::results{$qualifierrest};
                   5616:                 } else {
                   5617:                     return $Apache::lonhomework::history{$qualifierrest};
                   5618:                 }
1.335     albertel 5619: 	    } else {
1.359     albertel 5620: 		my %restored;
1.620     albertel 5621: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5622: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5623: 		} else {
                   5624: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5625: 		}
1.335     albertel 5626: 		return $restored{$qualifierrest};
                   5627: 	    }
1.48      www      5628: # ----------------------------------------------------------------- user.access
                   5629:         } elsif ($space eq 'access') {
1.218     albertel 5630: 	    # FIXME - not supporting calls for a specific user
1.48      www      5631:             return &allowed($qualifier,$rest);
                   5632: # ------------------------------------------ user.preferences, user.environment
                   5633:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5634: 	    if (($uname eq $env{'user.name'}) &&
                   5635: 		($udom eq $env{'user.domain'})) {
                   5636: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5637: 	    } else {
1.359     albertel 5638: 		my %returnhash;
                   5639: 		if (!$publicuser) {
                   5640: 		    %returnhash=&userenvironment($udom,$uname,
                   5641: 						 $qualifierrest);
                   5642: 		}
1.218     albertel 5643: 		return $returnhash{$qualifierrest};
                   5644: 	    }
1.48      www      5645: # ----------------------------------------------------------------- user.course
                   5646:         } elsif ($space eq 'course') {
1.218     albertel 5647: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5648:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5649: # ------------------------------------------------------------------- user.role
                   5650:         } elsif ($space eq 'role') {
1.218     albertel 5651: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5652:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5653:             if ($qualifier eq 'value') {
                   5654: 		return $role;
                   5655:             } elsif ($qualifier eq 'extent') {
                   5656:                 return $where;
                   5657:             }
                   5658: # ----------------------------------------------------------------- user.domain
                   5659:         } elsif ($space eq 'domain') {
1.218     albertel 5660:             return $udom;
1.48      www      5661: # ------------------------------------------------------------------- user.name
                   5662:         } elsif ($space eq 'name') {
1.218     albertel 5663:             return $uname;
1.48      www      5664: # ---------------------------------------------------- Any other user namespace
1.29      www      5665:         } else {
1.359     albertel 5666: 	    my %reply;
                   5667: 	    if (!$publicuser) {
                   5668: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5669: 	    }
                   5670: 	    return $reply{$qualifierrest};
1.48      www      5671:         }
1.236     www      5672:     } elsif ($realm eq 'query') {
                   5673: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5674:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5675: 						[$spacequalifierrest]);
1.620     albertel 5676: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5677:    } elsif ($realm eq 'request') {
1.48      www      5678: # ------------------------------------------------------------- request.browser
                   5679:         if ($space eq 'browser') {
1.430     www      5680: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5681: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5682: 		    return 1;
                   5683: 		} else {
                   5684: 		    return 0;
                   5685: 		}
                   5686: 	    } else {
1.620     albertel 5687: 		return $env{'browser.'.$qualifier};
1.430     www      5688: 	    }
1.57      www      5689: # ------------------------------------------------------------ request.filename
                   5690:         } else {
1.620     albertel 5691:             return $env{'request.'.$spacequalifierrest};
1.29      www      5692:         }
1.28      www      5693:     } elsif ($realm eq 'course') {
1.48      www      5694: # ---------------------------------------------------------- course.description
1.620     albertel 5695:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5696:     } elsif ($realm eq 'resource') {
1.165     www      5697: 
1.620     albertel 5698: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5699: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5700: 	}
1.693     albertel 5701: 
                   5702: 	if ($space eq 'title') {
                   5703: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5704: 	    return &gettitle($symbparm);
                   5705: 	}
                   5706: 	
                   5707: 	if ($space eq 'map') {
                   5708: 	    my ($map) = &decode_symb($symbparm);
                   5709: 	    return &symbread($map);
                   5710: 	}
                   5711: 
                   5712: 	my ($section, $group, @groups);
1.593     albertel 5713: 	my ($courselevelm,$courselevel);
1.539     albertel 5714: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5715: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5716: 
1.218     albertel 5717: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5718: 
1.60      www      5719: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5720: 	    my $symbp=$symbparm;
1.735     albertel 5721: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5722: 
                   5723: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5724: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5725: 
1.620     albertel 5726: 	    if (($env{'user.name'} eq $uname) &&
                   5727: 		($env{'user.domain'} eq $udom)) {
                   5728: 		$section=$env{'request.course.sec'};
1.733     raeburn  5729:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5730:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5731: 	    } else {
1.539     albertel 5732: 		if (! defined($usection)) {
1.551     albertel 5733: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5734: 		} else {
                   5735: 		    $section = $usection;
                   5736: 		}
1.733     raeburn  5737:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5738: 	    }
                   5739: 
                   5740: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5741: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5742: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5743: 
1.593     albertel 5744: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5745: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5746: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5747: 
1.60      www      5748: # ----------------------------------------------------------- first, check user
1.624     albertel 5749: 
                   5750: 	    my $userreply=&resdata($uname,$udom,'user',
                   5751: 				       ($courselevelr,$courselevelm,
                   5752: 					$courselevel));
                   5753: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5754: 
1.594     albertel 5755: # ------------------------------------------------ second, check some of course
1.684     raeburn  5756:             my $coursereply;
1.691     raeburn  5757:             if (@groups > 0) {
                   5758:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5759:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5760:                 if (defined($coursereply)) { return $coursereply; }
                   5761:             }
1.96      www      5762: 
1.684     raeburn  5763: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5764: 				     $env{'course.'.$courseid.'.domain'},
                   5765: 				     'course',
                   5766: 				     ($seclevelr,$seclevelm,$seclevel,
                   5767: 				      $courselevelr));
1.287     albertel 5768: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5769: 
1.60      www      5770: # ------------------------------------------------------ third, check map parms
1.218     albertel 5771: 	    my %parmhash=();
                   5772: 	    my $thisparm='';
                   5773: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5774: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5775: 		    &GDBM_READER(),0640)) {
1.218     albertel 5776: 		$thisparm=$parmhash{$symbparm};
                   5777: 		untie(%parmhash);
                   5778: 	    }
                   5779: 	    if ($thisparm) { return $thisparm; }
                   5780: 	}
1.594     albertel 5781: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5782: 
1.218     albertel 5783: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5784: 	my $filename;
                   5785: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5786: 	if ($symbparm) {
1.409     www      5787: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5788: 	} else {
1.620     albertel 5789: 	    $filename=$env{'request.filename'};
1.282     albertel 5790: 	}
                   5791: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5792: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5793: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5794: 	if (defined($metadata)) { return $metadata; }
1.142     www      5795: 
1.594     albertel 5796: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5797: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5798: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5799: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5800: 				     $env{'course.'.$courseid.'.domain'},
                   5801: 				     'course',
                   5802: 				     ($courselevelm,$courselevel));
1.593     albertel 5803: 	    if (defined($coursereply)) { return $coursereply; }
                   5804: 	}
1.145     www      5805: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5806: 	unless ($space eq '0') {
1.336     albertel 5807: 	    my @parts=split(/_/,$space);
                   5808: 	    my $id=pop(@parts);
                   5809: 	    my $part=join('_',@parts);
                   5810: 	    if ($part eq '') { $part='0'; }
                   5811: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5812: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5813: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5814: 	}
1.395     albertel 5815: 	if ($recurse) { return undef; }
                   5816: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5817: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5818: 
1.48      www      5819: # ---------------------------------------------------- Any other user namespace
                   5820:     } elsif ($realm eq 'environment') {
                   5821: # ----------------------------------------------------------------- environment
1.620     albertel 5822: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5823: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5824: 	} else {
1.770     albertel 5825: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5826: 		return '';
                   5827: 	    }
1.219     albertel 5828: 	    my %returnhash=&userenvironment($udom,$uname,
                   5829: 					    $spacequalifierrest);
                   5830: 	    return $returnhash{$spacequalifierrest};
                   5831: 	}
1.28      www      5832:     } elsif ($realm eq 'system') {
1.48      www      5833: # ----------------------------------------------------------------- system.time
                   5834: 	if ($space eq 'time') {
                   5835: 	    return time;
                   5836:         }
1.696     albertel 5837:     } elsif ($realm eq 'server') {
                   5838: # ----------------------------------------------------------------- system.time
                   5839: 	if ($space eq 'name') {
                   5840: 	    return $ENV{'SERVER_NAME'};
                   5841:         }
1.28      www      5842:     }
1.48      www      5843:     return '';
1.61      www      5844: }
                   5845: 
1.691     raeburn  5846: sub check_group_parms {
                   5847:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5848:     my @groupitems = ();
                   5849:     my $resultitem;
                   5850:     my @levels = ($symbparm,$mapparm,$what);
                   5851:     foreach my $group (@{$groups}) {
                   5852:         foreach my $level (@levels) {
                   5853:              my $item = $courseid.'.['.$group.'].'.$level;
                   5854:              push(@groupitems,$item);
                   5855:         }
                   5856:     }
                   5857:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5858:                             $env{'course.'.$courseid.'.domain'},
                   5859:                                      'course',@groupitems);
                   5860:     return $coursereply;
                   5861: }
                   5862: 
                   5863: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5864:     my ($courseid,@groups) = @_;
                   5865:     @groups = sort(@groups);
1.691     raeburn  5866:     return @groups;
                   5867: }
                   5868: 
1.395     albertel 5869: sub packages_tab_default {
                   5870:     my ($uri,$varname)=@_;
                   5871:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5872: 
                   5873:     my (@extension,@specifics,$do_default);
                   5874:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5875: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5876: 	if ($pack_type eq 'default') {
                   5877: 	    $do_default=1;
                   5878: 	} elsif ($pack_type eq 'extension') {
                   5879: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5880: 	} else {
                   5881: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5882: 	}
                   5883:     }
                   5884:     # first look for a package that matches the requested part id
                   5885:     foreach my $package (@specifics) {
                   5886: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5887: 	next if ($pack_part ne $part);
                   5888: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5889: 	    return $packagetab{"$pack_type&$name&default"};
                   5890: 	}
                   5891:     }
                   5892:     # look for any possible matching non extension_ package
                   5893:     foreach my $package (@specifics) {
                   5894: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5895: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5896: 	    return $packagetab{"$pack_type&$name&default"};
                   5897: 	}
1.585     albertel 5898: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5899: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5900: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5901: 	}
                   5902:     }
1.738     albertel 5903:     # look for any posible extension_ match
                   5904:     foreach my $package (@extension) {
                   5905: 	my ($package,$pack_type)=@{$package};
                   5906: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5907: 	    return $packagetab{"$pack_type&$name&default"};
                   5908: 	}
                   5909: 	if (defined($packagetab{$package."&$name&default"})) {
                   5910: 	    return $packagetab{$package."&$name&default"};
                   5911: 	}
                   5912:     }
                   5913:     # look for a global default setting
                   5914:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5915: 	return $packagetab{"default&$name&default"};
                   5916:     }
1.395     albertel 5917:     return undef;
                   5918: }
                   5919: 
1.334     albertel 5920: sub add_prefix_and_part {
                   5921:     my ($prefix,$part)=@_;
                   5922:     my $keyroot;
                   5923:     if (defined($prefix) && $prefix !~ /^__/) {
                   5924: 	# prefix that has a part already
                   5925: 	$keyroot=$prefix;
                   5926:     } elsif (defined($prefix)) {
                   5927: 	# prefix that is missing a part
                   5928: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5929:     } else {
                   5930: 	# no prefix at all
                   5931: 	if (defined($part)) { $keyroot='_'.$part; }
                   5932:     }
                   5933:     return $keyroot;
                   5934: }
                   5935: 
1.71      www      5936: # ---------------------------------------------------------------- Get metadata
                   5937: 
1.599     albertel 5938: my %metaentry;
1.71      www      5939: sub metadata {
1.176     www      5940:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5941:     $uri=&declutter($uri);
1.288     albertel 5942:     # if it is a non metadata possible uri return quickly
1.529     albertel 5943:     if (($uri eq '') || 
                   5944: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5945: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5946:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5947: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5948: 	return undef;
1.288     albertel 5949:     }
1.73      www      5950:     my $filename=$uri;
                   5951:     $uri=~s/\.meta$//;
1.172     www      5952: #
                   5953: # Is the metadata already cached?
1.177     www      5954: # Look at timestamp of caching
1.172     www      5955: # Everything is cached by the main uri, libraries are never directly cached
                   5956: #
1.428     albertel 5957:     if (!defined($liburi)) {
1.599     albertel 5958: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5959: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5960:     }
                   5961:     {
1.172     www      5962: #
                   5963: # Is this a recursive call for a library?
                   5964: #
1.599     albertel 5965: #	if (! exists($metacache{$uri})) {
                   5966: #	    $metacache{$uri}={};
                   5967: #	}
1.171     www      5968:         if ($liburi) {
                   5969: 	    $liburi=&declutter($liburi);
                   5970:             $filename=$liburi;
1.401     bowersj2 5971:         } else {
1.599     albertel 5972: 	    &devalidate_cache_new('meta',$uri);
                   5973: 	    undef(%metaentry);
1.401     bowersj2 5974: 	}
1.140     www      5975:         my %metathesekeys=();
1.73      www      5976:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5977: 	my $metastring;
1.768     albertel 5978: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5979: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5980: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5981: 	    $metastring=&getfile($file);
1.489     albertel 5982: 	}
1.208     albertel 5983:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5984:         my $token;
1.140     www      5985:         undef %metathesekeys;
1.71      www      5986:         while ($token=$parser->get_token) {
1.339     albertel 5987: 	    if ($token->[0] eq 'S') {
                   5988: 		if (defined($token->[2]->{'package'})) {
1.172     www      5989: #
                   5990: # This is a package - get package info
                   5991: #
1.339     albertel 5992: 		    my $package=$token->[2]->{'package'};
                   5993: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5994: 		    if (defined($token->[2]->{'id'})) { 
                   5995: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5996: 		    }
1.599     albertel 5997: 		    if ($metaentry{':packages'}) {
                   5998: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5999: 		    } else {
1.599     albertel 6000: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6001: 		    }
1.736     albertel 6002: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6003: 			my $part=$keyroot;
                   6004: 			$part=~s/^\_//;
1.736     albertel 6005: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6006: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6007: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6008: 			    # ignore package.tab specified default values
                   6009:                             # here &package_tab_default() will fetch those
                   6010: 			    if ($subp eq 'default') { next; }
1.736     albertel 6011: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6012: 			    my $unikey;
                   6013: 			    if ($pack =~ /_0$/) {
                   6014: 				$unikey='parameter_0_'.$name;
                   6015: 				$part=0;
                   6016: 			    } else {
                   6017: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6018: 			    }
1.339     albertel 6019: 			    if ($subp eq 'display') {
                   6020: 				$value.=' [Part: '.$part.']';
                   6021: 			    }
1.599     albertel 6022: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6023: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6024: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6025: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6026: 			    }
1.599     albertel 6027: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6028: 				$metaentry{':'.$unikey}=
                   6029: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6030: 			    }
1.339     albertel 6031: 			}
                   6032: 		    }
                   6033: 		} else {
1.172     www      6034: #
                   6035: # This is not a package - some other kind of start tag
1.339     albertel 6036: #
                   6037: 		    my $entry=$token->[1];
                   6038: 		    my $unikey;
                   6039: 		    if ($entry eq 'import') {
                   6040: 			$unikey='';
                   6041: 		    } else {
                   6042: 			$unikey=$entry;
                   6043: 		    }
                   6044: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6045: 
                   6046: 		    if (defined($token->[2]->{'id'})) { 
                   6047: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6048: 		    }
1.175     www      6049: 
1.339     albertel 6050: 		    if ($entry eq 'import') {
1.175     www      6051: #
                   6052: # Importing a library here
1.339     albertel 6053: #
                   6054: 			if ($depthcount<20) {
                   6055: 			    my $location=$parser->get_text('/import');
                   6056: 			    my $dir=$filename;
                   6057: 			    $dir=~s|[^/]*$||;
                   6058: 			    $location=&filelocation($dir,$location);
1.736     albertel 6059: 			    my $metadata = 
                   6060: 				&metadata($uri,'keys', $location,$unikey,
                   6061: 					  $depthcount+1);
                   6062: 			    foreach my $meta (split(',',$metadata)) {
                   6063: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6064: 				$metathesekeys{$meta}=1;
1.339     albertel 6065: 			    }
                   6066: 			}
                   6067: 		    } else { 
                   6068: 			
                   6069: 			if (defined($token->[2]->{'name'})) { 
                   6070: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6071: 			}
                   6072: 			$metathesekeys{$unikey}=1;
1.736     albertel 6073: 			foreach my $param (@{$token->[3]}) {
                   6074: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6075: 				$token->[2]->{$param};
1.339     albertel 6076: 			}
                   6077: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6078: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6079: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6080: 		 # only ws inside the tag, and not in default, so use default
                   6081: 		 # as value
1.599     albertel 6082: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6083: 			} else {
1.321     albertel 6084: 		  # either something interesting inside the tag or default
                   6085:                   # uninteresting
1.599     albertel 6086: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6087: 			}
1.172     www      6088: # end of not-a-package not-a-library import
1.339     albertel 6089: 		    }
1.172     www      6090: # end of not-a-package start tag
1.339     albertel 6091: 		}
1.172     www      6092: # the next is the end of "start tag"
1.339     albertel 6093: 	    }
                   6094: 	}
1.483     albertel 6095: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6096: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6097: 	    #no specific packages #how's our extension
                   6098: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6099: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6100: 					 \%metathesekeys);
                   6101: 	}
1.599     albertel 6102: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6103: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6104: 		#no specific packages well let's get default then
                   6105: 		if ($key!~/^default&/) { next; }
1.488     albertel 6106: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6107: 					     \%metathesekeys);
                   6108: 	    }
                   6109: 	}
1.338     www      6110: # are there custom rights to evaluate
1.599     albertel 6111: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6112: 
1.338     www      6113:     #
                   6114:     # Importing a rights file here
1.339     albertel 6115:     #
                   6116: 	    unless ($depthcount) {
1.599     albertel 6117: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6118: 		my $dir=$filename;
                   6119: 		$dir=~s|[^/]*$||;
                   6120: 		$location=&filelocation($dir,$location);
1.736     albertel 6121: 		my $rights_metadata =
                   6122: 		    &metadata($uri,'keys',$location,'_rights',
                   6123: 			      $depthcount+1);
                   6124: 		foreach my $rights (split(',',$rights_metadata)) {
                   6125: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6126: 		    $metathesekeys{$rights}=1;
1.339     albertel 6127: 		}
                   6128: 	    }
                   6129: 	}
1.737     albertel 6130: 	# uniqifiy package listing
                   6131: 	my %seen;
                   6132: 	my @uniq_packages =
                   6133: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6134: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6135: 
                   6136: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6137: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6138: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6139: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6140: # this is the end of "was not already recently cached
1.71      www      6141:     }
1.599     albertel 6142:     return $metaentry{':'.$what};
1.261     albertel 6143: }
                   6144: 
1.488     albertel 6145: sub metadata_create_package_def {
1.483     albertel 6146:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6147:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6148:     if ($subp eq 'default') { next; }
                   6149:     
1.599     albertel 6150:     if (defined($metaentry{':packages'})) {
                   6151: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6152:     } else {
1.599     albertel 6153: 	$metaentry{':packages'}=$package;
1.483     albertel 6154:     }
                   6155:     my $value=$packagetab{$key};
                   6156:     my $unikey;
                   6157:     $unikey='parameter_0_'.$name;
1.599     albertel 6158:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6159:     $$metathesekeys{$unikey}=1;
1.599     albertel 6160:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6161: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6162:     }
1.599     albertel 6163:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6164: 	$metaentry{':'.$unikey}=
                   6165: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6166:     }
                   6167: }
                   6168: 
1.261     albertel 6169: sub metadata_generate_part0 {
                   6170:     my ($metadata,$metacache,$uri) = @_;
                   6171:     my %allnames;
1.737     albertel 6172:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6173: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6174: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6175: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6176: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6177: 	    $allnames{$name}=$part;
                   6178: 	  }
                   6179: 	}
                   6180:     }
                   6181:     foreach my $name (keys(%allnames)) {
                   6182:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6183:       my $key=":parameter_0_$name";
1.261     albertel 6184:       $$metacache{"$key.part"}='0';
                   6185:       $$metacache{"$key.name"}=$name;
1.428     albertel 6186:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6187: 					   $allnames{$name}.'_'.$name.
                   6188: 					   '.type'};
1.428     albertel 6189:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6190: 			     '.display'};
1.644     www      6191:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6192:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6193:       $$metacache{"$key.display"}=$olddis;
                   6194:     }
1.71      www      6195: }
                   6196: 
1.764     albertel 6197: # ------------------------------------------------------ Devalidate title cache
                   6198: 
                   6199: sub devalidate_title_cache {
                   6200:     my ($url)=@_;
                   6201:     if (!$env{'request.course.id'}) { return; }
                   6202:     my $symb=&symbread($url);
                   6203:     if (!$symb) { return; }
                   6204:     my $key=$env{'request.course.id'}."\0".$symb;
                   6205:     &devalidate_cache_new('title',$key);
                   6206: }
                   6207: 
1.301     www      6208: # ------------------------------------------------- Get the title of a resource
                   6209: 
                   6210: sub gettitle {
                   6211:     my $urlsymb=shift;
                   6212:     my $symb=&symbread($urlsymb);
1.534     albertel 6213:     if ($symb) {
1.620     albertel 6214: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6215: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6216: 	if (defined($cached)) { 
                   6217: 	    return $result;
                   6218: 	}
1.534     albertel 6219: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6220: 	my $title='';
                   6221: 	my %bighash;
1.620     albertel 6222: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6223: 		&GDBM_READER(),0640)) {
                   6224: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6225: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6226: 	    untie %bighash;
                   6227: 	}
                   6228: 	$title=~s/\&colon\;/\:/gs;
                   6229: 	if ($title) {
1.599     albertel 6230: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6231: 	}
                   6232: 	$urlsymb=$url;
                   6233:     }
                   6234:     my $title=&metadata($urlsymb,'title');
                   6235:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6236:     return $title;
1.301     www      6237: }
1.613     albertel 6238: 
1.614     albertel 6239: sub get_slot {
                   6240:     my ($which,$cnum,$cdom)=@_;
                   6241:     if (!$cnum || !$cdom) {
1.790     albertel 6242: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6243: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6244: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6245:     }
1.703     albertel 6246:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6247:     my %slotinfo;
                   6248:     if (exists($remembered{$key})) {
                   6249: 	$slotinfo{$which} = $remembered{$key};
                   6250:     } else {
                   6251: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6252: 	&Apache::lonhomework::showhash(%slotinfo);
                   6253: 	my ($tmp)=keys(%slotinfo);
                   6254: 	if ($tmp=~/^error:/) { return (); }
                   6255: 	$remembered{$key} = $slotinfo{$which};
                   6256:     }
1.616     albertel 6257:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6258: 	return %{$slotinfo{$which}};
                   6259:     }
                   6260:     return $slotinfo{$which};
1.614     albertel 6261: }
1.31      www      6262: # ------------------------------------------------- Update symbolic store links
                   6263: 
                   6264: sub symblist {
                   6265:     my ($mapname,%newhash)=@_;
1.438     www      6266:     $mapname=&deversion(&declutter($mapname));
1.31      www      6267:     my %hash;
1.620     albertel 6268:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6269:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6270:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6271: 	    foreach my $url (keys %newhash) {
                   6272: 		next if ($url eq 'last_known'
                   6273: 			 && $env{'form.no_update_last_known'});
                   6274: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6275: 						    $newhash{$url}->[1],
                   6276: 						    $newhash{$url}->[0]);
1.191     harris41 6277:             }
1.31      www      6278:             if (untie(%hash)) {
                   6279: 		return 'ok';
                   6280:             }
                   6281:         }
                   6282:     }
                   6283:     return 'error';
1.212     www      6284: }
                   6285: 
                   6286: # --------------------------------------------------------------- Verify a symb
                   6287: 
                   6288: sub symbverify {
1.510     www      6289:     my ($symb,$thisurl)=@_;
                   6290:     my $thisfn=$thisurl;
1.439     www      6291:     $thisfn=&declutter($thisfn);
1.215     www      6292: # direct jump to resource in page or to a sequence - will construct own symbs
                   6293:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6294: # check URL part
1.409     www      6295:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6296: 
1.431     www      6297:     unless ($url eq $thisfn) { return 0; }
1.213     www      6298: 
1.216     www      6299:     $symb=&symbclean($symb);
1.510     www      6300:     $thisurl=&deversion($thisurl);
1.439     www      6301:     $thisfn=&deversion($thisfn);
1.213     www      6302: 
                   6303:     my %bighash;
                   6304:     my $okay=0;
1.431     www      6305: 
1.620     albertel 6306:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6307:                             &GDBM_READER(),0640)) {
1.510     www      6308:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6309:         unless ($ids) { 
1.510     www      6310:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6311:         }
                   6312:         if ($ids) {
                   6313: # ------------------------------------------------------------------- Has ID(s)
1.800   ! albertel 6314: 	    foreach my $id (split(/\,/,$ids)) {
        !          6315: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6316:                if (
                   6317:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6318:    eq $symb) { 
1.620     albertel 6319: 		   if (($env{'request.role.adv'}) ||
1.800   ! albertel 6320: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6321: 		       $okay=1; 
                   6322: 		   }
                   6323: 	       }
1.216     www      6324: 	   }
                   6325:         }
1.213     www      6326: 	untie(%bighash);
                   6327:     }
                   6328:     return $okay;
1.31      www      6329: }
                   6330: 
1.210     www      6331: # --------------------------------------------------------------- Clean-up symb
                   6332: 
                   6333: sub symbclean {
                   6334:     my $symb=shift;
1.568     albertel 6335:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6336: # remove version from map
                   6337:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6338: 
1.210     www      6339: # remove version from URL
                   6340:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6341: 
1.507     www      6342: # remove wrapper
                   6343: 
1.510     www      6344:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6345:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6346:     return $symb;
1.409     www      6347: }
                   6348: 
                   6349: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6350: 
                   6351: sub encode_symb {
                   6352:     my ($map,$resid,$url)=@_;
                   6353:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6354: }
1.409     www      6355: 
                   6356: sub decode_symb {
1.568     albertel 6357:     my $symb=shift;
                   6358:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6359:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6360:     return (&fixversion($map),$resid,&fixversion($url));
                   6361: }
                   6362: 
                   6363: sub fixversion {
                   6364:     my $fn=shift;
1.609     banghart 6365:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6366:     my %bighash;
                   6367:     my $uri=&clutter($fn);
1.620     albertel 6368:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6369: # is this cached?
1.599     albertel 6370:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6371:     if (defined($cached)) { return $result; }
                   6372: # unfortunately not cached, or expired
1.620     albertel 6373:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6374: 	    &GDBM_READER(),0640)) {
                   6375:  	if ($bighash{'version_'.$uri}) {
                   6376:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6377:  	    unless (($version eq 'mostrecent') || 
                   6378: 		    ($version==&getversion($uri))) {
1.440     www      6379:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6380:  	    }
                   6381:  	}
                   6382:  	untie %bighash;
1.413     www      6383:     }
1.599     albertel 6384:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6385: }
                   6386: 
                   6387: sub deversion {
                   6388:     my $url=shift;
                   6389:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6390:     return $url;
1.210     www      6391: }
                   6392: 
1.31      www      6393: # ------------------------------------------------------ Return symb list entry
                   6394: 
                   6395: sub symbread {
1.249     www      6396:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6397:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6398:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6399: # no filename provided? try from environment
1.44      www      6400:     unless ($thisfn) {
1.620     albertel 6401:         if ($env{'request.symb'}) {
                   6402: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6403: 	}
1.620     albertel 6404: 	$thisfn=$env{'request.filename'};
1.44      www      6405:     }
1.569     albertel 6406:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6407: # is that filename actually a symb? Verify, clean, and return
                   6408:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6409: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6410: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6411: 	}
1.242     www      6412:     }
1.44      www      6413:     $thisfn=declutter($thisfn);
1.31      www      6414:     my %hash;
1.37      www      6415:     my %bighash;
                   6416:     my $syval='';
1.620     albertel 6417:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6418:         my $targetfn = $thisfn;
1.609     banghart 6419:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6420:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6421:         }
1.687     albertel 6422: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6423: 	    $targetfn=$1;
                   6424: 	}
1.620     albertel 6425:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6426:                       &GDBM_READER(),0640)) {
1.481     raeburn  6427: 	    $syval=$hash{$targetfn};
1.37      www      6428:             untie(%hash);
                   6429:         }
                   6430: # ---------------------------------------------------------- There was an entry
                   6431:         if ($syval) {
1.601     albertel 6432: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6433: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6434: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6435: 		    #return $env{$cache_str}='';
1.601     albertel 6436: 		#}    
                   6437: 		#$syval.=$1;
                   6438: 	    #}
1.37      www      6439:         } else {
                   6440: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6441:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6442:                             &GDBM_READER(),0640)) {
1.37      www      6443: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6444:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6445:               unless ($ids) { 
                   6446:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6447:               }
                   6448:               unless ($ids) {
                   6449: # alias?
                   6450: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6451:               }
1.37      www      6452:               if ($ids) {
                   6453: # ------------------------------------------------------------------- Has ID(s)
                   6454:                  my @possibilities=split(/\,/,$ids);
1.39      www      6455:                  if ($#possibilities==0) {
                   6456: # ----------------------------------------------- There is only one possibility
1.37      www      6457: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6458: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6459: 						    $resid,$thisfn);
1.249     www      6460:                  } elsif (!$donotrecurse) {
1.39      www      6461: # ------------------------------------------ There is more than one possibility
                   6462:                      my $realpossible=0;
1.800   ! albertel 6463:                      foreach my $id (@possibilities) {
        !          6464: 			 my $file=$bighash{'src_'.$id};
1.39      www      6465:                          if (&allowed('bre',$file)) {
1.800   ! albertel 6466:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6467:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6468: 				$realpossible++;
1.626     albertel 6469:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6470: 						    $resid,$thisfn);
1.39      www      6471:                             }
                   6472: 			 }
1.191     harris41 6473:                      }
1.39      www      6474: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6475:                  } else {
                   6476:                      $syval='';
1.37      www      6477:                  }
                   6478: 	      }
                   6479:               untie(%bighash)
1.481     raeburn  6480:            }
1.31      www      6481:         }
1.62      www      6482:         if ($syval) {
1.620     albertel 6483: 	    return $env{$cache_str}=$syval;
1.62      www      6484:         }
1.31      www      6485:     }
1.44      www      6486:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6487:     return $env{$cache_str}='';
1.31      www      6488: }
                   6489: 
                   6490: # ---------------------------------------------------------- Return random seed
                   6491: 
1.32      www      6492: sub numval {
                   6493:     my $txt=shift;
                   6494:     $txt=~tr/A-J/0-9/;
                   6495:     $txt=~tr/a-j/0-9/;
                   6496:     $txt=~tr/K-T/0-9/;
                   6497:     $txt=~tr/k-t/0-9/;
                   6498:     $txt=~tr/U-Z/0-5/;
                   6499:     $txt=~tr/u-z/0-5/;
                   6500:     $txt=~s/\D//g;
1.564     albertel 6501:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6502:     return int($txt);
1.368     albertel 6503: }
                   6504: 
1.484     albertel 6505: sub numval2 {
                   6506:     my $txt=shift;
                   6507:     $txt=~tr/A-J/0-9/;
                   6508:     $txt=~tr/a-j/0-9/;
                   6509:     $txt=~tr/K-T/0-9/;
                   6510:     $txt=~tr/k-t/0-9/;
                   6511:     $txt=~tr/U-Z/0-5/;
                   6512:     $txt=~tr/u-z/0-5/;
                   6513:     $txt=~s/\D//g;
                   6514:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6515:     my $total;
                   6516:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6517:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6518:     return int($total);
                   6519: }
                   6520: 
1.575     albertel 6521: sub numval3 {
                   6522:     use integer;
                   6523:     my $txt=shift;
                   6524:     $txt=~tr/A-J/0-9/;
                   6525:     $txt=~tr/a-j/0-9/;
                   6526:     $txt=~tr/K-T/0-9/;
                   6527:     $txt=~tr/k-t/0-9/;
                   6528:     $txt=~tr/U-Z/0-5/;
                   6529:     $txt=~tr/u-z/0-5/;
                   6530:     $txt=~s/\D//g;
                   6531:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6532:     my $total;
                   6533:     foreach my $val (@txts) { $total+=$val; }
                   6534:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6535:     return $total;
                   6536: }
                   6537: 
1.675     albertel 6538: sub digest {
                   6539:     my ($data)=@_;
                   6540:     my $digest=&Digest::MD5::md5($data);
                   6541:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6542:     my ($e,$f);
                   6543:     {
                   6544:         use integer;
                   6545:         $e=($a+$b);
                   6546:         $f=($c+$d);
                   6547:         if ($_64bit) {
                   6548:             $e=(($e<<32)>>32);
                   6549:             $f=(($f<<32)>>32);
                   6550:         }
                   6551:     }
                   6552:     if (wantarray) {
                   6553: 	return ($e,$f);
                   6554:     } else {
                   6555: 	my $g;
                   6556: 	{
                   6557: 	    use integer;
                   6558: 	    $g=($e+$f);
                   6559: 	    if ($_64bit) {
                   6560: 		$g=(($g<<32)>>32);
                   6561: 	    }
                   6562: 	}
                   6563: 	return $g;
                   6564:     }
                   6565: }
                   6566: 
1.368     albertel 6567: sub latest_rnd_algorithm_id {
1.675     albertel 6568:     return '64bit5';
1.366     albertel 6569: }
1.32      www      6570: 
1.503     albertel 6571: sub get_rand_alg {
                   6572:     my ($courseid)=@_;
1.790     albertel 6573:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6574:     if ($courseid) {
1.620     albertel 6575: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6576:     }
                   6577:     return &latest_rnd_algorithm_id();
                   6578: }
                   6579: 
1.562     albertel 6580: sub validCODE {
                   6581:     my ($CODE)=@_;
                   6582:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6583:     return 0;
                   6584: }
                   6585: 
1.491     albertel 6586: sub getCODE {
1.620     albertel 6587:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6588:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6589: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6590: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6591: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6592:     }
                   6593:     return undef;
                   6594: }
                   6595: 
1.31      www      6596: sub rndseed {
1.155     albertel 6597:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6598: 
1.790     albertel 6599:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6600:     if (!$symb) {
1.366     albertel 6601: 	unless ($symb=$wsymb) { return time; }
                   6602:     }
                   6603:     if (!$courseid) { $courseid=$wcourseid; }
                   6604:     if (!$domain) { $domain=$wdomain; }
                   6605:     if (!$username) { $username=$wusername }
1.503     albertel 6606:     my $which=&get_rand_alg();
1.491     albertel 6607:     if (defined(&getCODE())) {
1.675     albertel 6608: 	if ($which eq '64bit5') {
                   6609: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6610: 	} elsif ($which eq '64bit4') {
1.575     albertel 6611: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6612: 	} else {
                   6613: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6614: 	}
1.675     albertel 6615:     } elsif ($which eq '64bit5') {
                   6616: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6617:     } elsif ($which eq '64bit4') {
                   6618: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6619:     } elsif ($which eq '64bit3') {
                   6620: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6621:     } elsif ($which eq '64bit2') {
                   6622: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6623:     } elsif ($which eq '64bit') {
                   6624: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6625:     }
                   6626:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6627: }
                   6628: 
                   6629: sub rndseed_32bit {
                   6630:     my ($symb,$courseid,$domain,$username)=@_;
                   6631:     {
                   6632: 	use integer;
                   6633: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6634: 	my $symbseed=numval($symb) << 22;
                   6635: 	my $namechck=unpack("%32C*",$username) << 17;
                   6636: 	my $nameseed=numval($username) << 12;
                   6637: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6638: 	my $courseseed=unpack("%32C*",$courseid);
                   6639: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6640: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6641: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6642: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6643: 	return $num;
                   6644:     }
                   6645: }
                   6646: 
                   6647: sub rndseed_64bit {
                   6648:     my ($symb,$courseid,$domain,$username)=@_;
                   6649:     {
                   6650: 	use integer;
                   6651: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6652: 	my $symbseed=numval($symb) << 10;
                   6653: 	my $namechck=unpack("%32S*",$username);
                   6654: 	
                   6655: 	my $nameseed=numval($username) << 21;
                   6656: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6657: 	my $courseseed=unpack("%32S*",$courseid);
                   6658: 	
                   6659: 	my $num1=$symbchck+$symbseed+$namechck;
                   6660: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6661: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6662: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6663: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6664: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6665: 	return "$num1,$num2";
1.155     albertel 6666:     }
1.366     albertel 6667: }
                   6668: 
1.443     albertel 6669: sub rndseed_64bit2 {
                   6670:     my ($symb,$courseid,$domain,$username)=@_;
                   6671:     {
                   6672: 	use integer;
                   6673: 	# strings need to be an even # of cahracters long, it it is odd the
                   6674:         # last characters gets thrown away
                   6675: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6676: 	my $symbseed=numval($symb) << 10;
                   6677: 	my $namechck=unpack("%32S*",$username.' ');
                   6678: 	
                   6679: 	my $nameseed=numval($username) << 21;
1.501     albertel 6680: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6681: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6682: 	
                   6683: 	my $num1=$symbchck+$symbseed+$namechck;
                   6684: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6685: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6686: 	#&logthis("rndseed :$num:$symb");
1.501     albertel 6687: 	return "$num1,$num2";
                   6688:     }
                   6689: }
                   6690: 
                   6691: sub rndseed_64bit3 {
                   6692:     my ($symb,$courseid,$domain,$username)=@_;
                   6693:     {
                   6694: 	use integer;
                   6695: 	# strings need to be an even # of cahracters long, it it is odd the
                   6696:         # last characters gets thrown away
                   6697: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6698: 	my $symbseed=numval2($symb) << 10;
                   6699: 	my $namechck=unpack("%32S*",$username.' ');
                   6700: 	
                   6701: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6702: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6703: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6704: 	
                   6705: 	my $num1=$symbchck+$symbseed+$namechck;
                   6706: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6707: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6708: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6709: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6710: 	
1.503     albertel 6711: 	return "$num1:$num2";
1.443     albertel 6712:     }
                   6713: }
                   6714: 
1.575     albertel 6715: sub rndseed_64bit4 {
                   6716:     my ($symb,$courseid,$domain,$username)=@_;
                   6717:     {
                   6718: 	use integer;
                   6719: 	# strings need to be an even # of cahracters long, it it is odd the
                   6720:         # last characters gets thrown away
                   6721: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6722: 	my $symbseed=numval3($symb) << 10;
                   6723: 	my $namechck=unpack("%32S*",$username.' ');
                   6724: 	
                   6725: 	my $nameseed=numval3($username) << 21;
                   6726: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6727: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6728: 	
                   6729: 	my $num1=$symbchck+$symbseed+$namechck;
                   6730: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6731: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6732: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6733: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6734: 	
                   6735: 	return "$num1:$num2";
                   6736:     }
                   6737: }
                   6738: 
1.675     albertel 6739: sub rndseed_64bit5 {
                   6740:     my ($symb,$courseid,$domain,$username)=@_;
                   6741:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6742:     return "$num1:$num2";
                   6743: }
                   6744: 
1.366     albertel 6745: sub rndseed_CODE_64bit {
                   6746:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6747:     {
1.366     albertel 6748: 	use integer;
1.443     albertel 6749: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6750: 	my $symbseed=numval2($symb);
1.491     albertel 6751: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6752: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6753: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6754: 	my $num1=$symbseed+$CODEchck;
                   6755: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6756: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6757: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6758: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6759: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6760: 	return "$num1:$num2";
1.366     albertel 6761:     }
                   6762: }
                   6763: 
1.575     albertel 6764: sub rndseed_CODE_64bit4 {
                   6765:     my ($symb,$courseid,$domain,$username)=@_;
                   6766:     {
                   6767: 	use integer;
                   6768: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6769: 	my $symbseed=numval3($symb);
                   6770: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6771: 	my $CODEseed=numval3(&getCODE());
                   6772: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6773: 	my $num1=$symbseed+$CODEchck;
                   6774: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6775: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6776: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6777: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6778: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6779: 	return "$num1:$num2";
                   6780:     }
                   6781: }
                   6782: 
1.675     albertel 6783: sub rndseed_CODE_64bit5 {
                   6784:     my ($symb,$courseid,$domain,$username)=@_;
                   6785:     my $code = &getCODE();
                   6786:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6787:     return "$num1:$num2";
                   6788: }
                   6789: 
1.366     albertel 6790: sub setup_random_from_rndseed {
                   6791:     my ($rndseed)=@_;
1.503     albertel 6792:     if ($rndseed =~/([,:])/) {
                   6793: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6794: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6795:     } else {
                   6796: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6797:     }
1.36      albertel 6798: }
                   6799: 
1.474     albertel 6800: sub latest_receipt_algorithm_id {
                   6801:     return 'receipt2';
                   6802: }
                   6803: 
1.480     www      6804: sub recunique {
                   6805:     my $fucourseid=shift;
                   6806:     my $unique;
1.620     albertel 6807:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6808: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6809:     } else {
                   6810: 	$unique=$perlvar{'lonReceipt'};
                   6811:     }
                   6812:     return unpack("%32C*",$unique);
                   6813: }
                   6814: 
                   6815: sub recprefix {
                   6816:     my $fucourseid=shift;
                   6817:     my $prefix;
1.620     albertel 6818:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6819: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6820:     } else {
                   6821: 	$prefix=$perlvar{'lonHostID'};
                   6822:     }
                   6823:     return unpack("%32C*",$prefix);
                   6824: }
                   6825: 
1.76      www      6826: sub ireceipt {
1.474     albertel 6827:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6828:     my $cuname=unpack("%32C*",$funame);
                   6829:     my $cudom=unpack("%32C*",$fudom);
                   6830:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6831:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6832:     my $cunique=&recunique($fucourseid);
1.474     albertel 6833:     my $cpart=unpack("%32S*",$part);
1.480     www      6834:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6835:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6836: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6837: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6838: 			       
                   6839: 	$return.= ($cunique%$cuname+
                   6840: 		   $cunique%$cudom+
                   6841: 		   $cusymb%$cuname+
                   6842: 		   $cusymb%$cudom+
                   6843: 		   $cucourseid%$cuname+
                   6844: 		   $cucourseid%$cudom+
                   6845: 		   $cpart%$cuname+
                   6846: 		   $cpart%$cudom);
                   6847:     } else {
                   6848: 	$return.= ($cunique%$cuname+
                   6849: 		   $cunique%$cudom+
                   6850: 		   $cusymb%$cuname+
                   6851: 		   $cusymb%$cudom+
                   6852: 		   $cucourseid%$cuname+
                   6853: 		   $cucourseid%$cudom);
                   6854:     }
                   6855:     return $return;
1.76      www      6856: }
                   6857: 
                   6858: sub receipt {
1.474     albertel 6859:     my ($part)=@_;
1.790     albertel 6860:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6861:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6862: }
1.260     ng       6863: 
1.790     albertel 6864: sub whichuser {
                   6865:     my ($passedsymb)=@_;
                   6866:     my ($symb,$courseid,$domain,$name,$publicuser);
                   6867:     if (defined($env{'form.grade_symb'})) {
                   6868: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   6869: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   6870: 	if (!$allowed &&
                   6871: 	    exists($env{'request.course.sec'}) &&
                   6872: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   6873: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   6874: 			      '/'.$env{'request.course.sec'});
                   6875: 	}
                   6876: 	if ($allowed) {
                   6877: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   6878: 	    $courseid=$tmp_courseid;
                   6879: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   6880: 	    ($name)=&get_env_multiple('form.grade_username');
                   6881: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   6882: 	}
                   6883:     }
                   6884:     if (!$passedsymb) {
                   6885: 	$symb=&symbread();
                   6886:     } else {
                   6887: 	$symb=$passedsymb;
                   6888:     }
                   6889:     $courseid=$env{'request.course.id'};
                   6890:     $domain=$env{'user.domain'};
                   6891:     $name=$env{'user.name'};
                   6892:     if ($name eq 'public' && $domain eq 'public') {
                   6893: 	if (!defined($env{'form.username'})) {
                   6894: 	    $env{'form.username'}.=time.rand(10000000);
                   6895: 	}
                   6896: 	$name.=$env{'form.username'};
                   6897:     }
                   6898:     return ($symb,$courseid,$domain,$name,$publicuser);
                   6899: 
                   6900: }
                   6901: 
1.36      albertel 6902: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6903: # returns either the contents of the file or 
                   6904: # -1 if the file doesn't exist
1.481     raeburn  6905: #
                   6906: # if the target is a file that was uploaded via DOCS, 
                   6907: # a check will be made to see if a current copy exists on the local server,
                   6908: # if it does this will be served, otherwise a copy will be retrieved from
                   6909: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6910: # the local server.   
1.472     albertel 6911: 
1.36      albertel 6912: sub getfile {
1.538     albertel 6913:     my ($file) = @_;
1.609     banghart 6914:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6915:     &repcopy($file);
                   6916:     return &readfile($file);
                   6917: }
                   6918: 
                   6919: sub repcopy_userfile {
                   6920:     my ($file)=@_;
1.609     banghart 6921:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6922:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6923:     my ($cdom,$cnum,$filename) = 
                   6924: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6925:     my ($info,$rtncode);
                   6926:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6927:     if (-e "$file") {
                   6928: 	my @fileinfo = stat($file);
                   6929: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6930: 	if ($lwpresp ne 'ok') {
                   6931: 	    if ($rtncode eq '404') {
1.538     albertel 6932: 		unlink($file);
1.482     albertel 6933: 	    }
1.517     albertel 6934: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6935: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6936: 	    #my $response=$ua->request($request);
                   6937: 	    #if ($response->is_success()) {
                   6938: 	#	return $response->content;
                   6939: 	#    } else {
                   6940: 	#	return -1;
                   6941: 	#    }
1.482     albertel 6942: 	    return -1;
                   6943: 	}
                   6944: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6945: 	    return 'ok';
1.482     albertel 6946: 	}
                   6947: 	$info = '';
1.538     albertel 6948: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6949: 	if ($lwpresp ne 'ok') {
                   6950: 	    return -1;
                   6951: 	}
                   6952:     } else {
1.538     albertel 6953: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6954: 	if ($lwpresp ne 'ok') {
1.517     albertel 6955: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6956: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6957: 	    my $response=$ua->request($request);
                   6958: 	    if ($response->is_success()) {
1.538     albertel 6959: 		$info=$response->content;
1.517     albertel 6960: 	    } else {
                   6961: 		return -1;
                   6962: 	    }
1.482     albertel 6963: 	}
                   6964: 	my @parts = ($cdom,$cnum); 
                   6965: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6966: 	    push @parts, split(/\//,$1);
1.518     albertel 6967: 	}
1.538     albertel 6968: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6969: 	foreach my $part (@parts) {
                   6970: 	    $path .= '/'.$part;
                   6971: 	    if (!-e $path) {
                   6972: 		mkdir($path,0770);
                   6973: 	    }
                   6974: 	}
                   6975:     }
1.538     albertel 6976:     open(FILE,">$file");
1.482     albertel 6977:     print FILE $info;
                   6978:     close(FILE);
1.607     raeburn  6979:     return 'ok';
1.481     raeburn  6980: }
                   6981: 
1.517     albertel 6982: sub tokenwrapper {
                   6983:     my $uri=shift;
1.552     albertel 6984:     $uri=~s|^http\://([^/]+)||;
                   6985:     $uri=~s|^/||;
1.620     albertel 6986:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6987:     my $token=$1;
1.552     albertel 6988:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6989:     if ($udom && $uname && $file) {
                   6990: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6991:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6992:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6993:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6994:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6995:     } else {
                   6996:         return '/adm/notfound.html';
                   6997:     }
                   6998: }
                   6999: 
1.481     raeburn  7000: sub getuploaded {
                   7001:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7002:     $uri=~s/^\///;
                   7003:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7004:     my $ua=new LWP::UserAgent;
                   7005:     my $request=new HTTP::Request($reqtype,$uri);
                   7006:     my $response=$ua->request($request);
                   7007:     $$rtncode = $response->code;
1.482     albertel 7008:     if (! $response->is_success()) {
                   7009: 	return 'failed';
                   7010:     }      
                   7011:     if ($reqtype eq 'HEAD') {
1.486     www      7012: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7013:     } elsif ($reqtype eq 'GET') {
                   7014: 	$$info = $response->content;
1.472     albertel 7015:     }
1.482     albertel 7016:     return 'ok';
1.36      albertel 7017: }
                   7018: 
1.481     raeburn  7019: sub readfile {
                   7020:     my $file = shift;
                   7021:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7022:     my $fh;
                   7023:     open($fh,"<$file");
                   7024:     my $a='';
1.800   ! albertel 7025:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7026:     return $a;
                   7027: }
                   7028: 
1.36      albertel 7029: sub filelocation {
1.590     banghart 7030:     my ($dir,$file) = @_;
                   7031:     my $location;
                   7032:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7033: 
                   7034:     if ($file =~ m-^/adm/-) {
                   7035: 	$file=~s-^/adm/wrapper/-/-;
                   7036: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7037:     }
1.590     banghart 7038:     if ($file=~m:^/~:) { # is a contruction space reference
                   7039:         $location = $file;
                   7040:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 7041:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   7042: 	# is a correct contruction space reference
                   7043:         $location = $file;
1.609     banghart 7044:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7045:         my ($udom,$uname,$filename)=
1.609     banghart 7046:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 7047:         my $home=&homeserver($uname,$udom);
                   7048:         my $is_me=0;
                   7049:         my @ids=&current_machine_ids();
                   7050:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7051:         if ($is_me) {
1.740     www      7052:   	    $location=&propath($udom,$uname).
1.590     banghart 7053:   	      '/userfiles/'.$filename;
                   7054:         } else {
                   7055:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7056:   	      $udom.'/'.$uname.'/'.$filename;
                   7057:         }
                   7058:     } else {
                   7059:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7060:         $file=~s:^/res/:/:;
                   7061:         if ( !( $file =~ m:^/:) ) {
                   7062:             $location = $dir. '/'.$file;
                   7063:         } else {
                   7064:             $location = '/home/httpd/html/res'.$file;
                   7065:         }
1.59      albertel 7066:     }
1.590     banghart 7067:     $location=~s://+:/:g; # remove duplicate /
                   7068:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7069:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7070:     return $location;
1.46      www      7071: }
1.36      albertel 7072: 
1.46      www      7073: sub hreflocation {
                   7074:     my ($dir,$file)=@_;
1.460     albertel 7075:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7076: 	$file=filelocation($dir,$file);
1.700     albertel 7077:     } elsif ($file=~m-^/adm/-) {
                   7078: 	$file=~s-^/adm/wrapper/-/-;
                   7079: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7080:     }
                   7081:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7082: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   7083:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 7084: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 7085:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   7086: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7087: 	    -/uploaded/$1/$2/-x;
1.46      www      7088:     }
1.462     albertel 7089:     return $file;
1.465     albertel 7090: }
                   7091: 
                   7092: sub current_machine_domains {
                   7093:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7094:     my @domains;
                   7095:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7096: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7097: 	if ($hostname eq $name) {
                   7098: 	    push(@domains,$hostdom{$id});
                   7099: 	}
                   7100:     }
                   7101:     return @domains;
                   7102: }
                   7103: 
                   7104: sub current_machine_ids {
                   7105:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7106:     my @ids;
                   7107:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7108: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7109: 	if ($hostname eq $name) {
                   7110: 	    push(@ids,$id);
                   7111: 	}
                   7112:     }
                   7113:     return @ids;
1.31      www      7114: }
                   7115: 
                   7116: # ------------------------------------------------------------- Declutters URLs
                   7117: 
                   7118: sub declutter {
                   7119:     my $thisfn=shift;
1.569     albertel 7120:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7121:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7122:     $thisfn=~s/^\///;
1.697     albertel 7123:     $thisfn=~s|^adm/wrapper/||;
                   7124:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7125:     $thisfn=~s/^res\///;
1.235     www      7126:     $thisfn=~s/\?.+$//;
1.268     www      7127:     return $thisfn;
                   7128: }
                   7129: 
                   7130: # ------------------------------------------------------------- Clutter up URLs
                   7131: 
                   7132: sub clutter {
                   7133:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7134:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7135:        $thisfn='/res'.$thisfn; 
                   7136:     }
1.694     albertel 7137:     if ($thisfn !~m|/adm|) {
1.695     albertel 7138: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7139: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7140: 	} else {
                   7141: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7142: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7143: 	    if ($embstyle eq 'ssi'
                   7144: 		|| ($embstyle eq 'hdn')
                   7145: 		|| ($embstyle eq 'rat')
                   7146: 		|| ($embstyle eq 'prv')
                   7147: 		|| ($embstyle eq 'ign')) {
                   7148: 		#do nothing with these
                   7149: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7150: 		|| ($embstyle eq 'emb')
                   7151: 		|| ($embstyle eq 'wrp')) {
                   7152: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7153: 	    } elsif ($embstyle eq 'unk'
                   7154: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7155: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7156: 	    } else {
1.718     www      7157: #		&logthis("Got a blank emb style");
1.695     albertel 7158: 	    }
1.694     albertel 7159: 	}
                   7160:     }
1.31      www      7161:     return $thisfn;
1.12      www      7162: }
                   7163: 
1.787     albertel 7164: sub clutter_with_no_wrapper {
                   7165:     my $uri = &clutter(shift);
                   7166:     if ($uri =~ m-^/adm/-) {
                   7167: 	$uri =~ s-^/adm/wrapper/-/-;
                   7168: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7169:     }
                   7170:     return $uri;
                   7171: }
                   7172: 
1.557     albertel 7173: sub freeze_escape {
                   7174:     my ($value)=@_;
                   7175:     if (ref($value)) {
                   7176: 	$value=&nfreeze($value);
                   7177: 	return '__FROZEN__'.&escape($value);
                   7178:     }
                   7179:     return &escape($value);
                   7180: }
                   7181: 
1.11      www      7182: 
1.557     albertel 7183: sub thaw_unescape {
                   7184:     my ($value)=@_;
                   7185:     if ($value =~ /^__FROZEN__/) {
                   7186: 	substr($value,0,10,undef);
                   7187: 	$value=&unescape($value);
                   7188: 	return &thaw($value);
                   7189:     }
                   7190:     return &unescape($value);
                   7191: }
                   7192: 
1.436     albertel 7193: sub correct_line_ends {
                   7194:     my ($result)=@_;
                   7195:     $$result =~s/\r\n/\n/mg;
                   7196:     $$result =~s/\r/\n/mg;
1.415     albertel 7197: }
1.1       albertel 7198: # ================================================================ Main Program
                   7199: 
1.184     www      7200: sub goodbye {
1.204     albertel 7201:    &logthis("Starting Shut down");
1.443     albertel 7202: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7203:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7204: #converted
1.599     albertel 7205: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7206:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7207: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7208: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7209: #1.1 only
1.599     albertel 7210: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7211: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7212: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7213: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7214:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7215:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7216:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7217:    &flushcourselogs();
                   7218:    &logthis("Shutting down");
                   7219: }
                   7220: 
1.179     www      7221: BEGIN {
1.228     harris41 7222: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7223:     unless ($readit) {
1.217     harris41 7224: {
1.781     raeburn  7225:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7226:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7227: }
1.1       albertel 7228: 
1.327     albertel 7229: # ------------------------------------------------------------ Read domain file
                   7230: {
                   7231:     %domaindescription = ();
                   7232:     %domain_auth_def = ();
                   7233:     %domain_auth_arg_def = ();
1.448     albertel 7234:     my $fh;
                   7235:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800   ! albertel 7236: 	while (my $line = <$fh>) {
        !          7237:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7238: #           next if /^\#/;
1.327     albertel 7239:            chomp;
1.403     www      7240:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800   ! albertel 7241: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7242: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7243:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7244: 	   $domaindescription{$domain}=$domain_description;
                   7245: 	   $domain_lang_def{$domain}=$def_lang;
                   7246: 	   $domain_city{$domain}=$city;
                   7247: 	   $domain_longi{$domain}=$longi;
                   7248: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7249:            $domain_primary{$domain}=$primary;
1.403     www      7250: 
1.448     albertel 7251:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7252: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7253: 	}
1.327     albertel 7254:     }
1.448     albertel 7255:     close ($fh);
1.327     albertel 7256: }
                   7257: 
                   7258: 
1.1       albertel 7259: # ------------------------------------------------------------- Read hosts file
                   7260: {
1.448     albertel 7261:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7262: 
                   7263:     while (my $configline=<$config>) {
1.303     matthew  7264:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7265:        chomp($configline);
1.595     albertel 7266:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7267:        $name=~s/\s//g;
1.595     albertel 7268:        if ($id && $domain && $role && $name) {
1.252     albertel 7269: 	 $hostname{$id}=$name;
                   7270: 	 $hostdom{$id}=$domain;
                   7271: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7272:        }
1.1       albertel 7273:     }
1.448     albertel 7274:     close($config);
1.619     albertel 7275:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7276:     #&get_iphost();
1.1       albertel 7277: }
                   7278: 
1.598     albertel 7279: sub get_iphost {
                   7280:     if (%iphost) { return %iphost; }
1.653     albertel 7281:     my %name_to_ip;
1.598     albertel 7282:     foreach my $id (keys(%hostname)) {
                   7283: 	my $name=$hostname{$id};
1.653     albertel 7284: 	my $ip;
                   7285: 	if (!exists($name_to_ip{$name})) {
                   7286: 	    $ip = gethostbyname($name);
                   7287: 	    if (!$ip || length($ip) ne 4) {
                   7288: 		&logthis("Skipping host $id name $name no IP found\n");
                   7289: 		next;
                   7290: 	    }
                   7291: 	    $ip=inet_ntoa($ip);
                   7292: 	    $name_to_ip{$name} = $ip;
                   7293: 	} else {
                   7294: 	    $ip = $name_to_ip{$name};
1.598     albertel 7295: 	}
                   7296: 	push(@{$iphost{$ip}},$id);
                   7297:     }
                   7298:     return %iphost;
                   7299: }
                   7300: 
1.1       albertel 7301: # ------------------------------------------------------ Read spare server file
                   7302: {
1.448     albertel 7303:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7304: 
                   7305:     while (my $configline=<$config>) {
                   7306:        chomp($configline);
1.284     matthew  7307:        if ($configline) {
1.784     albertel 7308: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7309: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7310: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7311:        }
                   7312:     }
1.448     albertel 7313:     close($config);
1.1       albertel 7314: }
1.11      www      7315: # ------------------------------------------------------------ Read permissions
                   7316: {
1.448     albertel 7317:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7318: 
                   7319:     while (my $configline=<$config>) {
1.448     albertel 7320: 	chomp($configline);
                   7321: 	if ($configline) {
                   7322: 	    my ($role,$perm)=split(/ /,$configline);
                   7323: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7324: 	}
1.11      www      7325:     }
1.448     albertel 7326:     close($config);
1.11      www      7327: }
                   7328: 
                   7329: # -------------------------------------------- Read plain texts for permissions
                   7330: {
1.448     albertel 7331:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7332: 
                   7333:     while (my $configline=<$config>) {
1.448     albertel 7334: 	chomp($configline);
                   7335: 	if ($configline) {
1.742     raeburn  7336: 	    my ($short,@plain)=split(/:/,$configline);
                   7337:             %{$prp{$short}} = ();
                   7338: 	    if (@plain > 0) {
                   7339:                 $prp{$short}{'std'} = $plain[0];
                   7340:                 for (my $i=1; $i<@plain; $i++) {
                   7341:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7342:                 }
                   7343:             }
1.448     albertel 7344: 	}
1.135     www      7345:     }
1.448     albertel 7346:     close($config);
1.135     www      7347: }
                   7348: 
                   7349: # ---------------------------------------------------------- Read package table
                   7350: {
1.448     albertel 7351:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7352: 
                   7353:     while (my $configline=<$config>) {
1.483     albertel 7354: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7355: 	chomp($configline);
                   7356: 	my ($short,$plain)=split(/:/,$configline);
                   7357: 	my ($pack,$name)=split(/\&/,$short);
                   7358: 	if ($plain ne '') {
                   7359: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7360: 	    $packagetab{$short}=$plain; 
                   7361: 	}
1.11      www      7362:     }
1.448     albertel 7363:     close($config);
1.329     matthew  7364: }
                   7365: 
                   7366: # ------------- set up temporary directory
                   7367: {
                   7368:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7369: 
1.11      www      7370: }
                   7371: 
1.794     albertel 7372: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7373: 				'compress_threshold'=> 20_000,
                   7374:  			        });
1.185     www      7375: 
1.281     www      7376: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7377: $dumpcount=0;
1.22      www      7378: 
1.163     harris41 7379: &logtouch();
1.672     albertel 7380: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7381: $readit=1;
1.564     albertel 7382:     {
                   7383: 	use integer;
                   7384: 	my $test=(2**32)+1;
1.568     albertel 7385: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7386: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7387:     }
1.195     www      7388: }
1.1       albertel 7389: }
1.179     www      7390: 
1.1       albertel 7391: 1;
1.191     harris41 7392: __END__
                   7393: 
1.243     albertel 7394: =pod
                   7395: 
1.191     harris41 7396: =head1 NAME
                   7397: 
1.243     albertel 7398: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7399: 
                   7400: =head1 SYNOPSIS
                   7401: 
1.243     albertel 7402: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7403: 
                   7404:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7405: 
1.243     albertel 7406: Common parameters:
                   7407: 
                   7408: =over 4
                   7409: 
                   7410: =item *
                   7411: 
                   7412: $uname : an internal username (if $cname expecting a course Id specifically)
                   7413: 
                   7414: =item *
                   7415: 
                   7416: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7417: 
                   7418: =item *
                   7419: 
                   7420: $symb : a resource instance identifier
                   7421: 
                   7422: =item *
                   7423: 
                   7424: $namespace : the name of a .db file that contains the data needed or
                   7425: being set.
                   7426: 
                   7427: =back
                   7428: 
1.394     bowersj2 7429: =head1 OVERVIEW
1.191     harris41 7430: 
1.394     bowersj2 7431: lonnet provides subroutines which interact with the
                   7432: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7433: about classes, users, and resources.
1.243     albertel 7434: 
                   7435: For many of these objects you can also use this to store data about
                   7436: them or modify them in various ways.
1.191     harris41 7437: 
1.394     bowersj2 7438: =head2 Symbs
1.191     harris41 7439: 
1.394     bowersj2 7440: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7441: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7442: map, the resource number of the resource in the map, and the URL of
                   7443: the resource itself. The latter is somewhat redundant, but might help
                   7444: if maps change.
                   7445: 
                   7446: An example is
                   7447: 
                   7448:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7449: 
                   7450: The respective map entry is
                   7451: 
                   7452:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7453:   title="Problem 2">
                   7454:  </resource>
                   7455: 
                   7456: Symbs are used by the random number generator, as well as to store and
                   7457: restore data specific to a certain instance of for example a problem.
                   7458: 
                   7459: =head2 Storing And Retrieving Data
                   7460: 
                   7461: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7462: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7463: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7464: is is the non-critical message twin of cstore. These functions are for
                   7465: handlers to store a perl hash to a user's permanent data space in an
                   7466: easy manner, and to retrieve it again on another call. It is expected
                   7467: that a handler would use this once at the beginning to retrieve data,
                   7468: and then again once at the end to send only the new data back.
                   7469: 
                   7470: The data is stored in the user's data directory on the user's
                   7471: homeserver under the ID of the course.
                   7472: 
                   7473: The hash that is returned by restore will have all of the previous
                   7474: value for all of the elements of the hash.
                   7475: 
                   7476: Example:
                   7477: 
                   7478:  #creating a hash
                   7479:  my %hash;
                   7480:  $hash{'foo'}='bar';
                   7481: 
                   7482:  #storing it
                   7483:  &Apache::lonnet::cstore(\%hash);
                   7484: 
                   7485:  #changing a value
                   7486:  $hash{'foo'}='notbar';
                   7487: 
                   7488:  #adding a new value
                   7489:  $hash{'bar'}='foo';
                   7490:  &Apache::lonnet::cstore(\%hash);
                   7491: 
                   7492:  #retrieving the hash
                   7493:  my %history=&Apache::lonnet::restore();
                   7494: 
                   7495:  #print the hash
                   7496:  foreach my $key (sort(keys(%history))) {
                   7497:    print("\%history{$key} = $history{$key}");
                   7498:  }
                   7499: 
                   7500: Will print out:
1.191     harris41 7501: 
1.394     bowersj2 7502:  %history{1:foo} = bar
                   7503:  %history{1:keys} = foo:timestamp
                   7504:  %history{1:timestamp} = 990455579
                   7505:  %history{2:bar} = foo
                   7506:  %history{2:foo} = notbar
                   7507:  %history{2:keys} = foo:bar:timestamp
                   7508:  %history{2:timestamp} = 990455580
                   7509:  %history{bar} = foo
                   7510:  %history{foo} = notbar
                   7511:  %history{timestamp} = 990455580
                   7512:  %history{version} = 2
                   7513: 
                   7514: Note that the special hash entries C<keys>, C<version> and
                   7515: C<timestamp> were added to the hash. C<version> will be equal to the
                   7516: total number of versions of the data that have been stored. The
                   7517: C<timestamp> attribute will be the UNIX time the hash was
                   7518: stored. C<keys> is available in every historical section to list which
                   7519: keys were added or changed at a specific historical revision of a
                   7520: hash.
                   7521: 
                   7522: B<Warning>: do not store the hash that restore returns directly. This
                   7523: will cause a mess since it will restore the historical keys as if the
                   7524: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7525: 
1.394     bowersj2 7526: Calling convention:
1.191     harris41 7527: 
1.394     bowersj2 7528:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7529:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7530: 
1.394     bowersj2 7531: For more detailed information, see lonnet specific documentation.
1.191     harris41 7532: 
1.394     bowersj2 7533: =head1 RETURN MESSAGES
1.191     harris41 7534: 
1.394     bowersj2 7535: =over 4
1.191     harris41 7536: 
1.394     bowersj2 7537: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7538: 
1.394     bowersj2 7539: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7540: when the connection is brought back up
1.191     harris41 7541: 
1.394     bowersj2 7542: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7543: for later delivery
1.191     harris41 7544: 
1.394     bowersj2 7545: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7546: 
1.394     bowersj2 7547: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7548: that was requested
1.191     harris41 7549: 
1.243     albertel 7550: =back
1.191     harris41 7551: 
1.243     albertel 7552: =head1 PUBLIC SUBROUTINES
1.191     harris41 7553: 
1.243     albertel 7554: =head2 Session Environment Functions
1.191     harris41 7555: 
1.243     albertel 7556: =over 4
1.191     harris41 7557: 
1.394     bowersj2 7558: =item * 
                   7559: X<appenv()>
                   7560: B<appenv(%hash)>: the value of %hash is written to
                   7561: the user envirnoment file, and will be restored for each access this
1.620     albertel 7562: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7563: process
1.191     harris41 7564: 
                   7565: =item *
1.394     bowersj2 7566: X<delenv()>
                   7567: B<delenv($regexp)>: removes all items from the session
                   7568: environment file that matches the regular expression in $regexp. The
1.620     albertel 7569: values are also delted from the current processes %env.
1.191     harris41 7570: 
1.795     albertel 7571: =item * get_env_multiple($name) 
                   7572: 
                   7573: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7574: values may be defined and end up as an array ref.
                   7575: 
                   7576: returns an array of values
                   7577: 
1.243     albertel 7578: =back
                   7579: 
                   7580: =head2 User Information
1.191     harris41 7581: 
1.243     albertel 7582: =over 4
1.191     harris41 7583: 
                   7584: =item *
1.394     bowersj2 7585: X<queryauthenticate()>
                   7586: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7587: authentication scheme
                   7588: 
                   7589: =item *
1.394     bowersj2 7590: X<authenticate()>
                   7591: B<authenticate($uname,$upass,$udom)>: try to
                   7592: authenticate user from domain's lib servers (first use the current
                   7593: one). C<$upass> should be the users password.
1.191     harris41 7594: 
                   7595: =item *
1.394     bowersj2 7596: X<homeserver()>
                   7597: B<homeserver($uname,$udom)>: find the server which has
                   7598: the user's directory and files (there must be only one), this caches
                   7599: the answer, and also caches if there is a borken connection.
1.191     harris41 7600: 
                   7601: =item *
1.394     bowersj2 7602: X<idget()>
                   7603: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7604: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7605: username, and only 1 username per ID in a specific domain) (returns
                   7606: hash: id=>name,id=>name)
1.191     harris41 7607: 
                   7608: =item *
1.394     bowersj2 7609: X<idrget()>
                   7610: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7611: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7612: 
                   7613: =item *
1.394     bowersj2 7614: X<idput()>
                   7615: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7616: 
                   7617: =item *
1.394     bowersj2 7618: X<rolesinit()>
                   7619: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7620: 
                   7621: =item *
1.551     albertel 7622: X<getsection()>
                   7623: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7624: course $cname, return section name/number or '' for "not in course"
                   7625: and '-1' for "no section"
                   7626: 
                   7627: =item *
1.394     bowersj2 7628: X<userenvironment()>
                   7629: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7630: passed in @what from the requested user's environment, returns a hash
                   7631: 
                   7632: =back
                   7633: 
                   7634: =head2 User Roles
                   7635: 
                   7636: =over 4
                   7637: 
                   7638: =item *
                   7639: 
                   7640: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7641: actions
                   7642:  F: full access
                   7643:  U,I,K: authentication modes (cxx only)
                   7644:  '': forbidden
                   7645:  1: user needs to choose course
                   7646:  2: browse allowed
1.766     albertel 7647:  A: passphrase authentication needed
1.243     albertel 7648: 
                   7649: =item *
                   7650: 
                   7651: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7652: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7653: and course level
                   7654: 
                   7655: =item *
                   7656: 
                   7657: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7658: explanation of a user role term
                   7659: 
                   7660: =back
                   7661: 
                   7662: =head2 User Modification
                   7663: 
                   7664: =over 4
                   7665: 
                   7666: =item *
                   7667: 
                   7668: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7669: user for the level given by URL.  Optional start and end dates (leave empty
                   7670: string or zero for "no date")
1.191     harris41 7671: 
                   7672: =item *
                   7673: 
1.243     albertel 7674: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7675: change a users, password, possible return values are: ok,
                   7676: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7677: refused
1.191     harris41 7678: 
                   7679: =item *
                   7680: 
1.243     albertel 7681: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7682: 
                   7683: =item *
                   7684: 
1.243     albertel 7685: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7686: modify user
1.191     harris41 7687: 
                   7688: =item *
                   7689: 
1.286     matthew  7690: modifystudent
                   7691: 
                   7692: modify a students enrollment and identification information.
                   7693: The course id is resolved based on the current users environment.  
                   7694: This means the envoking user must be a course coordinator or otherwise
                   7695: associated with a course.
                   7696: 
1.297     matthew  7697: This call is essentially a wrapper for lonnet::modifyuser and
                   7698: lonnet::modify_student_enrollment
1.286     matthew  7699: 
                   7700: Inputs: 
                   7701: 
                   7702: =over 4
                   7703: 
                   7704: =item B<$udom> Students loncapa domain
                   7705: 
                   7706: =item B<$uname> Students loncapa login name
                   7707: 
                   7708: =item B<$uid> Students id/student number
                   7709: 
                   7710: =item B<$umode> Students authentication mode
                   7711: 
                   7712: =item B<$upass> Students password
                   7713: 
                   7714: =item B<$first> Students first name
                   7715: 
                   7716: =item B<$middle> Students middle name
                   7717: 
                   7718: =item B<$last> Students last name
                   7719: 
                   7720: =item B<$gene> Students generation
                   7721: 
                   7722: =item B<$usec> Students section in course
                   7723: 
                   7724: =item B<$end> Unix time of the roles expiration
                   7725: 
                   7726: =item B<$start> Unix time of the roles start date
                   7727: 
                   7728: =item B<$forceid> If defined, allow $uid to be changed
                   7729: 
                   7730: =item B<$desiredhome> server to use as home server for student
                   7731: 
                   7732: =back
1.297     matthew  7733: 
                   7734: =item *
                   7735: 
                   7736: modify_student_enrollment
                   7737: 
                   7738: Change a students enrollment status in a class.  The environment variable
                   7739: 'role.request.course' must be defined for this function to proceed.
                   7740: 
                   7741: Inputs:
                   7742: 
                   7743: =over 4
                   7744: 
                   7745: =item $udom, students domain
                   7746: 
                   7747: =item $uname, students name
                   7748: 
                   7749: =item $uid, students user id
                   7750: 
                   7751: =item $first, students first name
                   7752: 
                   7753: =item $middle
                   7754: 
                   7755: =item $last
                   7756: 
                   7757: =item $gene
                   7758: 
                   7759: =item $usec
                   7760: 
                   7761: =item $end
                   7762: 
                   7763: =item $start
                   7764: 
                   7765: =back
                   7766: 
1.191     harris41 7767: 
                   7768: =item *
                   7769: 
1.243     albertel 7770: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7771: custom role; give a custom role to a user for the level given by URL.  Specify
                   7772: name and domain of role author, and role name
1.191     harris41 7773: 
                   7774: =item *
                   7775: 
1.243     albertel 7776: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7777: 
                   7778: =item *
                   7779: 
1.243     albertel 7780: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7781: 
                   7782: =back
                   7783: 
                   7784: =head2 Course Infomation
                   7785: 
                   7786: =over 4
1.191     harris41 7787: 
                   7788: =item *
                   7789: 
1.631     albertel 7790: coursedescription($courseid) : returns a hash of information about the
                   7791: specified course id, including all environment settings for the
                   7792: course, the description of the course will be in the hash under the
                   7793: key 'description'
1.191     harris41 7794: 
                   7795: =item *
                   7796: 
1.624     albertel 7797: resdata($name,$domain,$type,@which) : request for current parameter
                   7798: setting for a specific $type, where $type is either 'course' or 'user',
                   7799: @what should be a list of parameters to ask about. This routine caches
                   7800: answers for 5 minutes.
1.243     albertel 7801: 
                   7802: =back
                   7803: 
                   7804: =head2 Course Modification
                   7805: 
                   7806: =over 4
1.191     harris41 7807: 
                   7808: =item *
                   7809: 
1.243     albertel 7810: writecoursepref($courseid,%prefs) : write preferences (environment
                   7811: database) for a course
1.191     harris41 7812: 
                   7813: =item *
                   7814: 
1.243     albertel 7815: createcourse($udom,$description,$url) : make/modify course
                   7816: 
                   7817: =back
                   7818: 
                   7819: =head2 Resource Subroutines
                   7820: 
                   7821: =over 4
1.191     harris41 7822: 
                   7823: =item *
                   7824: 
1.243     albertel 7825: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7826: 
                   7827: =item *
                   7828: 
1.243     albertel 7829: repcopy($filename) : subscribes to the requested file, and attempts to
                   7830: replicate from the owning library server, Might return
1.607     raeburn  7831: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7832: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7833: resource. Expects the local filesystem pathname
                   7834: (/home/httpd/html/res/....)
                   7835: 
                   7836: =back
                   7837: 
                   7838: =head2 Resource Information
                   7839: 
                   7840: =over 4
1.191     harris41 7841: 
                   7842: =item *
                   7843: 
1.243     albertel 7844: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7845: a vairety of different possible values, $varname should be a request
                   7846: string, and the other parameters can be used to specify who and what
                   7847: one is asking about.
                   7848: 
                   7849: Possible values for $varname are environment.lastname (or other item
                   7850: from the envirnment hash), user.name (or someother aspect about the
                   7851: user), resource.0.maxtries (or some other part and parameter of a
                   7852: resource)
1.204     albertel 7853: 
                   7854: =item *
                   7855: 
1.243     albertel 7856: directcondval($number) : get current value of a condition; reads from a state
                   7857: string
1.204     albertel 7858: 
                   7859: =item *
                   7860: 
1.243     albertel 7861: condval($condidx) : value of condition index based on state
1.204     albertel 7862: 
                   7863: =item *
                   7864: 
1.243     albertel 7865: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7866: resource's metadata, $what should be either a specific key, or either
                   7867: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7868: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7869: 
                   7870: this function automatically caches all requests
1.191     harris41 7871: 
                   7872: =item *
                   7873: 
1.243     albertel 7874: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7875: network of library servers; returns file handle of where SQL and regex results
                   7876: will be stored for query
1.191     harris41 7877: 
                   7878: =item *
                   7879: 
1.243     albertel 7880: symbread($filename) : return symbolic list entry (filename argument optional);
                   7881: returns the data handle
1.191     harris41 7882: 
                   7883: =item *
                   7884: 
1.243     albertel 7885: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7886: a possible symb for the URL in $thisfn, and if is an encryypted
                   7887: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7888: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7889: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7890: 
1.191     harris41 7891: 
                   7892: =item *
                   7893: 
1.243     albertel 7894: symbclean($symb) : removes versions numbers from a symb, returns the
                   7895: cleaned symb
1.191     harris41 7896: 
                   7897: =item *
                   7898: 
1.243     albertel 7899: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7900: course map, user must be in a course for it to work.
1.191     harris41 7901: 
                   7902: =item *
                   7903: 
1.243     albertel 7904: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7905: 
                   7906: =item *
                   7907: 
1.243     albertel 7908: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7909: a random seed, all arguments are optional, if they aren't sent it uses the
                   7910: environment to derive them. Note: if symb isn't sent and it can't get one
                   7911: from &symbread it will use the current time as its return value
1.191     harris41 7912: 
                   7913: =item *
                   7914: 
1.243     albertel 7915: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7916: unfakeable, receipt
1.191     harris41 7917: 
                   7918: =item *
                   7919: 
1.620     albertel 7920: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7921: 
                   7922: =item *
                   7923: 
1.243     albertel 7924: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7925: 
                   7926: =item *
                   7927: 
1.243     albertel 7928: 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 7929: 
                   7930: =item *
                   7931: 
1.243     albertel 7932: 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 7933: 
                   7934: =item *
                   7935: 
1.243     albertel 7936: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7937: 
                   7938: =item *
                   7939: 
1.243     albertel 7940: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7941: forcing spreadsheet to reevaluate the resource scores next time.
                   7942: 
                   7943: =back
                   7944: 
                   7945: =head2 Storing/Retreiving Data
                   7946: 
                   7947: =over 4
1.191     harris41 7948: 
                   7949: =item *
                   7950: 
1.243     albertel 7951: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7952: for this url; hashref needs to be given and should be a \%hashname; the
                   7953: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7954: be derived from the env
1.191     harris41 7955: 
                   7956: =item *
                   7957: 
1.243     albertel 7958: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7959: uses critical subroutine
1.191     harris41 7960: 
                   7961: =item *
                   7962: 
1.243     albertel 7963: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7964: all args are optional
1.191     harris41 7965: 
                   7966: =item *
                   7967: 
1.717     albertel 7968: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7969: dumps the complete (or key matching regexp) namespace into a hash
                   7970: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7971: normally &store()ed into
                   7972: 
                   7973: $range should be either an integer '100' (give me the first 100
                   7974:                                            matching records)
                   7975:               or be  two integers sperated by a - with no spaces
                   7976:                  '30-50' (give me the 30th through the 50th matching
                   7977:                           records)
                   7978: 
                   7979: 
                   7980: =item *
                   7981: 
                   7982: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7983: replaces a &store() version of data with a replacement set of data
                   7984: for a particular resource in a namespace passed in the $storehash hash 
                   7985: reference
                   7986: 
                   7987: =item *
                   7988: 
1.243     albertel 7989: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7990: works very similar to store/cstore, but all data is stored in a
                   7991: temporary location and can be reset using tmpreset, $storehash should
                   7992: be a hash reference, returns nothing on success
1.191     harris41 7993: 
                   7994: =item *
                   7995: 
1.243     albertel 7996: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7997: similar to restore, but all data is stored in a temporary location and
                   7998: can be reset using tmpreset. Returns a hash of values on success,
                   7999: error string otherwise.
1.191     harris41 8000: 
                   8001: =item *
                   8002: 
1.243     albertel 8003: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8004: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8005: 
                   8006: =item *
                   8007: 
1.243     albertel 8008: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8009: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8010: 
                   8011: =item *
                   8012: 
1.243     albertel 8013: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8014: namesp ($udom and $uname are optional)
1.191     harris41 8015: 
                   8016: =item *
                   8017: 
1.702     albertel 8018: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8019: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8020: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8021: 
1.702     albertel 8022: $range should be either an integer '100' (give me the first 100
                   8023:                                            matching records)
                   8024:               or be  two integers sperated by a - with no spaces
                   8025:                  '30-50' (give me the 30th through the 50th matching
                   8026:                           records)
1.449     matthew  8027: =item *
                   8028: 
                   8029: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8030: $store can be a scalar, an array reference, or if the amount to be 
                   8031: incremented is > 1, a hash reference.
                   8032: 
                   8033: ($udom and $uname are optional)
1.191     harris41 8034: 
                   8035: =item *
                   8036: 
1.243     albertel 8037: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8038: ($udom and $uname are optional)
1.191     harris41 8039: 
                   8040: =item *
                   8041: 
1.243     albertel 8042: cput($namespace,$storehash,$udom,$uname) : critical put
                   8043: ($udom and $uname are optional)
1.191     harris41 8044: 
                   8045: =item *
                   8046: 
1.748     albertel 8047: newput($namespace,$storehash,$udom,$uname) :
                   8048: 
                   8049: Attempts to store the items in the $storehash, but only if they don't
                   8050: currently exist, if this succeeds you can be certain that you have 
                   8051: successfully created a new key value pair in the $namespace db.
                   8052: 
                   8053: 
                   8054: Args:
                   8055:  $namespace: name of database to store values to
                   8056:  $storehash: hashref to store to the db
                   8057:  $udom: (optional) domain of user containing the db
                   8058:  $uname: (optional) name of user caontaining the db
                   8059: 
                   8060: Returns:
                   8061:  'ok' -> succeeded in storing all keys of $storehash
                   8062:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8063:                         least <key> already existed in the db (other
                   8064:                         requested keys may also already exist)
                   8065:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8066:  'con_lost' -> unable to contact request server
                   8067:  'refused' -> action was not allowed by remote machine
                   8068: 
                   8069: 
                   8070: =item *
                   8071: 
1.243     albertel 8072: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8073: reference filled in from namesp (encrypts the return communication)
                   8074: ($udom and $uname are optional)
1.191     harris41 8075: 
                   8076: =item *
                   8077: 
1.243     albertel 8078: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8079: critical subroutine
                   8080: 
                   8081: =back
                   8082: 
                   8083: =head2 Network Status Functions
                   8084: 
                   8085: =over 4
1.191     harris41 8086: 
                   8087: =item *
                   8088: 
                   8089: dirlist($uri) : return directory list based on URI
                   8090: 
                   8091: =item *
                   8092: 
1.243     albertel 8093: spareserver() : find server with least workload from spare.tab
                   8094: 
                   8095: =back
                   8096: 
                   8097: =head2 Apache Request
                   8098: 
                   8099: =over 4
1.191     harris41 8100: 
                   8101: =item *
                   8102: 
1.243     albertel 8103: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8104: localhost, posts hash
                   8105: 
                   8106: =back
                   8107: 
                   8108: =head2 Data to String to Data
                   8109: 
                   8110: =over 4
1.191     harris41 8111: 
                   8112: =item *
                   8113: 
1.243     albertel 8114: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8115: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8116: 
                   8117: =item *
                   8118: 
1.243     albertel 8119: hashref2str($hashref) : convert a hashref into a string complete with
                   8120: escaping and '=' and '&' separators, supports elements that are
                   8121: arrayrefs and hashrefs
1.191     harris41 8122: 
                   8123: =item *
                   8124: 
1.243     albertel 8125: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8126: with escaping and '&' separators, supports elements that are arrayrefs
                   8127: and hashrefs
1.191     harris41 8128: 
                   8129: =item *
                   8130: 
1.243     albertel 8131: str2hash($string) : convert string to hash using unescaping and
                   8132: splitting on '=' and '&', supports elements that are arrayrefs and
                   8133: hashrefs
1.191     harris41 8134: 
                   8135: =item *
                   8136: 
1.243     albertel 8137: str2array($string) : convert string to hash using unescaping and
                   8138: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8139: 
                   8140: =back
                   8141: 
                   8142: =head2 Logging Routines
                   8143: 
                   8144: =over 4
                   8145: 
                   8146: These routines allow one to make log messages in the lonnet.log and
                   8147: lonnet.perm logfiles.
1.191     harris41 8148: 
                   8149: =item *
                   8150: 
1.243     albertel 8151: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8152: 
                   8153: =item *
                   8154: 
1.243     albertel 8155: logthis() : append message to the normal lonnet.log file, it gets
                   8156: preiodically rolled over and deleted.
1.191     harris41 8157: 
                   8158: =item *
                   8159: 
1.243     albertel 8160: logperm() : append a permanent message to lonnet.perm.log, this log
                   8161: file never gets deleted by any automated portion of the system, only
                   8162: messages of critical importance should go in here.
                   8163: 
                   8164: =back
                   8165: 
                   8166: =head2 General File Helper Routines
                   8167: 
                   8168: =over 4
1.191     harris41 8169: 
                   8170: =item *
                   8171: 
1.481     raeburn  8172: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8173: (a) files in /uploaded
                   8174:   (i) If a local copy of the file exists - 
                   8175:       compares modification date of local copy with last-modified date for 
                   8176:       definitive version stored on home server for course. If local copy is 
                   8177:       stale, requests a new version from the home server and stores it. 
                   8178:       If the original has been removed from the home server, then local copy 
                   8179:       is unlinked.
                   8180:   (ii) If local copy does not exist -
                   8181:       requests the file from the home server and stores it. 
                   8182:   
                   8183:   If $caller is 'uploadrep':  
                   8184:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8185:     for request for files originally uploaded via DOCS. 
                   8186:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8187:   
                   8188:   Otherwise:
                   8189:      This indicates a call from the content generation phase of the request.
                   8190:      -  returns the entire contents of the file or -1.
                   8191:      
                   8192: (b) files in /res
                   8193:    - returns the entire contents of a file or -1; 
                   8194:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8195: 
1.712     albertel 8196: 
                   8197: =item *
                   8198: 
                   8199: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8200:                   reference
                   8201: 
                   8202: returns either a stat() list of data about the file or an empty list
                   8203: if the file doesn't exist or couldn't find out about it (connection
                   8204: problems or user unknown)
                   8205: 
1.191     harris41 8206: =item *
                   8207: 
1.243     albertel 8208: filelocation($dir,$file) : returns file system location of a file
                   8209: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8210: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8211: and a file of ../bob will become /a/bob)
1.191     harris41 8212: 
                   8213: =item *
                   8214: 
                   8215: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8216: filelocation except for hrefs
                   8217: 
                   8218: =item *
                   8219: 
                   8220: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8221: 
1.243     albertel 8222: =back
                   8223: 
1.608     albertel 8224: =head2 Usererfile file routines (/uploaded*)
                   8225: 
                   8226: =over 4
                   8227: 
                   8228: =item *
                   8229: 
                   8230: userfileupload(): main rotine for putting a file in a user or course's
                   8231:                   filespace, arguments are,
                   8232: 
1.620     albertel 8233:  formname - required - this is the name of the element in $env where the
1.608     albertel 8234:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8235:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8236:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8237:  coursedoc - if true, store the file in the course of the active role
                   8238:              of the current user
                   8239:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8240:          if undefined, it will be placed in "unknown"
                   8241: 
                   8242:  (This routine calls clean_filename() to remove any dangerous
                   8243:  characters from the filename, and then calls finuserfileupload() to
                   8244:  complete the transaction)
                   8245: 
                   8246:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8247:  and /adm/notfound.html if unsuccessful
                   8248: 
                   8249: =item *
                   8250: 
                   8251: clean_filename(): routine for cleaing a filename up for storage in
                   8252:                  userfile space, argument is:
                   8253: 
                   8254:  filename - proposed filename
                   8255: 
                   8256: returns: the new clean filename
                   8257: 
                   8258: =item *
                   8259: 
                   8260: finishuserfileupload(): routine that creaes and sends the file to
                   8261: userspace, probably shouldn't be called directly
                   8262: 
                   8263:   docuname: username or courseid of destination for the file
                   8264:   docudom: domain of user/course of destination for the file
                   8265:   formname: same as for userfileupload()
                   8266:   fname: filename (inculding subdirectories) for the file
                   8267: 
                   8268:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8269:  and /adm/notfound.html if unsuccessful
                   8270: 
                   8271: =item *
                   8272: 
                   8273: renameuserfile(): renames an existing userfile to a new name
                   8274: 
                   8275:   Args:
                   8276:    docuname: username or courseid of destination for the file
                   8277:    docudom: domain of user/course of destination for the file
                   8278:    old: current file name (including any subdirs under userfiles)
                   8279:    new: desired file name (including any subdirs under userfiles)
                   8280: 
                   8281: =item *
                   8282: 
                   8283: mkdiruserfile(): creates a directory is a userfiles dir
                   8284: 
                   8285:   Args:
                   8286:    docuname: username or courseid of destination for the file
                   8287:    docudom: domain of user/course of destination for the file
                   8288:    dir: dir to create (including any subdirs under userfiles)
                   8289: 
                   8290: =item *
                   8291: 
                   8292: removeuserfile(): removes a file that exists in userfiles
                   8293: 
                   8294:   Args:
                   8295:    docuname: username or courseid of destination for the file
                   8296:    docudom: domain of user/course of destination for the file
                   8297:    fname: filname to delete (including any subdirs under userfiles)
                   8298: 
                   8299: =item *
                   8300: 
                   8301: removeuploadedurl(): convience function for removeuserfile()
                   8302: 
                   8303:   Args:
                   8304:    url:  a full /uploaded/... url to delete
                   8305: 
1.747     albertel 8306: =item * 
                   8307: 
                   8308: get_portfile_permissions():
                   8309:   Args:
                   8310:     domain: domain of user or course contain the portfolio files
                   8311:     user: name of user or num of course contain the portfolio files
                   8312:   Returns:
                   8313:     hashref of a dump of the proper file_permissions.db
                   8314:    
                   8315: 
                   8316: =item * 
                   8317: 
                   8318: get_access_controls():
                   8319: 
                   8320: Args:
                   8321:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8322:   group: (optional) the group you want the files associated with
                   8323:   file: (optional) the file you want access info on
                   8324: 
                   8325: Returns:
1.749     raeburn  8326:     a hash (keys are file names) of hashes containing
                   8327:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8328:         values are XML containing access control settings (see below) 
1.747     albertel 8329: 
                   8330: Internal notes:
                   8331: 
1.749     raeburn  8332:  access controls are stored in file_permissions.db as key=value pairs.
                   8333:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8334:         where scope -> public,guest,course,group,domains or users.
                   8335:               end -> UNIX time for end of access (0 -> no end date)
                   8336:               start -> UNIX time for start of access
                   8337: 
                   8338:     value -> XML description of access control
                   8339:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8340:             <start></start>
                   8341:             <end></end>
                   8342: 
                   8343:             <password></password>  for scope type = guest
                   8344: 
                   8345:             <domain></domain>     for scope type = course or group
                   8346:             <number></number>
                   8347:             <roles id="">
                   8348:              <role></role>
                   8349:              <access></access>
                   8350:              <section></section>
                   8351:              <group></group>
                   8352:             </roles>
                   8353: 
                   8354:             <dom></dom>         for scope type = domains
                   8355: 
                   8356:             <users>             for scope type = users
                   8357:              <user>
                   8358:               <uname></uname>
                   8359:               <udom></udom>
                   8360:              </user>
                   8361:             </users>
                   8362:            </scope> 
                   8363:               
                   8364:  Access data is also aggregated for each file in an additional key=value pair:
                   8365:  key -> path to file/file_name\0accesscontrol 
                   8366:  value -> reference to hash
                   8367:           hash contains key = value pairs
                   8368:           where key = uniqueID:scope_end_start
                   8369:                 value = UNIX time record was last updated
                   8370: 
                   8371:           Used to improve speed of look-ups of access controls for each file.  
                   8372:  
                   8373:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8374: 
                   8375: modify_access_controls():
                   8376: 
                   8377: Modifies access controls for a portfolio file
                   8378: Args
                   8379: 1. file name
                   8380: 2. reference to hash of required changes,
                   8381: 3. domain
                   8382: 4. username
                   8383:   where domain,username are the domain of the portfolio owner 
                   8384:   (either a user or a course) 
                   8385: 
                   8386: Returns:
                   8387: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8388: 2. result of deletions ('ok' or 'error', with error message).
                   8389: 3. reference to hash of any new or updated access controls.
                   8390: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8391:    key = integer (inbound ID)
                   8392:    value = uniqueID  
1.747     albertel 8393: 
1.608     albertel 8394: =back
                   8395: 
1.243     albertel 8396: =head2 HTTP Helper Routines
                   8397: 
                   8398: =over 4
                   8399: 
1.191     harris41 8400: =item *
                   8401: 
                   8402: escape() : unpack non-word characters into CGI-compatible hex codes
                   8403: 
                   8404: =item *
                   8405: 
                   8406: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8407: 
1.243     albertel 8408: =back
                   8409: 
                   8410: =head1 PRIVATE SUBROUTINES
                   8411: 
                   8412: =head2 Underlying communication routines (Shouldn't call)
                   8413: 
                   8414: =over 4
                   8415: 
                   8416: =item *
                   8417: 
                   8418: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8419: 
                   8420: =item *
                   8421: 
                   8422: reply() : uses subreply to send a message to remote machine, logs all failures
                   8423: 
                   8424: =item *
                   8425: 
                   8426: critical() : passes a critical message to another server; if cannot
                   8427: get through then place message in connection buffer directory and
                   8428: returns con_delayed, if incapable of saving message, returns
                   8429: con_failed
                   8430: 
                   8431: =item *
                   8432: 
                   8433: reconlonc() : tries to reconnect lonc client processes.
                   8434: 
                   8435: =back
                   8436: 
                   8437: =head2 Resource Access Logging
                   8438: 
                   8439: =over 4
                   8440: 
                   8441: =item *
                   8442: 
                   8443: flushcourselogs() : flush (save) buffer logs and access logs
                   8444: 
                   8445: =item *
                   8446: 
                   8447: courselog($what) : save message for course in hash
                   8448: 
                   8449: =item *
                   8450: 
                   8451: courseacclog($what) : save message for course using &courselog().  Perform
                   8452: special processing for specific resource types (problems, exams, quizzes, etc).
                   8453: 
1.191     harris41 8454: =item *
                   8455: 
                   8456: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8457: as a PerlChildExitHandler
1.243     albertel 8458: 
                   8459: =back
                   8460: 
                   8461: =head2 Other
                   8462: 
                   8463: =over 4
                   8464: 
                   8465: =item *
                   8466: 
                   8467: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8468: 
                   8469: =back
                   8470: 
                   8471: =cut

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