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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.807   ! albertel    4: # $Id: lonnet.pm,v 1.806 2006/11/21 20:58:06 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';
1.807   ! albertel   57: use LONCAPA qw(:DEFAULT :match);
1.740     www        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.807   ! albertel  193:     &logthis("$cmd $server");
1.205     www       194:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  195:     my $answer=subreply($cmd,$server);
1.65      www       196:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  197:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       198:                 " $cmd to $server returned $answer</font>");
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: # ----------------------------------------------------------- Send USR1 to lonc
                    204: 
                    205: sub reconlonc {
                    206:     my $peerfile=shift;
                    207:     &logthis("Trying to reconnect for $peerfile");
                    208:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  209:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  210: 	my $loncpid=<$fh>;
                    211:         chomp($loncpid);
                    212:         if (kill 0 => $loncpid) {
                    213: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    214:             kill USR1 => $loncpid;
                    215:             sleep 1;
                    216:             if (-e "$peerfile") { return; }
                    217:             &logthis("$peerfile still not there, give it another try");
                    218:             sleep 5;
                    219:             if (-e "$peerfile") { return; }
1.12      www       220:             &logthis(
1.672     albertel  221:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  222:         } else {
1.12      www       223: 	    &logthis(
1.672     albertel  224:                "<font color=\"blue\">WARNING:".
1.12      www       225:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  226:         }
                    227:     } else {
1.672     albertel  228:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  229:     }
                    230: }
                    231: 
                    232: # ------------------------------------------------------ Critical communication
1.12      www       233: 
1.1       albertel  234: sub critical {
                    235:     my ($cmd,$server)=@_;
1.89      www       236:     unless ($hostname{$server}) {
1.672     albertel  237:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       238:                " Critical message to unknown server ($server)</font>");
                    239:         return 'no_such_host';
                    240:     }
1.1       albertel  241:     my $answer=reply($cmd,$server);
                    242:     if ($answer eq 'con_lost') {
                    243: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  244: 	my $answer=reply($cmd,$server);
1.1       albertel  245:         if ($answer eq 'con_lost') {
                    246:             my $now=time;
                    247:             my $middlename=$cmd;
1.5       www       248:             $middlename=substr($middlename,0,16);
1.1       albertel  249:             $middlename=~s/\W//g;
                    250:             my $dfilename=
1.305     www       251:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    252:             $dumpcount++;
1.1       albertel  253:             {
1.448     albertel  254: 		my $dfh;
                    255: 		if (open($dfh,">$dfilename")) {
                    256: 		    print $dfh "$cmd\n"; 
                    257: 		    close($dfh);
                    258: 		}
1.1       albertel  259:             }
                    260:             sleep 2;
                    261:             my $wcmd='';
                    262:             {
1.448     albertel  263: 		my $dfh;
                    264: 		if (open($dfh,"<$dfilename")) {
                    265: 		    $wcmd=<$dfh>; 
                    266: 		    close($dfh);
                    267: 		}
1.1       albertel  268:             }
                    269:             chomp($wcmd);
1.7       www       270:             if ($wcmd eq $cmd) {
1.672     albertel  271: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       272:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  273:                 &logperm("D:$server:$cmd");
                    274: 	        return 'con_delayed';
                    275:             } else {
1.672     albertel  276:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       277:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  278:                 &logperm("F:$server:$cmd");
                    279:                 return 'con_failed';
                    280:             }
                    281:         }
                    282:     }
                    283:     return $answer;
1.405     albertel  284: }
                    285: 
1.755     albertel  286: # ------------------------------------------- check if return value is an error
                    287: 
                    288: sub error {
                    289:     my ($result) = @_;
1.756     albertel  290:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  291: 	if ($2 == 2) { return undef; }
                    292: 	return $1;
                    293:     }
                    294:     return undef;
                    295: }
                    296: 
1.783     albertel  297: sub convert_and_load_session_env {
                    298:     my ($lonidsdir,$handle)=@_;
                    299:     my @profile;
                    300:     {
                    301: 	open(my $idf,"$lonidsdir/$handle.id");
                    302: 	flock($idf,LOCK_SH);
                    303: 	@profile=<$idf>;
                    304: 	close($idf);
                    305:     }
                    306:     my %temp_env;
                    307:     foreach my $line (@profile) {
1.786     albertel  308: 	if ($line !~ m/=/) {
                    309: 	    return 0;
                    310: 	}
1.783     albertel  311: 	chomp($line);
                    312: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    313: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    314:     }
                    315:     unlink("$lonidsdir/$handle.id");
                    316:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    317: 	    0640)) {
                    318: 	%disk_env = %temp_env;
                    319: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    320: 	untie(%disk_env);
                    321:     }
1.786     albertel  322:     return 1;
1.783     albertel  323: }
                    324: 
1.374     www       325: # ------------------------------------------- Transfer profile into environment
1.780     albertel  326: my $env_loaded;
                    327: sub transfer_profile_to_env {
1.788     albertel  328:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    329:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       330: 
1.720     albertel  331:     if (!defined($lonidsdir)) {
                    332: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    333:     }
                    334:     if (!defined($handle)) {
                    335:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    336:     }
                    337: 
1.786     albertel  338:     my $convert;
                    339:     {
                    340:     	open(my $idf,"$lonidsdir/$handle.id");
                    341: 	flock($idf,LOCK_SH);
                    342: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    343: 		&GDBM_READER(),0640)) {
                    344: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    345: 	    untie(%disk_env);
                    346: 	} else {
                    347: 	    $convert = 1;
                    348: 	}
                    349:     }
                    350:     if ($convert) {
                    351: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    352: 	    &logthis("Failed to load session, or convert session.");
                    353: 	}
1.374     www       354:     }
1.783     albertel  355: 
1.786     albertel  356:     my %remove;
1.783     albertel  357:     while ( my $envname = each(%env) ) {
1.433     matthew   358:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    359:             if ($time < time-300) {
1.783     albertel  360:                 $remove{$key}++;
1.433     matthew   361:             }
                    362:         }
                    363:     }
1.783     albertel  364: 
1.619     albertel  365:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  366:     $env_loaded=1;
1.783     albertel  367:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   368:         &delenv($expired_key);
1.374     www       369:     }
1.1       albertel  370: }
                    371: 
1.5       www       372: # ---------------------------------------------------------- Append Environment
                    373: 
                    374: sub appenv {
1.6       www       375:     my %newenv=@_;
1.692     albertel  376:     foreach my $key (keys(%newenv)) {
                    377: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  378:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  379:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       380:                 .'</font>');
1.692     albertel  381: 	    delete($newenv{$key});
1.35      www       382:         } else {
1.692     albertel  383:             $env{$key}=$newenv{$key};
1.35      www       384:         }
1.191     harris41  385:     }
1.783     albertel  386:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    387: 	    0640)) {
                    388: 	while (my ($key,$value) = each(%newenv)) {
                    389: 	    $disk_env{$key} = $value;
1.448     albertel  390: 	}
1.783     albertel  391: 	untie(%disk_env);
1.56      www       392:     }
                    393:     return 'ok';
                    394: }
                    395: # ----------------------------------------------------- Delete from Environment
                    396: 
                    397: sub delenv {
                    398:     my $delthis=shift;
                    399:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  400:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       401:                 "Attempt to delete from environment ".$delthis);
                    402:         return 'error';
                    403:     }
1.783     albertel  404:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    405: 	    0640)) {
                    406: 	foreach my $key (keys(%disk_env)) {
                    407: 	    if ($key=~/^$delthis/) { 
1.619     albertel  408:                 delete($env{$key});
1.783     albertel  409:                 delete($disk_env{$key});
1.473     matthew   410:             }
1.448     albertel  411: 	}
1.783     albertel  412: 	untie(%disk_env);
1.5       www       413:     }
                    414:     return 'ok';
1.369     albertel  415: }
                    416: 
1.790     albertel  417: sub get_env_multiple {
                    418:     my ($name) = @_;
                    419:     my @values;
                    420:     if (defined($env{$name})) {
                    421:         # exists is it an array
                    422:         if (ref($env{$name})) {
                    423:             @values=@{ $env{$name} };
                    424:         } else {
                    425:             $values[0]=$env{$name};
                    426:         }
                    427:     }
                    428:     return(@values);
                    429: }
                    430: 
1.369     albertel  431: # ------------------------------------------ Find out current server userload
                    432: # there is a copy in lond
                    433: sub userload {
                    434:     my $numusers=0;
                    435:     {
                    436: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    437: 	my $filename;
                    438: 	my $curtime=time;
                    439: 	while ($filename=readdir(LONIDS)) {
                    440: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  441: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  442: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  443: 	}
                    444: 	closedir(LONIDS);
                    445:     }
                    446:     my $userloadpercent=0;
                    447:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    448:     if ($maxuserload) {
1.371     albertel  449: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  450:     }
1.372     albertel  451:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  452:     return $userloadpercent;
1.283     www       453: }
                    454: 
                    455: # ------------------------------------------ Fight off request when overloaded
                    456: 
                    457: sub overloaderror {
                    458:     my ($r,$checkserver)=@_;
                    459:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    460:     my $loadavg;
                    461:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  462:        open(my $loadfile,'/proc/loadavg');
1.283     www       463:        $loadavg=<$loadfile>;
                    464:        $loadavg =~ s/\s.*//g;
1.285     matthew   465:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  466:        close($loadfile);
1.283     www       467:     } else {
                    468:        $loadavg=&reply('load',$checkserver);
                    469:     }
1.285     matthew   470:     my $overload=$loadavg-100;
1.283     www       471:     if ($overload>0) {
1.285     matthew   472: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       473:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       474:         return 413;
1.283     www       475:     }    
                    476:     return '';
1.5       www       477: }
1.1       albertel  478: 
                    479: # ------------------------------ Find server with least workload from spare.tab
1.11      www       480: 
1.1       albertel  481: sub spareserver {
1.670     albertel  482:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  483:     my $spare_server;
1.370     albertel  484:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  485:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    486:                                                      :  $userloadpercent;
                    487:     
                    488:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    489: 	($spare_server, $lowest_load) =
                    490: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    491:     }
                    492: 
                    493:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    494: 
                    495:     if (!$found_server) {
                    496: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    497: 	    ($spare_server, $lowest_load) =
                    498: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    499: 	}
                    500:     }
                    501: 
                    502:     if (!$want_server_name) {
                    503: 	$spare_server="http://$hostname{$spare_server}";
                    504:     }
                    505:     return $spare_server;
                    506: }
                    507: 
                    508: sub compare_server_load {
                    509:     my ($try_server, $spare_server, $lowest_load) = @_;
                    510: 
                    511:     my $loadans     = &reply('load',    $try_server);
                    512:     my $userloadans = &reply('userload',$try_server);
                    513: 
                    514:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    515: 	next; #didn't get a number from the server
                    516:     }
                    517: 
                    518:     my $load;
                    519:     if ($loadans =~ /\d/) {
                    520: 	if ($userloadans =~ /\d/) {
                    521: 	    #both are numbers, pick the bigger one
                    522: 	    $load = ($loadans > $userloadans) ? $loadans 
                    523: 		                              : $userloadans;
1.411     albertel  524: 	} else {
1.784     albertel  525: 	    $load = $loadans;
1.411     albertel  526: 	}
1.784     albertel  527:     } else {
                    528: 	$load = $userloadans;
                    529:     }
                    530: 
                    531:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    532: 	$spare_server = $try_server;
                    533: 	$lowest_load  = $load;
1.370     albertel  534:     }
1.784     albertel  535:     return ($spare_server,$lowest_load);
1.202     matthew   536: }
                    537: # --------------------------------------------- Try to change a user's password
                    538: 
                    539: sub changepass {
1.799     raeburn   540:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   541:     $currentpass = &escape($currentpass);
                    542:     $newpass     = &escape($newpass);
1.799     raeburn   543:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   544: 		       $server);
                    545:     if (! $answer) {
                    546: 	&logthis("No reply on password change request to $server ".
                    547: 		 "by $uname in domain $udom.");
                    548:     } elsif ($answer =~ "^ok") {
                    549:         &logthis("$uname in $udom successfully changed their password ".
                    550: 		 "on $server.");
                    551:     } elsif ($answer =~ "^pwchange_failure") {
                    552: 	&logthis("$uname in $udom was unable to change their password ".
                    553: 		 "on $server.  The action was blocked by either lcpasswd ".
                    554: 		 "or pwchange");
                    555:     } elsif ($answer =~ "^non_authorized") {
                    556:         &logthis("$uname in $udom did not get their password correct when ".
                    557: 		 "attempting to change it on $server.");
                    558:     } elsif ($answer =~ "^auth_mode_error") {
                    559:         &logthis("$uname in $udom attempted to change their password despite ".
                    560: 		 "not being locally or internally authenticated on $server.");
                    561:     } elsif ($answer =~ "^unknown_user") {
                    562:         &logthis("$uname in $udom attempted to change their password ".
                    563: 		 "on $server but were unable to because $server is not ".
                    564: 		 "their home server.");
                    565:     } elsif ($answer =~ "^refused") {
                    566: 	&logthis("$server refused to change $uname in $udom password because ".
                    567: 		 "it was sent an unencrypted request to change the password.");
                    568:     }
                    569:     return $answer;
1.1       albertel  570: }
                    571: 
1.169     harris41  572: # ----------------------- Try to determine user's current authentication scheme
                    573: 
                    574: sub queryauthenticate {
                    575:     my ($uname,$udom)=@_;
1.456     albertel  576:     my $uhome=&homeserver($uname,$udom);
                    577:     if (!$uhome) {
                    578: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    579: 	return 'no_host';
                    580:     }
                    581:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    582:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    583: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  584:     }
1.456     albertel  585:     return $answer;
1.169     harris41  586: }
                    587: 
1.1       albertel  588: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       589: 
1.1       albertel  590: sub authenticate {
                    591:     my ($uname,$upass,$udom)=@_;
1.807   ! albertel  592:     $upass=&escape($upass);
        !           593:     $uname= &LONCAPA::clean_username($uname);
1.471     albertel  594:     my $uhome=&homeserver($uname,$udom);
                    595:     if (!$uhome) {
                    596: 	&logthis("User $uname at $udom is unknown in authenticate");
                    597: 	return 'no_host';
1.1       albertel  598:     }
1.471     albertel  599:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    600:     if ($answer eq 'authorized') {
                    601: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    602: 	return $uhome; 
                    603:     }
                    604:     if ($answer eq 'non_authorized') {
                    605: 	&logthis("User $uname at $udom rejected by $uhome");
                    606: 	return 'no_host'; 
1.9       www       607:     }
1.471     albertel  608:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  609:     return 'no_host';
                    610: }
                    611: 
                    612: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       613: 
1.599     albertel  614: my %homecache;
1.1       albertel  615: sub homeserver {
1.230     stredwic  616:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  617:     my $index="$uname:$udom";
1.426     albertel  618: 
1.599     albertel  619:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  620:     my $tryserver;
                    621:     foreach $tryserver (keys %libserv) {
1.230     stredwic  622:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  623: 		 exists($badServerCache{$tryserver}));
1.1       albertel  624: 	if ($hostdom{$tryserver} eq $udom) {
                    625:            my $answer=reply("home:$udom:$uname",$tryserver);
                    626:            if ($answer eq 'found') { 
1.599     albertel  627: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  628:            } elsif ($answer eq 'no_host') {
                    629: 	       $badServerCache{$tryserver}=1;
1.221     matthew   630:            }
1.1       albertel  631:        }
                    632:     }    
                    633:     return 'no_host';
1.70      www       634: }
                    635: 
                    636: # ------------------------------------- Find the usernames behind a list of IDs
                    637: 
                    638: sub idget {
                    639:     my ($udom,@ids)=@_;
                    640:     my %returnhash=();
                    641:     
                    642:     my $tryserver;
                    643:     foreach $tryserver (keys %libserv) {
                    644:        if ($hostdom{$tryserver} eq $udom) {
                    645: 	  my $idlist=join('&',@ids);
                    646:           $idlist=~tr/A-Z/a-z/; 
                    647: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    648:           my @answer=();
1.76      www       649:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       650: 	      @answer=split(/\&/,$reply);
                    651:           }                    ;
                    652:           my $i;
                    653:           for ($i=0;$i<=$#ids;$i++) {
                    654:               if ($answer[$i]) {
                    655: 		  $returnhash{$ids[$i]}=$answer[$i];
                    656:               } 
                    657:           }
                    658:        }
                    659:     }    
                    660:     return %returnhash;
                    661: }
                    662: 
                    663: # ------------------------------------- Find the IDs behind a list of usernames
                    664: 
                    665: sub idrget {
                    666:     my ($udom,@unames)=@_;
                    667:     my %returnhash=();
1.800     albertel  668:     foreach my $uname (@unames) {
                    669:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  670:     }
1.70      www       671:     return %returnhash;
                    672: }
                    673: 
                    674: # ------------------------------- Store away a list of names and associated IDs
                    675: 
                    676: sub idput {
                    677:     my ($udom,%ids)=@_;
                    678:     my %servers=();
1.800     albertel  679:     foreach my $uname (keys(%ids)) {
                    680: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    681:         my $uhom=&homeserver($uname,$udom);
1.70      www       682:         if ($uhom ne 'no_host') {
1.800     albertel  683:             my $id=&escape($ids{$uname});
1.70      www       684:             $id=~tr/A-Z/a-z/;
1.800     albertel  685:             my $esc_unam=&escape($uname);
1.70      www       686: 	    if ($servers{$uhom}) {
1.800     albertel  687: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       688:             } else {
1.800     albertel  689:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       690:             }
                    691:         }
1.191     harris41  692:     }
1.800     albertel  693:     foreach my $server (keys(%servers)) {
                    694:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  695:     }
1.344     www       696: }
                    697: 
1.806     raeburn   698: # ------------------------------------------- get items from domain db files   
                    699: 
                    700: sub get_dom {
                    701:     my ($namespace,$storearr,$udom)=@_;
                    702:     my $items='';
                    703:     foreach my $item (@$storearr) {
                    704:         $items.=&escape($item).'&';
                    705:     }
                    706:     $items=~s/\&$//;
                    707:     if (!$udom) { $udom=$env{'user.domain'}; }
                    708:     if (exists($domain_primary{$udom})) {
                    709:         my $uhome=$domain_primary{$udom};
                    710:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    711:         my @pairs=split(/\&/,$rep);
                    712:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    713:             return @pairs;
                    714:         }
                    715:         my %returnhash=();
                    716:         my $i=0;
                    717:         foreach my $item (@$storearr) {
                    718:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    719:             $i++;
                    720:         }
                    721:         return %returnhash;
                    722:     } else {
                    723:         &logthis("get_dom failed - no primary domain server for $udom");
                    724:     }
                    725: }
                    726: 
                    727: # -------------------------------------------- put items in domain db files 
                    728: 
                    729: sub put_dom {
                    730:     my ($namespace,$storehash,$udom)=@_;
                    731:     if (!$udom) { $udom=$env{'user.domain'}; }
                    732:     if (exists($domain_primary{$udom})) {
                    733:         my $uhome=$domain_primary{$udom};
                    734:         my $items='';
                    735:         foreach my $item (keys(%$storehash)) {
                    736:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    737:         }
                    738:         $items=~s/\&$//;
                    739:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    740:     } else {
                    741:         &logthis("put_dom failed - no primary domain server for $udom");
                    742:     }
                    743: }
                    744: 
1.344     www       745: # --------------------------------------------------- Assign a key to a student
                    746: 
                    747: sub assign_access_key {
1.364     www       748: #
                    749: # a valid key looks like uname:udom#comments
                    750: # comments are being appended
                    751: #
1.498     www       752:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    753:     $kdom=
1.620     albertel  754:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       755:     $knum=
1.620     albertel  756:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       757:     $cdom=
1.620     albertel  758:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       759:     $cnum=
1.620     albertel  760:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    761:     $udom=$env{'user.name'} unless (defined($udom));
                    762:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       763:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       764:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  765:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       766:                                                   # assigned to this person
                    767:                                                   # - this should not happen,
1.345     www       768:                                                   # unless something went wrong
                    769:                                                   # the first time around
                    770: # ready to assign
1.364     www       771:         $logentry=$1.'; '.$logentry;
1.496     www       772:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       773:                                                  $kdom,$knum) eq 'ok') {
1.345     www       774: # key now belongs to user
1.346     www       775: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       776:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    777:                 &appenv('environment.'.$envkey => $ckey);
                    778:                 return 'ok';
                    779:             } else {
                    780:                 return 
                    781:   'error: Count not permanently assign key, will need to be re-entered later.';
                    782: 	    }
                    783:         } else {
                    784:             return 'error: Could not assign key, try again later.';
                    785:         }
1.364     www       786:     } elsif (!$existing{$ckey}) {
1.345     www       787: # the key does not exist
                    788: 	return 'error: The key does not exist';
                    789:     } else {
                    790: # the key is somebody else's
                    791: 	return 'error: The key is already in use';
                    792:     }
1.344     www       793: }
                    794: 
1.364     www       795: # ------------------------------------------ put an additional comment on a key
                    796: 
                    797: sub comment_access_key {
                    798: #
                    799: # a valid key looks like uname:udom#comments
                    800: # comments are being appended
                    801: #
                    802:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    803:     $cdom=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       805:     $cnum=
1.620     albertel  806:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       807:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    808:     if ($existing{$ckey}) {
                    809:         $existing{$ckey}.='; '.$logentry;
                    810: # ready to assign
1.367     www       811:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       812:                                                  $cdom,$cnum) eq 'ok') {
                    813: 	    return 'ok';
                    814:         } else {
                    815: 	    return 'error: Count not store comment.';
                    816:         }
                    817:     } else {
                    818: # the key does not exist
                    819: 	return 'error: The key does not exist';
                    820:     }
                    821: }
                    822: 
1.344     www       823: # ------------------------------------------------------ Generate a set of keys
                    824: 
                    825: sub generate_access_keys {
1.364     www       826:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       827:     $cdom=
1.620     albertel  828:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       829:     $cnum=
1.620     albertel  830:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       831:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       832:     unless (($cdom) && ($cnum)) { return 0; }
                    833:     if ($number>10000) { return 0; }
                    834:     sleep(2); # make sure don't get same seed twice
                    835:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    836:     my $total=0;
                    837:     for (my $i=1;$i<=$number;$i++) {
                    838:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    839:                   sprintf("%lx",int(100000*rand)).'-'.
                    840:                   sprintf("%lx",int(100000*rand));
                    841:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    842:        $newkey=~s/0/h/g; # and also 0 and O
                    843:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    844:        if ($existing{$newkey}) {
                    845:            $i--;
                    846:        } else {
1.364     www       847: 	  if (&put('accesskeys',
                    848:               { $newkey => '# generated '.localtime().
1.620     albertel  849:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       850:                            '; '.$logentry },
                    851: 		   $cdom,$cnum) eq 'ok') {
1.344     www       852:               $total++;
                    853: 	  }
                    854:        }
                    855:     }
1.620     albertel  856:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       857:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    858:     return $total;
                    859: }
                    860: 
                    861: # ------------------------------------------------------- Validate an accesskey
                    862: 
                    863: sub validate_access_key {
                    864:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    865:     $cdom=
1.620     albertel  866:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       867:     $cnum=
1.620     albertel  868:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    869:     $udom=$env{'user.domain'} unless (defined($udom));
                    870:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       871:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  872:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       873: }
                    874: 
                    875: # ------------------------------------- Find the section of student in a course
1.652     albertel  876: sub devalidate_getsection_cache {
                    877:     my ($udom,$unam,$courseid)=@_;
                    878:     my $hashid="$udom:$unam:$courseid";
                    879:     &devalidate_cache_new('getsection',$hashid);
                    880: }
1.298     matthew   881: 
                    882: sub getsection {
                    883:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  884:     my $cachetime=1800;
1.551     albertel  885: 
                    886:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  887:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  888:     if (defined($cached)) { return $result; }
                    889: 
1.298     matthew   890:     my %Pending; 
                    891:     my %Expired;
                    892:     #
                    893:     # Each role can either have not started yet (pending), be active, 
                    894:     #    or have expired.
                    895:     #
                    896:     # If there is an active role, we are done.
                    897:     #
                    898:     # If there is more than one role which has not started yet, 
                    899:     #     choose the one which will start sooner
                    900:     # If there is one role which has not started yet, return it.
                    901:     #
                    902:     # If there is more than one expired role, choose the one which ended last.
                    903:     # If there is a role which has expired, return it.
                    904:     #
1.800     albertel  905:     foreach my $line (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    906: 					&homeserver($unam,$udom)))) {
                    907:         my ($key,$value)=split(/\=/,$line,2);
1.298     matthew   908:         $key=&unescape($key);
1.479     albertel  909:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   910:         my $section=$1;
                    911:         if ($key eq $courseid.'_st') { $section=''; }
                    912:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    913:         my $now=time;
1.548     albertel  914:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   915:             $Expired{$end}=$section;
                    916:             next;
                    917:         }
1.548     albertel  918:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   919:             $Pending{$start}=$section;
                    920:             next;
                    921:         }
1.599     albertel  922:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   923:     }
                    924:     #
                    925:     # Presumedly there will be few matching roles from the above
                    926:     # loop and the sorting time will be negligible.
                    927:     if (scalar(keys(%Pending))) {
                    928:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  929:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   930:     } 
                    931:     if (scalar(keys(%Expired))) {
                    932:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    933:         my $time = pop(@sorted);
1.599     albertel  934:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   935:     }
1.599     albertel  936:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   937: }
1.70      www       938: 
1.599     albertel  939: sub save_cache {
                    940:     &purge_remembered();
1.722     albertel  941:     #&Apache::loncommon::validate_page();
1.620     albertel  942:     undef(%env);
1.780     albertel  943:     undef($env_loaded);
1.599     albertel  944: }
1.452     albertel  945: 
1.599     albertel  946: my $to_remember=-1;
                    947: my %remembered;
                    948: my %accessed;
                    949: my $kicks=0;
                    950: my $hits=0;
                    951: sub devalidate_cache_new {
                    952:     my ($name,$id,$debug) = @_;
                    953:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    954:     $id=&escape($name.':'.$id);
                    955:     $memcache->delete($id);
                    956:     delete($remembered{$id});
                    957:     delete($accessed{$id});
                    958: }
                    959: 
                    960: sub is_cached_new {
                    961:     my ($name,$id,$debug) = @_;
                    962:     $id=&escape($name.':'.$id);
                    963:     if (exists($remembered{$id})) {
                    964: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    965: 	$accessed{$id}=[&gettimeofday()];
                    966: 	$hits++;
                    967: 	return ($remembered{$id},1);
                    968:     }
                    969:     my $value = $memcache->get($id);
                    970:     if (!(defined($value))) {
                    971: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  972: 	return (undef,undef);
1.416     albertel  973:     }
1.599     albertel  974:     if ($value eq '__undef__') {
                    975: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    976: 	$value=undef;
                    977:     }
                    978:     &make_room($id,$value,$debug);
                    979:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    980:     return ($value,1);
                    981: }
                    982: 
                    983: sub do_cache_new {
                    984:     my ($name,$id,$value,$time,$debug) = @_;
                    985:     $id=&escape($name.':'.$id);
                    986:     my $setvalue=$value;
                    987:     if (!defined($setvalue)) {
                    988: 	$setvalue='__undef__';
                    989:     }
1.623     albertel  990:     if (!defined($time) ) {
                    991: 	$time=600;
                    992:     }
1.599     albertel  993:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  994:     $memcache->set($id,$setvalue,$time);
                    995:     # need to make a copy of $value
                    996:     #&make_room($id,$value,$debug);
1.599     albertel  997:     return $value;
                    998: }
                    999: 
                   1000: sub make_room {
                   1001:     my ($id,$value,$debug)=@_;
                   1002:     $remembered{$id}=$value;
                   1003:     if ($to_remember<0) { return; }
                   1004:     $accessed{$id}=[&gettimeofday()];
                   1005:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1006:     my $to_kick;
                   1007:     my $max_time=0;
                   1008:     foreach my $other (keys(%accessed)) {
                   1009: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1010: 	    $to_kick=$other;
                   1011: 	    $max_time=&tv_interval($accessed{$other});
                   1012: 	}
                   1013:     }
                   1014:     delete($remembered{$to_kick});
                   1015:     delete($accessed{$to_kick});
                   1016:     $kicks++;
                   1017:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1018:     return;
                   1019: }
                   1020: 
1.599     albertel 1021: sub purge_remembered {
1.604     albertel 1022:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1023:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1024:     undef(%remembered);
                   1025:     undef(%accessed);
1.428     albertel 1026: }
1.70      www      1027: # ------------------------------------- Read an entry from a user's environment
                   1028: 
                   1029: sub userenvironment {
                   1030:     my ($udom,$unam,@what)=@_;
                   1031:     my %returnhash=();
                   1032:     my @answer=split(/\&/,
                   1033:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1034:                       &homeserver($unam,$udom)));
                   1035:     my $i;
                   1036:     for ($i=0;$i<=$#what;$i++) {
                   1037: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1038:     }
                   1039:     return %returnhash;
1.1       albertel 1040: }
                   1041: 
1.617     albertel 1042: # ---------------------------------------------------------- Get a studentphoto
                   1043: sub studentphoto {
                   1044:     my ($udom,$unam,$ext) = @_;
                   1045:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1046:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1047:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1048:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1049:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1050:             } else {
                   1051:                 my ($result,$perm_reqd)=
1.707     albertel 1052: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1053:                 if ($result eq 'ok') {
                   1054:                     if (!($perm_reqd eq 'yes')) {
                   1055:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1056:                     }
                   1057:                 }
                   1058:             }
                   1059:         }
                   1060:     } else {
                   1061:         my ($result,$perm_reqd) = 
1.707     albertel 1062: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1063:         if ($result eq 'ok') {
                   1064:             if (!($perm_reqd eq 'yes')) {
                   1065:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1066:             }
                   1067:         }
                   1068:     }
                   1069:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1070: }
                   1071: 
                   1072: sub retrievestudentphoto {
                   1073:     my ($udom,$unam,$ext,$type) = @_;
                   1074:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1075:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1076:     if ($ret eq 'ok') {
                   1077:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1078:         if ($type eq 'thumbnail') {
                   1079:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1080:         }
                   1081:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1082:         return $tokenurl;
                   1083:     } else {
                   1084:         if ($type eq 'thumbnail') {
                   1085:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1086:         } else { 
                   1087:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1088:         }
1.617     albertel 1089:     }
                   1090: }
                   1091: 
1.263     www      1092: # -------------------------------------------------------------------- New chat
                   1093: 
                   1094: sub chatsend {
1.724     raeburn  1095:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1096:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1097:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1098:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1099:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1100: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1101: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1102: }
                   1103: 
                   1104: # ------------------------------------------ Find current version of a resource
                   1105: 
                   1106: sub getversion {
                   1107:     my $fname=&clutter(shift);
                   1108:     unless ($fname=~/^\/res\//) { return -1; }
                   1109:     return &currentversion(&filelocation('',$fname));
                   1110: }
                   1111: 
                   1112: sub currentversion {
                   1113:     my $fname=shift;
1.599     albertel 1114:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1115:     if (defined($cached)) { return $result; }
1.292     www      1116:     my $author=$fname;
                   1117:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1118:     my ($udom,$uname)=split(/\//,$author);
                   1119:     my $home=homeserver($uname,$udom);
                   1120:     if ($home eq 'no_host') { 
                   1121:         return -1; 
                   1122:     }
                   1123:     my $answer=reply("currentversion:$fname",$home);
                   1124:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1125: 	return -1;
                   1126:     }
1.599     albertel 1127:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1128: }
                   1129: 
1.1       albertel 1130: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1131: 
1.1       albertel 1132: sub subscribe {
                   1133:     my $fname=shift;
1.761     raeburn  1134:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1135:     $fname=~s/[\n\r]//g;
1.1       albertel 1136:     my $author=$fname;
                   1137:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1138:     my ($udom,$uname)=split(/\//,$author);
                   1139:     my $home=homeserver($uname,$udom);
1.335     albertel 1140:     if ($home eq 'no_host') {
                   1141:         return 'not_found';
1.1       albertel 1142:     }
                   1143:     my $answer=reply("sub:$fname",$home);
1.64      www      1144:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1145: 	$answer.=' by '.$home;
                   1146:     }
1.1       albertel 1147:     return $answer;
                   1148: }
                   1149:     
1.8       www      1150: # -------------------------------------------------------------- Replicate file
                   1151: 
                   1152: sub repcopy {
                   1153:     my $filename=shift;
1.23      www      1154:     $filename=~s/\/+/\//g;
1.607     raeburn  1155:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1156:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1157:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1158: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1159: 	return &repcopy_userfile($filename);
                   1160:     }
1.532     albertel 1161:     $filename=~s/[\n\r]//g;
1.8       www      1162:     my $transname="$filename.in.transfer";
1.607     raeburn  1163:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1164:     my $remoteurl=subscribe($filename);
1.64      www      1165:     if ($remoteurl =~ /^con_lost by/) {
                   1166: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1167:            return 'unavailable';
1.8       www      1168:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1169: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1170: 	   return 'not_found';
1.64      www      1171:     } elsif ($remoteurl =~ /^rejected by/) {
                   1172: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1173:            return 'forbidden';
1.20      www      1174:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1175:            return 'ok';
1.8       www      1176:     } else {
1.290     www      1177:         my $author=$filename;
                   1178:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1179:         my ($udom,$uname)=split(/\//,$author);
                   1180:         my $home=homeserver($uname,$udom);
                   1181:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1182:            my @parts=split(/\//,$filename);
                   1183:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1184:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1185:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1186: 	       return 'bad_request';
1.8       www      1187:            }
                   1188:            my $count;
                   1189:            for ($count=5;$count<$#parts;$count++) {
                   1190:                $path.="/$parts[$count]";
                   1191:                if ((-e $path)!=1) {
                   1192: 		   mkdir($path,0777);
                   1193:                }
                   1194:            }
                   1195:            my $ua=new LWP::UserAgent;
                   1196:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1197:            my $response=$ua->request($request,$transname);
                   1198:            if ($response->is_error()) {
                   1199: 	       unlink($transname);
                   1200:                my $message=$response->status_line;
1.672     albertel 1201:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1202:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1203:                return 'unavailable';
1.8       www      1204:            } else {
1.16      www      1205: 	       if ($remoteurl!~/\.meta$/) {
                   1206:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1207:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1208:                   if ($mresponse->is_error()) {
                   1209: 		      unlink($filename.'.meta');
                   1210:                       &logthis(
1.672     albertel 1211:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1212:                   }
                   1213: 	       }
1.8       www      1214:                rename($transname,$filename);
1.607     raeburn  1215:                return 'ok';
1.8       www      1216:            }
1.290     www      1217:        }
1.8       www      1218:     }
1.330     www      1219: }
                   1220: 
                   1221: # ------------------------------------------------ Get server side include body
                   1222: sub ssi_body {
1.381     albertel 1223:     my ($filelink,%form)=@_;
1.606     matthew  1224:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1225:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1226:     }
1.330     www      1227:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1228:                                      &ssi($filelink,%form));
1.778     albertel 1229:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1230:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1231:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1232:     return $output;
1.8       www      1233: }
                   1234: 
1.15      www      1235: # --------------------------------------------------------- Server Side Include
                   1236: 
1.782     albertel 1237: sub absolute_url {
                   1238:     my ($host_name) = @_;
                   1239:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1240:     if ($host_name eq '') {
                   1241: 	$host_name = $ENV{'SERVER_NAME'};
                   1242:     }
                   1243:     return $protocol.$host_name;
                   1244: }
                   1245: 
1.15      www      1246: sub ssi {
                   1247: 
1.23      www      1248:     my ($fn,%form)=@_;
1.15      www      1249: 
                   1250:     my $ua=new LWP::UserAgent;
1.23      www      1251:     
                   1252:     my $request;
1.711     albertel 1253: 
                   1254:     $form{'no_update_last_known'}=1;
                   1255: 
1.23      www      1256:     if (%form) {
1.782     albertel 1257:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1258:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1259:     } else {
1.782     albertel 1260:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1261:     }
                   1262: 
1.15      www      1263:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1264:     my $response=$ua->request($request);
                   1265: 
1.324     www      1266:     return $response->content;
                   1267: }
                   1268: 
                   1269: sub externalssi {
                   1270:     my ($url)=@_;
                   1271:     my $ua=new LWP::UserAgent;
                   1272:     my $request=new HTTP::Request('GET',$url);
                   1273:     my $response=$ua->request($request);
1.15      www      1274:     return $response->content;
                   1275: }
1.254     www      1276: 
1.492     albertel 1277: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1278: 
                   1279: sub allowuploaded {
                   1280:     my ($srcurl,$url)=@_;
                   1281:     $url=&clutter(&declutter($url));
                   1282:     my $dir=$url;
                   1283:     $dir=~s/\/[^\/]+$//;
                   1284:     my %httpref=();
                   1285:     my $httpurl=&hreflocation('',$url);
                   1286:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1287:     &Apache::lonnet::appenv(%httpref);
1.254     www      1288: }
1.477     raeburn  1289: 
1.478     albertel 1290: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1291: # input: action, courseID, current domain, intended
1.637     raeburn  1292: #        path to file, source of file, instruction to parse file for objects,
                   1293: #        ref to hash for embedded objects,
                   1294: #        ref to hash for codebase of java objects.
                   1295: #
1.485     raeburn  1296: # output: url to file (if action was uploaddoc), 
                   1297: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1298: #
1.478     albertel 1299: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1300: # course.
1.477     raeburn  1301: #
1.478     albertel 1302: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1303: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1304: #          course's home server.
1.477     raeburn  1305: #
1.478     albertel 1306: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1307: #          be copied from $source (current location) to 
                   1308: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1309: #         and will then be copied to
                   1310: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1311: #         course's home server.
1.485     raeburn  1312: #
1.481     raeburn  1313: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1314: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1315: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1316: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1317: #         in course's home server.
1.637     raeburn  1318: #
1.477     raeburn  1319: 
                   1320: sub process_coursefile {
1.638     albertel 1321:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1322:     my $fetchresult;
1.638     albertel 1323:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1324:     if ($action eq 'propagate') {
1.638     albertel 1325:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1326: 			     $home);
1.481     raeburn  1327:     } else {
1.477     raeburn  1328:         my $fpath = '';
                   1329:         my $fname = $file;
1.478     albertel 1330:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1331:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1332:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1333:         if ($action eq 'copy') {
                   1334:             if ($source eq '') {
                   1335:                 $fetchresult = 'no source file';
                   1336:                 return $fetchresult;
                   1337:             } else {
                   1338:                 my $destination = $filepath.'/'.$fname;
                   1339:                 rename($source,$destination);
                   1340:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1341:                                  $home);
1.481     raeburn  1342:             }
                   1343:         } elsif ($action eq 'uploaddoc') {
                   1344:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1345:             print $fh $env{'form.'.$source};
1.481     raeburn  1346:             close($fh);
1.637     raeburn  1347:             if ($parser eq 'parse') {
                   1348:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1349:                 unless ($parse_result eq 'ok') {
                   1350:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1351:                 }
                   1352:             }
1.477     raeburn  1353:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1354:                                  $home);
1.481     raeburn  1355:             if ($fetchresult eq 'ok') {
                   1356:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1357:             } else {
                   1358:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1359:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1360:                 return '/adm/notfound.html';
                   1361:             }
1.477     raeburn  1362:         }
                   1363:     }
1.485     raeburn  1364:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1365:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1366:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1367:     }
                   1368:     return $fetchresult;
                   1369: }
                   1370: 
1.637     raeburn  1371: sub build_filepath {
                   1372:     my ($fpath) = @_;
                   1373:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1374:     unless ($fpath eq '') {
                   1375:         my @parts=split('/',$fpath);
                   1376:         foreach my $part (@parts) {
                   1377:             $filepath.= '/'.$part;
                   1378:             if ((-e $filepath)!=1) {
                   1379:                 mkdir($filepath,0777);
                   1380:             }
                   1381:         }
                   1382:     }
                   1383:     return $filepath;
                   1384: }
                   1385: 
                   1386: sub store_edited_file {
1.638     albertel 1387:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1388:     my $file = $primary_url;
                   1389:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1390:     my $fpath = '';
                   1391:     my $fname = $file;
                   1392:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1393:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1394:     my $filepath = &build_filepath($fpath);
                   1395:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1396:     print $fh $content;
                   1397:     close($fh);
1.638     albertel 1398:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1399:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1400: 			  $home);
1.637     raeburn  1401:     if ($$fetchresult eq 'ok') {
                   1402:         return '/uploaded/'.$fpath.'/'.$fname;
                   1403:     } else {
1.638     albertel 1404:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1405: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1406:         return '/adm/notfound.html';
                   1407:     }
                   1408: }
                   1409: 
1.531     albertel 1410: sub clean_filename {
                   1411:     my ($fname)=@_;
1.315     www      1412: # Replace Windows backslashes by forward slashes
1.257     www      1413:     $fname=~s/\\/\//g;
1.315     www      1414: # Get rid of everything but the actual filename
1.257     www      1415:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1416: # Replace spaces by underscores
                   1417:     $fname=~s/\s+/\_/g;
                   1418: # Replace all other weird characters by nothing
1.317     www      1419:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1420: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1421: # numbers
                   1422:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1423:     return $fname;
                   1424: }
                   1425: 
1.608     albertel 1426: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1427: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1428: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1429: #        $coursedoc - if true up to the current course
                   1430: #                     if false
                   1431: #        $subdir - directory in userfile to store the file into
                   1432: #        $parser, $allfiles, $codebase - unknown
                   1433: #
                   1434: # output: url of file in userspace, or error: <message> 
                   1435: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1436: 
                   1437: 
1.531     albertel 1438: sub userfileupload {
1.719     banghart 1439:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1440:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1441:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1442:     $fname=&clean_filename($fname);
1.315     www      1443: # See if there is anything left
1.257     www      1444:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1445:     chop($env{'form.'.$formname});
1.523     raeburn  1446:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1447:         my $now = time;
                   1448:         my $filepath = 'tmp/helprequests/'.$now;
                   1449:         my @parts=split(/\//,$filepath);
                   1450:         my $fullpath = $perlvar{'lonDaemons'};
                   1451:         for (my $i=0;$i<@parts;$i++) {
                   1452:             $fullpath .= '/'.$parts[$i];
                   1453:             if ((-e $fullpath)!=1) {
                   1454:                 mkdir($fullpath,0777);
                   1455:             }
                   1456:         }
                   1457:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1458:         print $fh $env{'form.'.$formname};
1.523     raeburn  1459:         close($fh);
1.741     raeburn  1460:         return $fullpath.'/'.$fname;
                   1461:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1462:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1463:                        '_'.$env{'user.domain'}.'/pending';
                   1464:         my @parts=split(/\//,$filepath);
                   1465:         my $fullpath = $perlvar{'lonDaemons'};
                   1466:         for (my $i=0;$i<@parts;$i++) {
                   1467:             $fullpath .= '/'.$parts[$i];
                   1468:             if ((-e $fullpath)!=1) {
                   1469:                 mkdir($fullpath,0777);
                   1470:             }
                   1471:         }
                   1472:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1473:         print $fh $env{'form.'.$formname};
                   1474:         close($fh);
                   1475:         return $fullpath.'/'.$fname;
1.523     raeburn  1476:     }
1.719     banghart 1477:     
1.258     www      1478: # Create the directory if not present
1.493     albertel 1479:     $fname="$subdir/$fname";
1.259     www      1480:     if ($coursedoc) {
1.638     albertel 1481: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1482: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1483:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1484:             return &finishuserfileupload($docuname,$docudom,
                   1485: 					 $formname,$fname,$parser,$allfiles,
                   1486: 					 $codebase);
1.481     raeburn  1487:         } else {
1.620     albertel 1488:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1489:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1490: 				       $fname,$formname,$parser,
                   1491: 				       $allfiles,$codebase);
1.481     raeburn  1492:         }
1.719     banghart 1493:     } elsif (defined($destuname)) {
                   1494:         my $docuname=$destuname;
                   1495:         my $docudom=$destudom;
                   1496: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1497: 				     $fname,$parser,$allfiles,$codebase);
                   1498:         
1.259     www      1499:     } else {
1.638     albertel 1500:         my $docuname=$env{'user.name'};
                   1501:         my $docudom=$env{'user.domain'};
1.714     raeburn  1502:         if (exists($env{'form.group'})) {
                   1503:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1504:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1505:         }
1.638     albertel 1506: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1507: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1508:     }
1.271     www      1509: }
                   1510: 
                   1511: sub finishuserfileupload {
1.638     albertel 1512:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1513:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1514:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1515:     my ($fnamepath,$file);
                   1516:     $file=$fname;
                   1517:     if ($fname=~m|/|) {
                   1518:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1519: 	$path.=$fnamepath.'/';
                   1520:     }
1.259     www      1521:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1522:     my $count;
                   1523:     for ($count=4;$count<=$#parts;$count++) {
                   1524:         $filepath.="/$parts[$count]";
                   1525:         if ((-e $filepath)!=1) {
                   1526: 	    mkdir($filepath,0777);
                   1527:         }
                   1528:     }
                   1529: # Save the file
                   1530:     {
1.701     albertel 1531: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1532: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1533: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1534: 	    return '/adm/notfound.html';
                   1535: 	}
                   1536: 	if (!print FH ($env{'form.'.$formname})) {
                   1537: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1538: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1539: 	    return '/adm/notfound.html';
                   1540: 	}
1.570     albertel 1541: 	close(FH);
1.258     www      1542:     }
1.637     raeburn  1543:     if ($parser eq 'parse') {
1.638     albertel 1544:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1545: 						   $codebase);
1.637     raeburn  1546:         unless ($parse_result eq 'ok') {
1.638     albertel 1547:             &logthis('Failed to parse '.$filepath.$file.
                   1548: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1549:         }
                   1550:     }
1.259     www      1551: # Notify homeserver to grep it
                   1552: #
1.638     albertel 1553:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1554:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1555:     if ($fetchresult eq 'ok') {
1.259     www      1556: #
1.258     www      1557: # Return the URL to it
1.494     albertel 1558:         return '/uploaded/'.$path.$file;
1.263     www      1559:     } else {
1.494     albertel 1560:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1561: 		 ': '.$fetchresult);
1.263     www      1562:         return '/adm/notfound.html';
                   1563:     }    
1.493     albertel 1564: }
                   1565: 
1.637     raeburn  1566: sub extract_embedded_items {
1.648     raeburn  1567:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1568:     my @state = ();
                   1569:     my %javafiles = (
                   1570:                       codebase => '',
                   1571:                       code => '',
                   1572:                       archive => ''
                   1573:                     );
                   1574:     my %mediafiles = (
                   1575:                       src => '',
                   1576:                       movie => '',
                   1577:                      );
1.648     raeburn  1578:     my $p;
                   1579:     if ($content) {
                   1580:         $p = HTML::LCParser->new($content);
                   1581:     } else {
                   1582:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1583:     }
1.641     albertel 1584:     while (my $t=$p->get_token()) {
1.640     albertel 1585: 	if ($t->[0] eq 'S') {
                   1586: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1587: 	    push (@state, $tagname);
1.648     raeburn  1588:             if (lc($tagname) eq 'allow') {
                   1589:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1590:             }
1.640     albertel 1591: 	    if (lc($tagname) eq 'img') {
                   1592: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1593: 	    }
1.645     raeburn  1594:             if (lc($tagname) eq 'script') {
                   1595:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1596:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1597:                 } else {
                   1598:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1599:                 }
                   1600:             }
                   1601:             if (lc($tagname) eq 'link') {
                   1602:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1603:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1604:                 }
                   1605:             }
1.640     albertel 1606: 	    if (lc($tagname) eq 'object' ||
                   1607: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1608: 		foreach my $item (keys(%javafiles)) {
                   1609: 		    $javafiles{$item} = '';
                   1610: 		}
                   1611: 	    }
                   1612: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1613: 		my $name = lc($attr->{'name'});
                   1614: 		foreach my $item (keys(%javafiles)) {
                   1615: 		    if ($name eq $item) {
                   1616: 			$javafiles{$item} = $attr->{'value'};
                   1617: 			last;
                   1618: 		    }
                   1619: 		}
                   1620: 		foreach my $item (keys(%mediafiles)) {
                   1621: 		    if ($name eq $item) {
                   1622: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1623: 			last;
                   1624: 		    }
                   1625: 		}
                   1626: 	    }
                   1627: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1628: 		foreach my $item (keys(%javafiles)) {
                   1629: 		    if ($attr->{$item}) {
                   1630: 			$javafiles{$item} = $attr->{$item};
                   1631: 			last;
                   1632: 		    }
                   1633: 		}
                   1634: 		foreach my $item (keys(%mediafiles)) {
                   1635: 		    if ($attr->{$item}) {
                   1636: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1637: 			last;
                   1638: 		    }
                   1639: 		}
                   1640: 	    }
                   1641: 	} elsif ($t->[0] eq 'E') {
                   1642: 	    my ($tagname) = ($t->[1]);
                   1643: 	    if ($javafiles{'codebase'} ne '') {
                   1644: 		$javafiles{'codebase'} .= '/';
                   1645: 	    }  
                   1646: 	    if (lc($tagname) eq 'applet' ||
                   1647: 		lc($tagname) eq 'object' ||
                   1648: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1649: 		) {
                   1650: 		foreach my $item (keys(%javafiles)) {
                   1651: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1652: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1653: 			&add_filetype($allfiles,$file,$item);
                   1654: 		    }
                   1655: 		}
                   1656: 	    } 
                   1657: 	    pop @state;
                   1658: 	}
                   1659:     }
1.637     raeburn  1660:     return 'ok';
                   1661: }
                   1662: 
1.639     albertel 1663: sub add_filetype {
                   1664:     my ($allfiles,$file,$type)=@_;
                   1665:     if (exists($allfiles->{$file})) {
                   1666: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1667: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1668: 	}
                   1669:     } else {
                   1670: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1671:     }
                   1672: }
                   1673: 
1.493     albertel 1674: sub removeuploadedurl {
                   1675:     my ($url)=@_;
                   1676:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1677:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1678: }
                   1679: 
                   1680: sub removeuserfile {
                   1681:     my ($docuname,$docudom,$fname)=@_;
                   1682:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1683:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1684:     if ($result eq 'ok') {
                   1685:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1686:             my $metafile = $fname.'.meta';
                   1687:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
                   1688:         }
                   1689:     }
                   1690:     return $result;
1.257     www      1691: }
1.15      www      1692: 
1.530     albertel 1693: sub mkdiruserfile {
                   1694:     my ($docuname,$docudom,$dir)=@_;
                   1695:     my $home=&homeserver($docuname,$docudom);
                   1696:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1697: }
                   1698: 
1.531     albertel 1699: sub renameuserfile {
                   1700:     my ($docuname,$docudom,$old,$new)=@_;
                   1701:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1702:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1703:                         &escape("$old").':'.&escape("$new"),$home);
                   1704:     if ($result eq 'ok') {
                   1705:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1706:             my $oldmeta = $old.'.meta';
                   1707:             my $newmeta = $new.'.meta';
                   1708:             my $metaresult = 
                   1709:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
                   1710:         }
                   1711:     }
                   1712:     return $result;
1.531     albertel 1713: }
                   1714: 
1.14      www      1715: # ------------------------------------------------------------------------- Log
                   1716: 
                   1717: sub log {
                   1718:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1719:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1720: }
                   1721: 
                   1722: # ------------------------------------------------------------------ Course Log
1.352     www      1723: #
                   1724: # This routine flushes several buffers of non-mission-critical nature
                   1725: #
1.157     www      1726: 
                   1727: sub flushcourselogs {
1.352     www      1728:     &logthis('Flushing log buffers');
                   1729: #
                   1730: # course logs
                   1731: # This is a log of all transactions in a course, which can be used
                   1732: # for data mining purposes
                   1733: #
                   1734: # It also collects the courseid database, which lists last transaction
                   1735: # times and course titles for all courseids
                   1736: #
                   1737:     my %courseidbuffer=();
1.800     albertel 1738:     foreach my $crsid (keys %courselogs) {
1.352     www      1739:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1740: 		          &escape($courselogs{$crsid}),
                   1741: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1742: 	    delete $courselogs{$crsid};
                   1743:         } else {
                   1744:             &logthis('Failed to flush log buffer for '.$crsid);
                   1745:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1746:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1747:                         " exceeded maximum size, deleting.</font>");
                   1748:                delete $courselogs{$crsid};
                   1749:             }
1.352     www      1750:         }
                   1751:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1752:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1753: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1754:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1755:         } else {
                   1756:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1757: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1758:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1759:         }
1.191     harris41 1760:     }
1.352     www      1761: #
                   1762: # Write course id database (reverse lookup) to homeserver of courses 
                   1763: # Is used in pickcourse
                   1764: #
1.800     albertel 1765:     foreach my $crsid (keys(%courseidbuffer)) {
                   1766:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1767:     }
                   1768: #
                   1769: # File accesses
                   1770: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1771: #
1.449     matthew  1772:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1773:         if ($entry =~ /___count$/) {
                   1774:             my ($dom,$name);
1.807   ! albertel 1775:             ($dom,$name,undef)=
        !          1776: 		($entry=~m{___($match_domain)/($match_username)/(.*)___count$});
1.458     matthew  1777:             if (! defined($dom) || $dom eq '' || 
                   1778:                 ! defined($name) || $name eq '') {
1.620     albertel 1779:                 my $cid = $env{'request.course.id'};
                   1780:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1781:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1782:             }
1.450     matthew  1783:             my $value = $accesshash{$entry};
                   1784:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1785:             my %temphash=($url => $value);
1.449     matthew  1786:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1787:             if ($result eq 'ok') {
                   1788:                 delete $accesshash{$entry};
                   1789:             } elsif ($result eq 'unknown_cmd') {
                   1790:                 # Target server has old code running on it.
1.450     matthew  1791:                 my %temphash=($entry => $value);
1.449     matthew  1792:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1793:                     delete $accesshash{$entry};
                   1794:                 }
                   1795:             }
                   1796:         } else {
1.807   ! albertel 1797:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_username)/(.*)___(\w+)$});
1.450     matthew  1798:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1799:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1800:                 delete $accesshash{$entry};
                   1801:             }
1.185     www      1802:         }
1.191     harris41 1803:     }
1.352     www      1804: #
                   1805: # Roles
                   1806: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1807: #
1.800     albertel 1808:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1809:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1810: 	    split(/\:/,$entry);
                   1811:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1812:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1813:                 $rudom,$runame) eq 'ok') {
                   1814: 	    delete $userrolehash{$entry};
                   1815:         }
                   1816:     }
1.662     raeburn  1817: #
                   1818: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1819: #
                   1820:     my %domrolebuffer = ();
                   1821:     foreach my $entry (keys %domainrolehash) {
                   1822:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1823:         if ($domrolebuffer{$rudom}) {
                   1824:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1825:                       '='.&escape($domainrolehash{$entry});
                   1826:         } else {
                   1827:             $domrolebuffer{$rudom}.=&escape($entry).
                   1828:                       '='.&escape($domainrolehash{$entry});
                   1829:         }
                   1830:         delete $domainrolehash{$entry};
                   1831:     }
                   1832:     foreach my $dom (keys(%domrolebuffer)) {
                   1833:         foreach my $tryserver (keys %libserv) {
                   1834:             if ($hostdom{$tryserver} eq $dom) {
                   1835:                 unless (&reply('domroleput:'.$dom.':'.
                   1836:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1837:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1838:                 }
                   1839:             }
                   1840:         }
                   1841:     }
1.186     www      1842:     $dumpcount++;
1.157     www      1843: }
                   1844: 
                   1845: sub courselog {
                   1846:     my $what=shift;
1.158     www      1847:     $what=time.':'.$what;
1.620     albertel 1848:     unless ($env{'request.course.id'}) { return ''; }
                   1849:     $coursedombuf{$env{'request.course.id'}}=
                   1850:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1851:     $coursenumbuf{$env{'request.course.id'}}=
                   1852:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1853:     $coursehombuf{$env{'request.course.id'}}=
                   1854:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1855:     $coursedescrbuf{$env{'request.course.id'}}=
                   1856:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1857:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1858:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1859:     $courseownerbuf{$env{'request.course.id'}}=
                   1860:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1861:     $coursetypebuf{$env{'request.course.id'}}=
                   1862:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1863:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1864: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1865:     } else {
1.620     albertel 1866: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1867:     }
1.620     albertel 1868:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1869: 	&flushcourselogs();
                   1870:     }
1.158     www      1871: }
                   1872: 
                   1873: sub courseacclog {
                   1874:     my $fnsymb=shift;
1.620     albertel 1875:     unless ($env{'request.course.id'}) { return ''; }
                   1876:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1877:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1878:         $what.=':POST';
1.583     matthew  1879:         # FIXME: Probably ought to escape things....
1.800     albertel 1880: 	foreach my $key (keys(%env)) {
                   1881:             if ($key=~/^form\.(.*)/) {
                   1882: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1883:             }
1.191     harris41 1884:         }
1.583     matthew  1885:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1886:         # FIXME: We should not be depending on a form parameter that someone
                   1887:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1888:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1889:             $what.= ':POST';
                   1890:             # FIXME: Probably ought to escape things....
                   1891:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1892:                                  'crsdiscuss') {
1.620     albertel 1893:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1894:             }
                   1895:         }
1.158     www      1896:     }
                   1897:     &courselog($what);
1.149     www      1898: }
                   1899: 
1.185     www      1900: sub countacc {
                   1901:     my $url=&declutter(shift);
1.458     matthew  1902:     return if (! defined($url) || $url eq '');
1.620     albertel 1903:     unless ($env{'request.course.id'}) { return ''; }
                   1904:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1905:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1906:     $accesshash{$key}++;
1.185     www      1907: }
1.349     www      1908: 
1.361     www      1909: sub linklog {
                   1910:     my ($from,$to)=@_;
                   1911:     $from=&declutter($from);
                   1912:     $to=&declutter($to);
                   1913:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1914:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1915: }
                   1916:   
1.349     www      1917: sub userrolelog {
                   1918:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1919:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1920:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1921:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1922:         ($trole=~/^ta/)) {
1.350     www      1923:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1924:        $userrolehash
                   1925:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1926:                     =$tend.':'.$tstart;
1.662     raeburn  1927:     }
                   1928:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1929:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1930:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1931:         ($trole=~/^sc/)) {
                   1932:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1933:        $domainrolehash
                   1934:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1935:                     = $tend.':'.$tstart;
                   1936:     }
1.351     www      1937: }
                   1938: 
                   1939: sub get_course_adv_roles {
                   1940:     my $cid=shift;
1.620     albertel 1941:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1942:     my %coursehash=&coursedescription($cid);
1.470     www      1943:     my %nothide=();
1.800     albertel 1944:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1945: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      1946:     }
1.351     www      1947:     my %returnhash=();
                   1948:     my %dumphash=
                   1949:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1950:     my $now=time;
1.800     albertel 1951:     foreach my $entry (keys %dumphash) {
                   1952: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      1953:         if (($tstart) && ($tstart<0)) { next; }
                   1954:         if (($tend) && ($tend<$now)) { next; }
                   1955:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1956:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 1957: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1958: 	if ((&privileged($username,$domain)) && 
                   1959: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1960: 	if ($role eq 'cr') { next; }
1.351     www      1961:         my $key=&plaintext($role);
                   1962:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1963:         if ($returnhash{$key}) {
                   1964: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1965:         } else {
                   1966:             $returnhash{$key}=$username.':'.$domain;
                   1967:         }
1.400     www      1968:      }
                   1969:     return %returnhash;
                   1970: }
                   1971: 
                   1972: sub get_my_roles {
                   1973:     my ($uname,$udom)=@_;
1.620     albertel 1974:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1975:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1976:     my %dumphash=
                   1977:             &dump('nohist_userroles',$udom,$uname);
                   1978:     my %returnhash=();
                   1979:     my $now=time;
1.800     albertel 1980:     foreach my $entry (keys(%dumphash)) {
                   1981: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      1982:         if (($tstart) && ($tstart<0)) { next; }
                   1983:         if (($tend) && ($tend<$now)) { next; }
                   1984:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1985:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      1986: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1987:      }
                   1988:     return %returnhash;
1.399     www      1989: }
                   1990: 
                   1991: # ----------------------------------------------------- Frontpage Announcements
                   1992: #
                   1993: #
                   1994: 
                   1995: sub postannounce {
                   1996:     my ($server,$text)=@_;
                   1997:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1998:     unless ($text=~/\w/) { $text=''; }
                   1999:     return &reply('setannounce:'.&escape($text),$server);
                   2000: }
                   2001: 
                   2002: sub getannounce {
1.448     albertel 2003: 
                   2004:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2005: 	my $announcement='';
1.800     albertel 2006: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2007: 	close($fh);
1.399     www      2008: 	if ($announcement=~/\w/) { 
                   2009: 	    return 
                   2010:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2011:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2012: 	} else {
                   2013: 	    return '';
                   2014: 	}
                   2015:     } else {
                   2016: 	return '';
                   2017:     }
1.351     www      2018: }
1.353     www      2019: 
                   2020: # ---------------------------------------------------------- Course ID routines
                   2021: # Deal with domain's nohist_courseid.db files
                   2022: #
                   2023: 
                   2024: sub courseidput {
                   2025:     my ($domain,$what,$coursehome)=@_;
                   2026:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2027: }
                   2028: 
                   2029: sub courseiddump {
1.791     raeburn  2030:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2031:     my %returnhash=();
1.355     www      2032:     unless ($domfilter) { $domfilter=''; }
1.353     www      2033:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2034:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2035: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2036: 	        foreach my $line (
1.506     raeburn  2037:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2038: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2039:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2040:                                $tryserver))) {
1.800     albertel 2041: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2042:                     if (($key) && ($value)) {
1.516     raeburn  2043: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2044:                     }
1.353     www      2045:                 }
                   2046:             }
                   2047:         }
                   2048:     }
                   2049:     return %returnhash;
                   2050: }
                   2051: 
1.658     raeburn  2052: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2053: 
                   2054: sub dcmailput {
1.685     raeburn  2055:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2056:     my $status = &Apache::lonnet::critical(
1.740     www      2057:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2058:        &escape($message),$server);
1.662     raeburn  2059:     return $status;
                   2060: }
                   2061: 
1.658     raeburn  2062: sub dcmaildump {
                   2063:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2064:     my %returnhash=();
                   2065:     if (exists($domain_primary{$dom})) {
                   2066:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2067:                                                          &escape($enddate).':';
                   2068: 	my @esc_senders=map { &escape($_)} @$senders;
                   2069: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2070: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2071:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2072:             if (($key) && ($value)) {
                   2073:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2074:             }
                   2075:         }
                   2076:     }
                   2077:     return %returnhash;
                   2078: }
1.662     raeburn  2079: # ---------------------------------------------------------- Domain roles
                   2080: 
                   2081: sub get_domain_roles {
                   2082:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2083:     if (undef($startdate) || $startdate eq '') {
                   2084:         $startdate = '.';
                   2085:     }
                   2086:     if (undef($enddate) || $enddate eq '') {
                   2087:         $enddate = '.';
                   2088:     }
                   2089:     my $rolelist = join(':',@{$roles});
                   2090:     my %personnel = ();
                   2091:     foreach my $tryserver (keys(%libserv)) {
                   2092:         if ($hostdom{$tryserver} eq $dom) {
                   2093:             %{$personnel{$tryserver}}=();
1.800     albertel 2094:             foreach my $line (
1.662     raeburn  2095:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2096:                    &escape($startdate).':'.&escape($enddate).':'.
                   2097:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2098:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2099:                 if (($key) && ($value)) {
                   2100:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2101:                 }
                   2102:             }
                   2103:         }
                   2104:     }
                   2105:     return %personnel;
                   2106: }
1.658     raeburn  2107: 
1.149     www      2108: # ----------------------------------------------------------- Check out an item
                   2109: 
1.504     albertel 2110: sub get_first_access {
                   2111:     my ($type,$argsymb)=@_;
1.790     albertel 2112:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2113:     if ($argsymb) { $symb=$argsymb; }
                   2114:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2115:     if ($type eq 'map') {
                   2116: 	$res=&symbread($map);
                   2117:     } else {
                   2118: 	$res=$symb;
                   2119:     }
                   2120:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2121:     return $times{"$courseid\0$res"};
1.504     albertel 2122: }
                   2123: 
                   2124: sub set_first_access {
                   2125:     my ($type)=@_;
1.790     albertel 2126:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2127:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2128:     if ($type eq 'map') {
                   2129: 	$res=&symbread($map);
                   2130:     } else {
                   2131: 	$res=$symb;
                   2132:     }
                   2133:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2134:     if (!$firstaccess) {
1.588     albertel 2135: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2136:     }
                   2137:     return 'already_set';
1.504     albertel 2138: }
                   2139: 
1.149     www      2140: sub checkout {
                   2141:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2142:     my $now=time;
                   2143:     my $lonhost=$perlvar{'lonHostID'};
                   2144:     my $infostr=&escape(
1.234     www      2145:                  'CHECKOUTTOKEN&'.
1.149     www      2146:                  $tuname.'&'.
                   2147:                  $tudom.'&'.
                   2148:                  $tcrsid.'&'.
                   2149:                  $symb.'&'.
                   2150: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2151:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2152:     if ($token=~/^error\:/) { 
1.672     albertel 2153:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2154:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2155:                  "</font>");
                   2156:         return ''; 
                   2157:     }
                   2158: 
1.149     www      2159:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2160:     $token=~tr/a-z/A-Z/;
                   2161: 
1.153     www      2162:     my %infohash=('resource.0.outtoken' => $token,
                   2163:                   'resource.0.checkouttime' => $now,
                   2164:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2165: 
                   2166:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2167:        return '';
1.151     www      2168:     } else {
1.672     albertel 2169:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2170:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2171:                  "</font>");
1.149     www      2172:     }    
                   2173: 
                   2174:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2175:                          &escape('Checkout '.$infostr.' - '.
                   2176:                                                  $token)) ne 'ok') {
                   2177: 	return '';
1.151     www      2178:     } else {
1.672     albertel 2179:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2180:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2181:                  "</font>");
1.149     www      2182:     }
1.151     www      2183:     return $token;
1.149     www      2184: }
                   2185: 
                   2186: # ------------------------------------------------------------ Check in an item
                   2187: 
                   2188: sub checkin {
                   2189:     my $token=shift;
1.150     www      2190:     my $now=time;
                   2191:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2192:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2193:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2194:     $dtoken=~s/\W/\_/g;
1.234     www      2195:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2196:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2197: 
1.154     www      2198:     unless (($tuname) && ($tudom)) {
                   2199:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2200:         return '';
                   2201:     }
                   2202:     
                   2203:     unless (&allowed('mgr',$tcrsid)) {
                   2204:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2205:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2206:         return '';
                   2207:     }
                   2208: 
1.153     www      2209:     my %infohash=('resource.0.intoken' => $token,
                   2210:                   'resource.0.checkintime' => $now,
                   2211:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2212: 
                   2213:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2214:        return '';
                   2215:     }    
                   2216: 
                   2217:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2218:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2219: 	return '';
                   2220:     }
                   2221: 
                   2222:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2223: }
                   2224: 
                   2225: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2226: 
                   2227: sub expirespread {
                   2228:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2229:     my $cid=$env{'request.course.id'}; 
1.110     www      2230:     if ($cid) {
                   2231:        my $now=time;
                   2232:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2233:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2234:                             $env{'course.'.$cid.'.num'}.
1.110     www      2235: 	        	    ':nohist_expirationdates:'.
                   2236:                             &escape($key).'='.$now,
1.620     albertel 2237:                             $env{'course.'.$cid.'.home'})
1.110     www      2238:     }
                   2239:     return 'ok';
1.14      www      2240: }
                   2241: 
1.109     www      2242: # ----------------------------------------------------- Devalidate Spreadsheets
                   2243: 
                   2244: sub devalidate {
1.325     www      2245:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2246:     my $cid=$env{'request.course.id'}; 
1.109     www      2247:     if ($cid) {
1.391     matthew  2248:         # delete the stored spreadsheets for
                   2249:         # - the student level sheet of this user in course's homespace
                   2250:         # - the assessment level sheet for this resource 
                   2251:         #   for this user in user's homespace
1.553     albertel 2252: 	# - current conditional state info
1.325     www      2253: 	my $key=$uname.':'.$udom.':';
1.109     www      2254:         my $status=
1.299     matthew  2255: 	    &del('nohist_calculatedsheets',
1.391     matthew  2256: 		 [$key.'studentcalc:'],
1.620     albertel 2257: 		 $env{'course.'.$cid.'.domain'},
                   2258: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2259: 		.' '.
                   2260: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2261: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2262:         unless ($status eq 'ok ok') {
                   2263:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2264:                     $uname.' at '.$udom.' for '.
1.109     www      2265: 		    $symb.': '.$status);
1.133     albertel 2266:         }
1.553     albertel 2267: 	&delenv('user.state.'.$cid);
1.109     www      2268:     }
                   2269: }
                   2270: 
1.265     albertel 2271: sub get_scalar {
                   2272:     my ($string,$end) = @_;
                   2273:     my $value;
                   2274:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2275: 	$value = $1;
                   2276:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2277: 	$value = $1;
                   2278:     }
                   2279:     return &unescape($value);
                   2280: }
                   2281: 
                   2282: sub array2str {
                   2283:   my (@array) = @_;
                   2284:   my $result=&arrayref2str(\@array);
                   2285:   $result=~s/^__ARRAY_REF__//;
                   2286:   $result=~s/__END_ARRAY_REF__$//;
                   2287:   return $result;
                   2288: }
                   2289: 
1.204     albertel 2290: sub arrayref2str {
                   2291:   my ($arrayref) = @_;
1.265     albertel 2292:   my $result='__ARRAY_REF__';
1.204     albertel 2293:   foreach my $elem (@$arrayref) {
1.265     albertel 2294:     if(ref($elem) eq 'ARRAY') {
                   2295:       $result.=&arrayref2str($elem).'&';
                   2296:     } elsif(ref($elem) eq 'HASH') {
                   2297:       $result.=&hashref2str($elem).'&';
                   2298:     } elsif(ref($elem)) {
                   2299:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2300:     } else {
                   2301:       $result.=&escape($elem).'&';
                   2302:     }
                   2303:   }
                   2304:   $result=~s/\&$//;
1.265     albertel 2305:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2306:   return $result;
                   2307: }
                   2308: 
1.168     albertel 2309: sub hash2str {
1.204     albertel 2310:   my (%hash) = @_;
                   2311:   my $result=&hashref2str(\%hash);
1.265     albertel 2312:   $result=~s/^__HASH_REF__//;
                   2313:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2314:   return $result;
                   2315: }
                   2316: 
                   2317: sub hashref2str {
                   2318:   my ($hashref)=@_;
1.265     albertel 2319:   my $result='__HASH_REF__';
1.800     albertel 2320:   foreach my $key (sort(keys(%$hashref))) {
                   2321:     if (ref($key) eq 'ARRAY') {
                   2322:       $result.=&arrayref2str($key).'=';
                   2323:     } elsif (ref($key) eq 'HASH') {
                   2324:       $result.=&hashref2str($key).'=';
                   2325:     } elsif (ref($key)) {
1.265     albertel 2326:       $result.='=';
1.800     albertel 2327:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2328:     } else {
1.800     albertel 2329: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2330:     }
                   2331: 
1.800     albertel 2332:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2333:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2334:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2335:       $result.=&hashref2str($hashref->{$key}).'&';
                   2336:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2337:        $result.='&';
1.800     albertel 2338:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2339:     } else {
1.800     albertel 2340:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2341:     }
                   2342:   }
1.168     albertel 2343:   $result=~s/\&$//;
1.265     albertel 2344:   $result .= '__END_HASH_REF__';
1.168     albertel 2345:   return $result;
                   2346: }
                   2347: 
                   2348: sub str2hash {
1.265     albertel 2349:     my ($string)=@_;
                   2350:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2351:     return %$hash;
                   2352: }
                   2353: 
                   2354: sub str2hashref {
1.168     albertel 2355:   my ($string) = @_;
1.265     albertel 2356: 
                   2357:   my %hash;
                   2358: 
                   2359:   if($string !~ /^__HASH_REF__/) {
                   2360:       if (! ($string eq '' || !defined($string))) {
                   2361: 	  $hash{'error'}='Not hash reference';
                   2362:       }
                   2363:       return (\%hash, $string);
                   2364:   }
                   2365: 
                   2366:   $string =~ s/^__HASH_REF__//;
                   2367: 
                   2368:   while($string !~ /^__END_HASH_REF__/) {
                   2369:       #key
                   2370:       my $key='';
                   2371:       if($string =~ /^__HASH_REF__/) {
                   2372:           ($key, $string)=&str2hashref($string);
                   2373:           if(defined($key->{'error'})) {
                   2374:               $hash{'error'}='Bad data';
                   2375:               return (\%hash, $string);
                   2376:           }
                   2377:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2378:           ($key, $string)=&str2arrayref($string);
                   2379:           if($key->[0] eq 'Array reference error') {
                   2380:               $hash{'error'}='Bad data';
                   2381:               return (\%hash, $string);
                   2382:           }
                   2383:       } else {
                   2384:           $string =~ s/^(.*?)=//;
1.267     albertel 2385: 	  $key=&unescape($1);
1.265     albertel 2386:       }
                   2387:       $string =~ s/^=//;
                   2388: 
                   2389:       #value
                   2390:       my $value='';
                   2391:       if($string =~ /^__HASH_REF__/) {
                   2392:           ($value, $string)=&str2hashref($string);
                   2393:           if(defined($value->{'error'})) {
                   2394:               $hash{'error'}='Bad data';
                   2395:               return (\%hash, $string);
                   2396:           }
                   2397:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2398:           ($value, $string)=&str2arrayref($string);
                   2399:           if($value->[0] eq 'Array reference error') {
                   2400:               $hash{'error'}='Bad data';
                   2401:               return (\%hash, $string);
                   2402:           }
                   2403:       } else {
                   2404: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2405:       }
                   2406:       $string =~ s/^&//;
                   2407: 
                   2408:       $hash{$key}=$value;
1.204     albertel 2409:   }
1.265     albertel 2410: 
                   2411:   $string =~ s/^__END_HASH_REF__//;
                   2412: 
                   2413:   return (\%hash, $string);
1.204     albertel 2414: }
                   2415: 
                   2416: sub str2array {
1.265     albertel 2417:     my ($string)=@_;
                   2418:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2419:     return @$array;
                   2420: }
                   2421: 
                   2422: sub str2arrayref {
1.204     albertel 2423:   my ($string) = @_;
1.265     albertel 2424:   my @array;
                   2425: 
                   2426:   if($string !~ /^__ARRAY_REF__/) {
                   2427:       if (! ($string eq '' || !defined($string))) {
                   2428: 	  $array[0]='Array reference error';
                   2429:       }
                   2430:       return (\@array, $string);
                   2431:   }
                   2432: 
                   2433:   $string =~ s/^__ARRAY_REF__//;
                   2434: 
                   2435:   while($string !~ /^__END_ARRAY_REF__/) {
                   2436:       my $value='';
                   2437:       if($string =~ /^__HASH_REF__/) {
                   2438:           ($value, $string)=&str2hashref($string);
                   2439:           if(defined($value->{'error'})) {
                   2440:               $array[0] ='Array reference error';
                   2441:               return (\@array, $string);
                   2442:           }
                   2443:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2444:           ($value, $string)=&str2arrayref($string);
                   2445:           if($value->[0] eq 'Array reference error') {
                   2446:               $array[0] ='Array reference error';
                   2447:               return (\@array, $string);
                   2448:           }
                   2449:       } else {
                   2450: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2451:       }
                   2452:       $string =~ s/^&//;
                   2453: 
                   2454:       push(@array, $value);
1.191     harris41 2455:   }
1.265     albertel 2456: 
                   2457:   $string =~ s/^__END_ARRAY_REF__//;
                   2458: 
                   2459:   return (\@array, $string);
1.168     albertel 2460: }
                   2461: 
1.167     albertel 2462: # -------------------------------------------------------------------Temp Store
                   2463: 
1.168     albertel 2464: sub tmpreset {
                   2465:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2466:   if (!$symb) {
                   2467:     $symb=&symbread();
1.620     albertel 2468:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2469:   }
                   2470:   $symb=escape($symb);
                   2471: 
1.620     albertel 2472:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2473:   $namespace=~s/\//\_/g;
                   2474:   $namespace=~s/\W//g;
                   2475: 
1.620     albertel 2476:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2477:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2478:   if ($domain eq 'public' && $stuname eq 'public') {
                   2479:       $stuname=$ENV{'REMOTE_ADDR'};
                   2480:   }
1.168     albertel 2481:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2482:   my %hash;
                   2483:   if (tie(%hash,'GDBM_File',
                   2484: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2485: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2486:     foreach my $key (keys %hash) {
1.180     albertel 2487:       if ($key=~ /:$symb/) {
1.168     albertel 2488: 	delete($hash{$key});
                   2489:       }
                   2490:     }
                   2491:   }
                   2492: }
                   2493: 
1.167     albertel 2494: sub tmpstore {
1.168     albertel 2495:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2496: 
                   2497:   if (!$symb) {
                   2498:     $symb=&symbread();
1.620     albertel 2499:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2500:   }
                   2501:   $symb=escape($symb);
                   2502: 
                   2503:   if (!$namespace) {
                   2504:     # I don't think we would ever want to store this for a course.
                   2505:     # it seems this will only be used if we don't have a course.
1.620     albertel 2506:     #$namespace=$env{'request.course.id'};
1.168     albertel 2507:     #if (!$namespace) {
1.620     albertel 2508:       $namespace=$env{'request.state'};
1.168     albertel 2509:     #}
                   2510:   }
                   2511:   $namespace=~s/\//\_/g;
                   2512:   $namespace=~s/\W//g;
1.620     albertel 2513:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2514:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2515:   if ($domain eq 'public' && $stuname eq 'public') {
                   2516:       $stuname=$ENV{'REMOTE_ADDR'};
                   2517:   }
1.168     albertel 2518:   my $now=time;
                   2519:   my %hash;
                   2520:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2521:   if (tie(%hash,'GDBM_File',
                   2522: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2523: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2524:     $hash{"version:$symb"}++;
                   2525:     my $version=$hash{"version:$symb"};
                   2526:     my $allkeys=''; 
                   2527:     foreach my $key (keys(%$storehash)) {
                   2528:       $allkeys.=$key.':';
1.591     albertel 2529:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2530:     }
                   2531:     $hash{"$version:$symb:timestamp"}=$now;
                   2532:     $allkeys.='timestamp';
                   2533:     $hash{"$version:keys:$symb"}=$allkeys;
                   2534:     if (untie(%hash)) {
                   2535:       return 'ok';
                   2536:     } else {
                   2537:       return "error:$!";
                   2538:     }
                   2539:   } else {
                   2540:     return "error:$!";
                   2541:   }
                   2542: }
1.167     albertel 2543: 
1.168     albertel 2544: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2545: 
1.168     albertel 2546: sub tmprestore {
                   2547:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2548: 
1.168     albertel 2549:   if (!$symb) {
                   2550:     $symb=&symbread();
1.620     albertel 2551:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2552:   }
                   2553:   $symb=escape($symb);
                   2554: 
1.620     albertel 2555:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2556: 
1.620     albertel 2557:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2558:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2559:   if ($domain eq 'public' && $stuname eq 'public') {
                   2560:       $stuname=$ENV{'REMOTE_ADDR'};
                   2561:   }
1.168     albertel 2562:   my %returnhash;
                   2563:   $namespace=~s/\//\_/g;
                   2564:   $namespace=~s/\W//g;
                   2565:   my %hash;
                   2566:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2567:   if (tie(%hash,'GDBM_File',
                   2568: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2569: 	  &GDBM_READER(),0640)) {
1.168     albertel 2570:     my $version=$hash{"version:$symb"};
                   2571:     $returnhash{'version'}=$version;
                   2572:     my $scope;
                   2573:     for ($scope=1;$scope<=$version;$scope++) {
                   2574:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2575:       my @keys=split(/:/,$vkeys);
                   2576:       my $key;
                   2577:       $returnhash{"$scope:keys"}=$vkeys;
                   2578:       foreach $key (@keys) {
1.591     albertel 2579: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2580: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2581:       }
                   2582:     }
1.168     albertel 2583:     if (!(untie(%hash))) {
                   2584:       return "error:$!";
                   2585:     }
                   2586:   } else {
                   2587:     return "error:$!";
                   2588:   }
                   2589:   return %returnhash;
1.167     albertel 2590: }
                   2591: 
1.9       www      2592: # ----------------------------------------------------------------------- Store
                   2593: 
                   2594: sub store {
1.124     www      2595:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2596:     my $home='';
                   2597: 
1.168     albertel 2598:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2599: 
1.213     www      2600:     $symb=&symbclean($symb);
1.122     albertel 2601:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2602: 
1.620     albertel 2603:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2604:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2605: 
                   2606:     &devalidate($symb,$stuname,$domain);
1.109     www      2607: 
                   2608:     $symb=escape($symb);
1.187     www      2609:     if (!$namespace) { 
1.620     albertel 2610:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2611:           return ''; 
                   2612:        } 
                   2613:     }
1.620     albertel 2614:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2615: 
                   2616:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2617:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2618: 
1.12      www      2619:     my $namevalue='';
1.800     albertel 2620:     foreach my $key (keys(%$storehash)) {
                   2621:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2622:     }
1.12      www      2623:     $namevalue=~s/\&$//;
1.187     www      2624:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2625:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2626: }
                   2627: 
1.47      www      2628: # -------------------------------------------------------------- Critical Store
                   2629: 
                   2630: sub cstore {
1.124     www      2631:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2632:     my $home='';
                   2633: 
1.168     albertel 2634:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2635: 
1.213     www      2636:     $symb=&symbclean($symb);
1.122     albertel 2637:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2638: 
1.620     albertel 2639:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2640:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2641: 
                   2642:     &devalidate($symb,$stuname,$domain);
1.109     www      2643: 
                   2644:     $symb=escape($symb);
1.187     www      2645:     if (!$namespace) { 
1.620     albertel 2646:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2647:           return ''; 
                   2648:        } 
                   2649:     }
1.620     albertel 2650:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2651: 
                   2652:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2653:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2654: 
1.47      www      2655:     my $namevalue='';
1.800     albertel 2656:     foreach my $key (keys(%$storehash)) {
                   2657:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2658:     }
1.47      www      2659:     $namevalue=~s/\&$//;
1.187     www      2660:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2661:     return critical
                   2662:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2663: }
                   2664: 
1.9       www      2665: # --------------------------------------------------------------------- Restore
                   2666: 
                   2667: sub restore {
1.124     www      2668:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2669:     my $home='';
                   2670: 
1.168     albertel 2671:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2672: 
1.122     albertel 2673:     if (!$symb) {
                   2674:       unless ($symb=escape(&symbread())) { return ''; }
                   2675:     } else {
1.213     www      2676:       $symb=&escape(&symbclean($symb));
1.122     albertel 2677:     }
1.188     www      2678:     if (!$namespace) { 
1.620     albertel 2679:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2680:           return ''; 
                   2681:        } 
                   2682:     }
1.620     albertel 2683:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2684:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2685:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2686:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2687: 
1.12      www      2688:     my %returnhash=();
1.800     albertel 2689:     foreach my $line (split(/\&/,$answer)) {
                   2690: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2691:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2692:     }
1.75      www      2693:     my $version;
                   2694:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2695:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2696:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2697:        }
1.75      www      2698:     }
1.13      www      2699:     return %returnhash;
1.34      www      2700: }
                   2701: 
                   2702: # ---------------------------------------------------------- Course Description
                   2703: 
                   2704: sub coursedescription {
1.731     albertel 2705:     my ($courseid,$args)=@_;
1.34      www      2706:     $courseid=~s/^\///;
1.49      www      2707:     $courseid=~s/\_/\//g;
1.34      www      2708:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2709:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2710:     my $normalid=$cdomain.'_'.$cnum;
                   2711:     # need to always cache even if we get errors otherwise we keep 
                   2712:     # trying and trying and trying to get the course description.
                   2713:     my %envhash=();
                   2714:     my %returnhash=();
1.731     albertel 2715:     
                   2716:     my $expiretime=600;
                   2717:     if ($env{'request.course.id'} eq $normalid) {
                   2718: 	$expiretime=120;
                   2719:     }
                   2720: 
                   2721:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2722:     if (!$args->{'freshen_cache'}
                   2723: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2724: 	foreach my $key (keys(%env)) {
                   2725: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2726: 	    my ($setting) = $1;
                   2727: 	    $returnhash{$setting} = $env{$key};
                   2728: 	}
                   2729: 	return %returnhash;
                   2730:     }
                   2731: 
                   2732:     # get the data agin
                   2733:     if (!$args->{'one_time'}) {
                   2734: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2735:     }
1.34      www      2736:     if ($chome ne 'no_host') {
1.302     albertel 2737:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2738:        if (!exists($returnhash{'con_lost'})) {
                   2739:            $returnhash{'home'}= $chome;
                   2740: 	   $returnhash{'domain'} = $cdomain;
                   2741: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2742:            if (!defined($returnhash{'type'})) {
                   2743:                $returnhash{'type'} = 'Course';
                   2744:            }
1.130     albertel 2745:            while (my ($name,$value) = each %returnhash) {
1.53      www      2746:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2747:            }
1.270     www      2748:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2749:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2750: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2751:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2752:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2753:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2754:        }
                   2755:     }
1.731     albertel 2756:     if (!$args->{'one_time'}) {
                   2757: 	&appenv(%envhash);
                   2758:     }
1.302     albertel 2759:     return %returnhash;
1.461     www      2760: }
                   2761: 
                   2762: # -------------------------------------------------See if a user is privileged
                   2763: 
                   2764: sub privileged {
                   2765:     my ($username,$domain)=@_;
                   2766:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2767: 			&homeserver($username,$domain));
                   2768:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2769:     my $now=time;
                   2770:     if ($rolesdump ne '') {
1.800     albertel 2771:         foreach my $entry (split(/&/,$rolesdump)) {
                   2772: 	    if ($entry!~/^rolesdef_/) {
                   2773: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2774: 		$area=~s/\_\w\w$//;
                   2775: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2776: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2777: 		    my $active=1;
                   2778: 		    if ($tend) {
                   2779: 			if ($tend<$now) { $active=0; }
                   2780: 		    }
                   2781: 		    if ($tstart) {
                   2782: 			if ($tstart>$now) { $active=0; }
                   2783: 		    }
                   2784: 		    if ($active) { return 1; }
                   2785: 		}
                   2786: 	    }
                   2787: 	}
                   2788:     }
                   2789:     return 0;
1.9       www      2790: }
1.1       albertel 2791: 
1.103     harris41 2792: # -------------------------------------------------------- Get user privileges
1.11      www      2793: 
                   2794: sub rolesinit {
                   2795:     my ($domain,$username,$authhost)=@_;
                   2796:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2797:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2798:     my %allroles=();
1.678     raeburn  2799:     my %allgroups=();   
1.11      www      2800:     my $now=time;
1.743     albertel 2801:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2802:     my $group_privs;
1.11      www      2803: 
                   2804:     if ($rolesdump ne '') {
1.800     albertel 2805:         foreach my $entry (split(/&/,$rolesdump)) {
                   2806: 	  if ($entry!~/^rolesdef_/) {
                   2807:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2808: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2809:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2810: 	    if ($role=~/^cr/) { 
1.807   ! albertel 2811: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
        !          2812: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2813: 		    ($tend,$tstart)=split('_',$trest);
                   2814: 		} else {
                   2815: 		    $trole=$role;
                   2816: 		}
1.678     raeburn  2817:             } elsif ($role =~ m|^gr/|) {
                   2818:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2819:                 ($trole,$group_privs) = split(/\//,$trole);
                   2820:                 $group_privs = &unescape($group_privs);
1.587     albertel 2821: 	    } else {
                   2822: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2823: 	    }
1.743     albertel 2824: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2825: 					 $username);
                   2826: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2827:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2828:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2829:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2830: 		my $spec=$trole.'.'.$area;
                   2831: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2832: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2833:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2834:                 } elsif ($trole eq 'gr') {
                   2835:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2836: 		} else {
1.567     raeburn  2837:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2838: 		}
1.12      www      2839:             }
1.662     raeburn  2840:           }
1.191     harris41 2841:         }
1.743     albertel 2842:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2843:         $userroles{'user.adv'}    = $adv;
                   2844: 	$userroles{'user.author'} = $author;
1.620     albertel 2845:         $env{'user.adv'}=$adv;
1.11      www      2846:     }
1.743     albertel 2847:     return \%userroles;  
1.11      www      2848: }
                   2849: 
1.567     raeburn  2850: sub set_arearole {
                   2851:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2852: # log the associated role with the area
                   2853:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2854:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2855: }
                   2856: 
                   2857: sub custom_roleprivs {
                   2858:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2859:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2860:     my $homsvr=homeserver($rauthor,$rdomain);
                   2861:     if ($hostname{$homsvr} ne '') {
                   2862:         my ($rdummy,$roledef)=
                   2863:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2864:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2865:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2866:             if (defined($syspriv)) {
                   2867:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2868:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2869:             }
                   2870:             if ($tdomain ne '') {
                   2871:                 if (defined($dompriv)) {
                   2872:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2873:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2874:                 }
                   2875:                 if (($trest ne '') && (defined($coursepriv))) {
                   2876:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2877:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2878:                 }
                   2879:             }
                   2880:         }
                   2881:     }
                   2882: }
                   2883: 
1.678     raeburn  2884: sub group_roleprivs {
                   2885:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2886:     my $access = 1;
                   2887:     my $now = time;
                   2888:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2889:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2890:     if ($access) {
1.807   ! albertel 2891:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_username)/([^/]+)$|);
1.678     raeburn  2892:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2893:     }
                   2894: }
1.567     raeburn  2895: 
                   2896: sub standard_roleprivs {
                   2897:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2898:     if (defined($pr{$trole.':s'})) {
                   2899:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2900:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2901:     }
                   2902:     if ($tdomain ne '') {
                   2903:         if (defined($pr{$trole.':d'})) {
                   2904:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2905:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2906:         }
                   2907:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2908:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2909:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2910:         }
                   2911:     }
                   2912: }
                   2913: 
                   2914: sub set_userprivs {
1.678     raeburn  2915:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2916:     my $author=0;
                   2917:     my $adv=0;
1.678     raeburn  2918:     my %grouproles = ();
                   2919:     if (keys(%{$allgroups}) > 0) {
                   2920:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2921:             my ($trole,$area,$sec,$extendedarea);
1.807   ! albertel 2922:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_username)(/?\w*)-) {
1.678     raeburn  2923:                 $trole = $1;
                   2924:                 $area = $2;
1.681     raeburn  2925:                 $sec = $3;
                   2926:                 $extendedarea = $area.$sec;
                   2927:                 if (exists($$allgroups{$area})) {
                   2928:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2929:                         my $spec = $trole.'.'.$extendedarea;
                   2930:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2931:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2932:                     }
                   2933:                 }
                   2934:             }
                   2935:         }
                   2936:     }
1.800     albertel 2937:     foreach my $group (keys(%grouproles)) {
                   2938:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2939:     }
1.800     albertel 2940:     foreach my $role (keys(%{$allroles})) {
                   2941:         my %thesepriv;
                   2942:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   2943:         foreach my $item (split(/:/,$$allroles{$role})) {
                   2944:             if ($item ne '') {
                   2945:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  2946:                 if ($restrictions eq '') {
                   2947:                     $thesepriv{$privilege}='F';
                   2948:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2949:                     $thesepriv{$privilege}.=$restrictions;
                   2950:                 }
                   2951:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2952:             }
                   2953:         }
                   2954:         my $thesestr='';
1.800     albertel 2955:         foreach my $priv (keys(%thesepriv)) {
                   2956: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   2957: 	}
                   2958:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  2959:     }
                   2960:     return ($author,$adv);
                   2961: }
                   2962: 
1.12      www      2963: # --------------------------------------------------------------- get interface
                   2964: 
                   2965: sub get {
1.131     albertel 2966:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2967:    my $items='';
1.800     albertel 2968:    foreach my $item (@$storearr) {
                   2969:        $items.=&escape($item).'&';
1.191     harris41 2970:    }
1.12      www      2971:    $items=~s/\&$//;
1.620     albertel 2972:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2973:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2974:    my $uhome=&homeserver($uname,$udomain);
                   2975: 
1.133     albertel 2976:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2977:    my @pairs=split(/\&/,$rep);
1.273     albertel 2978:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2979:      return @pairs;
                   2980:    }
1.15      www      2981:    my %returnhash=();
1.42      www      2982:    my $i=0;
1.800     albertel 2983:    foreach my $item (@$storearr) {
                   2984:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      2985:       $i++;
1.191     harris41 2986:    }
1.15      www      2987:    return %returnhash;
1.27      www      2988: }
                   2989: 
                   2990: # --------------------------------------------------------------- del interface
                   2991: 
                   2992: sub del {
1.133     albertel 2993:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2994:    my $items='';
1.800     albertel 2995:    foreach my $item (@$storearr) {
                   2996:        $items.=&escape($item).'&';
1.191     harris41 2997:    }
1.27      www      2998:    $items=~s/\&$//;
1.620     albertel 2999:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3000:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3001:    my $uhome=&homeserver($uname,$udomain);
                   3002: 
                   3003:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3004: }
                   3005: 
                   3006: # -------------------------------------------------------------- dump interface
                   3007: 
                   3008: sub dump {
1.755     albertel 3009:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3010:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3011:     if (!$uname) { $uname=$env{'user.name'}; }
                   3012:     my $uhome=&homeserver($uname,$udomain);
                   3013:     if ($regexp) {
                   3014: 	$regexp=&escape($regexp);
                   3015:     } else {
                   3016: 	$regexp='.';
                   3017:     }
                   3018:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3019:     my @pairs=split(/\&/,$rep);
                   3020:     my %returnhash=();
                   3021:     foreach my $item (@pairs) {
                   3022: 	my ($key,$value)=split(/=/,$item,2);
                   3023: 	$key = &unescape($key);
                   3024: 	next if ($key =~ /^error: 2 /);
                   3025: 	$returnhash{$key}=&thaw_unescape($value);
                   3026:     }
                   3027:     return %returnhash;
1.407     www      3028: }
                   3029: 
1.717     albertel 3030: # --------------------------------------------------------- dumpstore interface
                   3031: 
                   3032: sub dumpstore {
                   3033:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3034:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   3035: }
                   3036: 
1.407     www      3037: # -------------------------------------------------------------- keys interface
                   3038: 
                   3039: sub getkeys {
                   3040:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3041:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3042:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3043:    my $uhome=&homeserver($uname,$udomain);
                   3044:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3045:    my @keyarray=();
1.800     albertel 3046:    foreach my $key (split(/\&/,$rep)) {
                   3047:       push(@keyarray,&unescape($key));
1.407     www      3048:    }
                   3049:    return @keyarray;
1.318     matthew  3050: }
                   3051: 
1.319     matthew  3052: # --------------------------------------------------------------- currentdump
                   3053: sub currentdump {
1.328     matthew  3054:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3055:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3056:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3057:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3058:    my $uhome = &homeserver($sname,$sdom);
                   3059:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3060:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3061:    #
1.318     matthew  3062:    my %returnhash=();
1.319     matthew  3063:    #
                   3064:    if ($rep eq "unknown_cmd") { 
                   3065:        # an old lond will not know currentdump
                   3066:        # Do a dump and make it look like a currentdump
1.326     matthew  3067:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3068:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3069:        my %hash = @tmp;
                   3070:        @tmp=();
1.424     matthew  3071:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3072:    } else {
                   3073:        my @pairs=split(/\&/,$rep);
1.800     albertel 3074:        foreach my $pair (@pairs) {
                   3075:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3076:            my ($symb,$param) = split(/:/,$key);
                   3077:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3078:                                                         &thaw_unescape($value);
1.319     matthew  3079:        }
1.191     harris41 3080:    }
1.12      www      3081:    return %returnhash;
1.424     matthew  3082: }
                   3083: 
                   3084: sub convert_dump_to_currentdump{
                   3085:     my %hash = %{shift()};
                   3086:     my %returnhash;
                   3087:     # Code ripped from lond, essentially.  The only difference
                   3088:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3089:     # we might run in to problems with parameter names =~ /^v\./
                   3090:     while (my ($key,$value) = each(%hash)) {
                   3091:         my ($v,$symb,$param) = split(/:/,$key);
                   3092:         next if ($v eq 'version' || $symb eq 'keys');
                   3093:         next if (exists($returnhash{$symb}) &&
                   3094:                  exists($returnhash{$symb}->{$param}) &&
                   3095:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3096:         $returnhash{$symb}->{$param}=$value;
                   3097:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3098:     }
                   3099:     #
                   3100:     # Remove all of the keys in the hashes which keep track of
                   3101:     # the version of the parameter.
                   3102:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3103:         # use a foreach because we are going to delete from the hash.
                   3104:         foreach my $key (keys(%$param_hash)) {
                   3105:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3106:         }
                   3107:     }
                   3108:     return \%returnhash;
1.12      www      3109: }
                   3110: 
1.627     albertel 3111: # ------------------------------------------------------ critical inc interface
                   3112: 
                   3113: sub cinc {
                   3114:     return &inc(@_,'critical');
                   3115: }
                   3116: 
1.449     matthew  3117: # --------------------------------------------------------------- inc interface
                   3118: 
                   3119: sub inc {
1.627     albertel 3120:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3121:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3122:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3123:     my $uhome=&homeserver($uname,$udomain);
                   3124:     my $items='';
                   3125:     if (! ref($store)) {
                   3126:         # got a single value, so use that instead
                   3127:         $items = &escape($store).'=&';
                   3128:     } elsif (ref($store) eq 'SCALAR') {
                   3129:         $items = &escape($$store).'=&';        
                   3130:     } elsif (ref($store) eq 'ARRAY') {
                   3131:         $items = join('=&',map {&escape($_);} @{$store});
                   3132:     } elsif (ref($store) eq 'HASH') {
                   3133:         while (my($key,$value) = each(%{$store})) {
                   3134:             $items.= &escape($key).'='.&escape($value).'&';
                   3135:         }
                   3136:     }
                   3137:     $items=~s/\&$//;
1.627     albertel 3138:     if ($critical) {
                   3139: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3140:     } else {
                   3141: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3142:     }
1.449     matthew  3143: }
                   3144: 
1.12      www      3145: # --------------------------------------------------------------- put interface
                   3146: 
                   3147: sub put {
1.134     albertel 3148:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3149:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3150:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3151:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3152:    my $items='';
1.800     albertel 3153:    foreach my $item (keys(%$storehash)) {
                   3154:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3155:    }
1.12      www      3156:    $items=~s/\&$//;
1.134     albertel 3157:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3158: }
                   3159: 
1.631     albertel 3160: # ------------------------------------------------------------ newput interface
                   3161: 
                   3162: sub newput {
                   3163:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3164:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3165:    if (!$uname) { $uname=$env{'user.name'}; }
                   3166:    my $uhome=&homeserver($uname,$udomain);
                   3167:    my $items='';
                   3168:    foreach my $key (keys(%$storehash)) {
                   3169:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3170:    }
                   3171:    $items=~s/\&$//;
                   3172:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3173: }
                   3174: 
                   3175: # ---------------------------------------------------------  putstore interface
                   3176: 
1.524     raeburn  3177: sub putstore {
1.715     albertel 3178:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3180:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3181:    my $uhome=&homeserver($uname,$udomain);
                   3182:    my $items='';
1.715     albertel 3183:    foreach my $key (keys(%$storehash)) {
                   3184:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3185:    }
1.715     albertel 3186:    $items=~s/\&$//;
1.716     albertel 3187:    my $esc_symb=&escape($symb);
                   3188:    my $esc_v=&escape($version);
1.715     albertel 3189:    my $reply =
1.716     albertel 3190:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3191: 	      $uhome);
                   3192:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3193:        # gfall back to way things use to be done
1.715     albertel 3194:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3195: 			    $uname);
1.524     raeburn  3196:    }
1.715     albertel 3197:    return $reply;
                   3198: }
                   3199: 
                   3200: sub old_putstore {
1.716     albertel 3201:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3202:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3203:     if (!$uname) { $uname=$env{'user.name'}; }
                   3204:     my $uhome=&homeserver($uname,$udomain);
                   3205:     my %newstorehash;
1.800     albertel 3206:     foreach my $item (keys(%$storehash)) {
                   3207: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3208: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3209:     }
                   3210:     my $items='';
                   3211:     my %allitems = ();
1.800     albertel 3212:     foreach my $item (keys(%newstorehash)) {
                   3213: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3214: 	    my $key = $1.':keys:'.$2;
                   3215: 	    $allitems{$key} .= $3.':';
                   3216: 	}
1.800     albertel 3217: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3218:     }
1.800     albertel 3219:     foreach my $item (keys(%allitems)) {
                   3220: 	$allitems{$item} =~ s/\:$//;
                   3221: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3222:     }
                   3223:     $items=~s/\&$//;
                   3224:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3225: }
                   3226: 
1.47      www      3227: # ------------------------------------------------------ critical put interface
                   3228: 
                   3229: sub cput {
1.134     albertel 3230:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3231:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3232:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3233:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3234:    my $items='';
1.800     albertel 3235:    foreach my $item (keys(%$storehash)) {
                   3236:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3237:    }
1.47      www      3238:    $items=~s/\&$//;
1.134     albertel 3239:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3240: }
                   3241: 
                   3242: # -------------------------------------------------------------- eget interface
                   3243: 
                   3244: sub eget {
1.133     albertel 3245:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3246:    my $items='';
1.800     albertel 3247:    foreach my $item (@$storearr) {
                   3248:        $items.=&escape($item).'&';
1.191     harris41 3249:    }
1.12      www      3250:    $items=~s/\&$//;
1.620     albertel 3251:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3252:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3253:    my $uhome=&homeserver($uname,$udomain);
                   3254:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3255:    my @pairs=split(/\&/,$rep);
                   3256:    my %returnhash=();
1.42      www      3257:    my $i=0;
1.800     albertel 3258:    foreach my $item (@$storearr) {
                   3259:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3260:       $i++;
1.191     harris41 3261:    }
1.12      www      3262:    return %returnhash;
                   3263: }
                   3264: 
1.667     albertel 3265: # ------------------------------------------------------------ tmpput interface
                   3266: sub tmpput {
1.802     raeburn  3267:     my ($storehash,$server,$context)=@_;
1.667     albertel 3268:     my $items='';
1.800     albertel 3269:     foreach my $item (keys(%$storehash)) {
                   3270: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3271:     }
                   3272:     $items=~s/\&$//;
1.802     raeburn  3273:     if (defined($context)) {
                   3274:         $items .= ':'.&escape($context);
                   3275:     }
1.667     albertel 3276:     return &reply("tmpput:$items",$server);
                   3277: }
                   3278: 
                   3279: # ------------------------------------------------------------ tmpget interface
                   3280: sub tmpget {
1.688     albertel 3281:     my ($token,$server)=@_;
                   3282:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3283:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3284:     my %returnhash;
                   3285:     foreach my $item (split(/\&/,$rep)) {
                   3286: 	my ($key,$value)=split(/=/,$item);
                   3287: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3288:     }
                   3289:     return %returnhash;
                   3290: }
                   3291: 
1.688     albertel 3292: # ------------------------------------------------------------ tmpget interface
                   3293: sub tmpdel {
                   3294:     my ($token,$server)=@_;
                   3295:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3296:     return &reply("tmpdel:$token",$server);
                   3297: }
                   3298: 
1.765     albertel 3299: # -------------------------------------------------- portfolio access checking
                   3300: 
                   3301: sub portfolio_access {
1.766     albertel 3302:     my ($requrl) = @_;
1.765     albertel 3303:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3304:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3305:     if ($result eq 'ok') {
1.766     albertel 3306:        return 'F';
1.765     albertel 3307:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3308:        return 'A';
1.765     albertel 3309:     }
1.766     albertel 3310:     return '';
1.765     albertel 3311: }
                   3312: 
                   3313: sub get_portfolio_access {
1.767     albertel 3314:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3315: 
                   3316:     if (!ref($access_hash)) {
                   3317: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3318: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3319: 						   $file_name);
                   3320: 	$access_hash = $access_controls{$file_name};
                   3321:     }
                   3322: 
1.765     albertel 3323:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3324:     my $now = time;
                   3325:     if (ref($access_hash) eq 'HASH') {
                   3326:         foreach my $key (keys(%{$access_hash})) {
                   3327:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3328:             if ($start > $now) {
                   3329:                 next;
                   3330:             }
                   3331:             if ($end && $end<$now) {
                   3332:                 next;
                   3333:             }
                   3334:             if ($scope eq 'public') {
                   3335:                 $public = $key;
                   3336:                 last;
                   3337:             } elsif ($scope eq 'guest') {
                   3338:                 $guest = $key;
                   3339:             } elsif ($scope eq 'domains') {
                   3340:                 push(@domains,$key);
                   3341:             } elsif ($scope eq 'users') {
                   3342:                 push(@users,$key);
                   3343:             } elsif ($scope eq 'course') {
                   3344:                 push(@courses,$key);
                   3345:             } elsif ($scope eq 'group') {
                   3346:                 push(@groups,$key);
                   3347:             }
                   3348:         }
                   3349:         if ($public) {
                   3350:             return 'ok';
                   3351:         }
                   3352:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3353:             if ($guest) {
                   3354:                 return $guest;
                   3355:             }
                   3356:         } else {
                   3357:             if (@domains > 0) {
                   3358:                 foreach my $domkey (@domains) {
                   3359:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3360:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3361:                             return 'ok';
                   3362:                         }
                   3363:                     }
                   3364:                 }
                   3365:             }
                   3366:             if (@users > 0) {
                   3367:                 foreach my $userkey (@users) {
                   3368:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3369:                         return 'ok';
                   3370:                     }
                   3371:                 }
                   3372:             }
                   3373:             my %roleshash;
                   3374:             my @courses_and_groups = @courses;
                   3375:             push(@courses_and_groups,@groups); 
                   3376:             if (@courses_and_groups > 0) {
                   3377:                 my (%allgroups,%allroles); 
                   3378:                 my ($start,$end,$role,$sec,$group);
                   3379:                 foreach my $envkey (%env) {
1.807   ! albertel 3380:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_username)/?([^/]*)$-) {
1.765     albertel 3381:                         my $cid = $2.'_'.$3; 
                   3382:                         if ($1 eq 'gr') {
                   3383:                             $group = $4;
                   3384:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3385:                         } else {
                   3386:                             if ($4 eq '') {
                   3387:                                 $sec = 'none';
                   3388:                             } else {
                   3389:                                 $sec = $4;
                   3390:                             }
                   3391:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3392:                         }
1.807   ! albertel 3393:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_username)/?([^/]*)$-) {
1.765     albertel 3394:                         my $cid = $2.'_'.$3;
                   3395:                         if ($4 eq '') {
                   3396:                             $sec = 'none';
                   3397:                         } else {
                   3398:                             $sec = $4;
                   3399:                         }
                   3400:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3401:                     }
                   3402:                 }
                   3403:                 if (keys(%allroles) == 0) {
                   3404:                     return;
                   3405:                 }
                   3406:                 foreach my $key (@courses_and_groups) {
                   3407:                     my %content = %{$$access_hash{$key}};
                   3408:                     my $cnum = $content{'number'};
                   3409:                     my $cdom = $content{'domain'};
                   3410:                     my $cid = $cdom.'_'.$cnum;
                   3411:                     if (!exists($allroles{$cid})) {
                   3412:                         next;
                   3413:                     }    
                   3414:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3415:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3416:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3417:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3418:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3419:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3420:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3421:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3422:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3423:                                         if (grep/^all$/,@sections) {
                   3424:                                             return 'ok';
                   3425:                                         } else {
                   3426:                                             if (grep/^$sec$/,@sections) {
                   3427:                                                 return 'ok';
                   3428:                                             }
                   3429:                                         }
                   3430:                                     }
                   3431:                                 }
                   3432:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3433:                                     if (grep/^none$/,@groups) {
                   3434:                                         return 'ok';
                   3435:                                     }
                   3436:                                 } else {
                   3437:                                     if (grep/^all$/,@groups) {
                   3438:                                         return 'ok';
                   3439:                                     } 
                   3440:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3441:                                         if (grep/^$group$/,@groups) {
                   3442:                                             return 'ok';
                   3443:                                         }
                   3444:                                     }
                   3445:                                 } 
                   3446:                             }
                   3447:                         }
                   3448:                     }
                   3449:                 }
                   3450:             }
                   3451:             if ($guest) {
                   3452:                 return $guest;
                   3453:             }
                   3454:         }
                   3455:     }
                   3456:     return;
                   3457: }
                   3458: 
                   3459: sub course_group_datechecker {
                   3460:     my ($dates,$now,$status) = @_;
                   3461:     my ($start,$end) = split(/\./,$dates);
                   3462:     if (!$start && !$end) {
                   3463:         return 'ok';
                   3464:     }
                   3465:     if (grep/^active$/,@{$status}) {
                   3466:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3467:             return 'ok';
                   3468:         }
                   3469:     }
                   3470:     if (grep/^previous$/,@{$status}) {
                   3471:         if ($end > $now ) {
                   3472:             return 'ok';
                   3473:         }
                   3474:     }
                   3475:     if (grep/^future$/,@{$status}) {
                   3476:         if ($start > $now) {
                   3477:             return 'ok';
                   3478:         }
                   3479:     }
                   3480:     return; 
                   3481: }
                   3482: 
                   3483: sub parse_portfolio_url {
                   3484:     my ($url) = @_;
                   3485: 
                   3486:     my ($type,$udom,$unum,$group,$file_name);
                   3487:     
1.807   ! albertel 3488:     if ($url =~  m-^/*uploaded/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3489: 	$type = 1;
                   3490:         $udom = $1;
                   3491:         $unum = $2;
                   3492:         $file_name = $3;
1.807   ! albertel 3493:     } elsif ($url =~ m-^/*uploaded/($match_domain)/($match_username)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3494: 	$type = 2;
                   3495:         $udom = $1;
                   3496:         $unum = $2;
                   3497:         $group = $3;
                   3498:         $file_name = $3.'/'.$4;
                   3499:     }
                   3500:     if (wantarray) {
                   3501: 	return ($type,$udom,$unum,$file_name,$group);
                   3502:     }
                   3503:     return $type;
                   3504: }
                   3505: 
                   3506: sub is_portfolio_url {
                   3507:     my ($url) = @_;
                   3508:     return scalar(&parse_portfolio_url($url));
                   3509: }
                   3510: 
1.798     raeburn  3511: sub is_portfolio_file {
                   3512:     my ($file) = @_;
1.807   ! albertel 3513:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/$match_username\/portfolio/)) {
1.798     raeburn  3514:         return 1;
                   3515:     }
                   3516:     return;
                   3517: }
                   3518: 
                   3519: 
1.341     www      3520: # ---------------------------------------------- Custom access rule evaluation
                   3521: 
                   3522: sub customaccess {
                   3523:     my ($priv,$uri)=@_;
1.807   ! albertel 3524:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.343     www      3525:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.807   ! albertel 3526:     $udom = &LONCAPA::clean_domain($udom);
        !          3527:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3528:     my $access=0;
1.800     albertel 3529:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3530: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3531:         if ($role) {
                   3532: 	   if ($role ne $urole) { next; }
                   3533:         }
1.800     albertel 3534:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3535:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3536:             if ($tdom) {
                   3537: 		if ($tdom ne $udom) { next; }
                   3538:             }
                   3539:             if ($tcrs) {
                   3540: 		if ($tcrs ne $ucrs) { next; }
                   3541:             }
                   3542:             if ($tsec) {
                   3543: 		if ($tsec ne $usec) { next; }
                   3544:             }
                   3545:             $access=($effect eq 'allow');
                   3546:             last;
1.342     www      3547:         }
1.402     bowersj2 3548: 	if ($realm eq '' && $role eq '') {
                   3549:             $access=($effect eq 'allow');
                   3550: 	}
1.341     www      3551:     }
                   3552:     return $access;
                   3553: }
                   3554: 
1.103     harris41 3555: # ------------------------------------------------- Check for a user privilege
1.12      www      3556: 
                   3557: sub allowed {
1.579     albertel 3558:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3559:     my $ver_orguri=$uri;
1.439     www      3560:     $uri=&deversion($uri);
1.152     www      3561:     my $orguri=$uri;
1.52      www      3562:     $uri=&declutter($uri);
1.545     banghart 3563:     
1.620     albertel 3564:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3565: # Free bre access to adm and meta resources
1.775     albertel 3566:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3567: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3568: 	&& ($priv eq 'bre')) {
1.14      www      3569: 	return 'F';
1.159     www      3570:     }
                   3571: 
1.545     banghart 3572: # Free bre access to user's own portfolio contents
1.714     raeburn  3573:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3574:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3575: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3576:         return 'F';
                   3577:     }
                   3578: 
1.762     raeburn  3579: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3580:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3581:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3582:         if (exists($env{'request.course.id'})) {
                   3583:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3584:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3585:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3586:                 my $courseprivid=$env{'request.course.id'};
                   3587:                 $courseprivid=~s/\_/\//;
                   3588:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3589:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3590:                     return $1; 
1.762     raeburn  3591:                 } else {
                   3592:                     if ($env{'request.course.sec'}) {
                   3593:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3594:                     }
                   3595:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3596:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3597:                         return $2;
                   3598:                     }
1.714     raeburn  3599:                 }
                   3600:             }
                   3601:         }
                   3602:     }
                   3603: 
1.159     www      3604: # Free bre to public access
                   3605: 
                   3606:     if ($priv eq 'bre') {
1.238     www      3607:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3608: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3609:            return 'F'; 
                   3610:         }
1.238     www      3611:         if ($copyright eq 'priv') {
                   3612:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3613: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3614: 		return '';
                   3615:             }
                   3616:         }
                   3617:         if ($copyright eq 'domain') {
                   3618:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3619: 	    unless (($env{'user.domain'} eq $1) ||
                   3620:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3621: 		return '';
                   3622:             }
1.262     matthew  3623:         }
1.620     albertel 3624:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3625:             # Library role, so allow browsing of resources in this domain.
                   3626:             return 'F';
1.238     www      3627:         }
1.341     www      3628:         if ($copyright eq 'custom') {
                   3629: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3630:         }
1.14      www      3631:     }
1.264     matthew  3632:     # Domain coordinator is trying to create a course
1.620     albertel 3633:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3634:         # uri is the requested domain in this case.
                   3635:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3636:         # a role of dc for the domain in question.
1.620     albertel 3637:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3638:     }
1.29      www      3639: 
1.52      www      3640:     my $thisallowed='';
                   3641:     my $statecond=0;
                   3642:     my $courseprivid='';
                   3643: 
                   3644: # Course
                   3645: 
1.620     albertel 3646:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3647:        $thisallowed.=$1;
                   3648:     }
1.29      www      3649: 
1.52      www      3650: # Domain
                   3651: 
1.620     albertel 3652:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3653:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3654:        $thisallowed.=$1;
                   3655:     }
1.52      www      3656: 
                   3657: # Course: uri itself is a course
1.66      www      3658:     my $courseuri=$uri;
                   3659:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3660:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3661: 
1.620     albertel 3662:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3663:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3664:        $thisallowed.=$1;
                   3665:     }
1.29      www      3666: 
1.665     albertel 3667: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3668: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3669:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3670: 	$thisallowed='';
1.671     raeburn  3671:         my ($match)=&is_on_map($uri);
                   3672:         if ($match) {
                   3673:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3674:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3675:                 $thisallowed.=$1;
                   3676:             }
                   3677:         } else {
1.705     albertel 3678:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3679:             if ($refuri) {
                   3680:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3681:                     $thisallowed='F';
1.671     raeburn  3682:                 } else {
                   3683:                     $refuri=&declutter($refuri);
                   3684:                     my ($match) = &is_on_map($refuri);
                   3685:                     if ($match) {
                   3686:                         $thisallowed='F';
                   3687:                     }
1.669     raeburn  3688:                 }
1.671     raeburn  3689:             }
                   3690:         }
1.314     www      3691:     }
1.492     albertel 3692: 
1.766     albertel 3693:     if ($priv eq 'bre'
                   3694: 	&& $thisallowed ne 'F' 
                   3695: 	&& $thisallowed ne '2'
                   3696: 	&& &is_portfolio_url($uri)) {
                   3697: 	$thisallowed = &portfolio_access($uri);
                   3698:     }
                   3699:     
1.52      www      3700: # Full access at system, domain or course-wide level? Exit.
1.29      www      3701: 
                   3702:     if ($thisallowed=~/F/) {
                   3703: 	return 'F';
                   3704:     }
                   3705: 
1.52      www      3706: # If this is generating or modifying users, exit with special codes
1.29      www      3707: 
1.643     www      3708:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3709: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3710: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3711: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3712: 	    unless ($auname) { return $thisallowed; }
                   3713: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3714: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3715: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3716: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3717: 	}
1.52      www      3718: 	return $thisallowed;
                   3719:     }
                   3720: #
1.103     harris41 3721: # Gathered so far: system, domain and course wide privileges
1.52      www      3722: #
                   3723: # Course: See if uri or referer is an individual resource that is part of 
                   3724: # the course
                   3725: 
1.620     albertel 3726:     if ($env{'request.course.id'}) {
1.232     www      3727: 
1.620     albertel 3728:        $courseprivid=$env{'request.course.id'};
                   3729:        if ($env{'request.course.sec'}) {
                   3730:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3731:        }
                   3732:        $courseprivid=~s/\_/\//;
                   3733:        my $checkreferer=1;
1.232     www      3734:        my ($match,$cond)=&is_on_map($uri);
                   3735:        if ($match) {
                   3736:            $statecond=$cond;
1.620     albertel 3737:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3738:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3739:                $thisallowed.=$1;
                   3740:                $checkreferer=0;
                   3741:            }
1.29      www      3742:        }
1.83      www      3743:        
1.148     www      3744:        if ($checkreferer) {
1.620     albertel 3745: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3746:             unless ($refuri) {
1.800     albertel 3747:                 foreach my $key (keys(%env)) {
                   3748: 		    if ($key=~/^httpref\..*\*/) {
                   3749: 			my $pattern=$key;
1.156     www      3750:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3751:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3752:                         $pattern=~s/\//\\\//g;
1.152     www      3753:                         if ($orguri=~/$pattern/) {
1.800     albertel 3754: 			    $refuri=$env{$key};
1.148     www      3755:                         }
                   3756:                     }
1.191     harris41 3757:                 }
1.148     www      3758:             }
1.232     www      3759: 
1.148     www      3760:          if ($refuri) { 
1.152     www      3761: 	  $refuri=&declutter($refuri);
1.232     www      3762:           my ($match,$cond)=&is_on_map($refuri);
                   3763:             if ($match) {
                   3764:               my $refstatecond=$cond;
1.620     albertel 3765:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3766:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3767:                   $thisallowed.=$1;
1.53      www      3768:                   $uri=$refuri;
                   3769:                   $statecond=$refstatecond;
1.52      www      3770:               }
                   3771:           }
1.148     www      3772:         }
1.29      www      3773:        }
1.52      www      3774:    }
1.29      www      3775: 
1.52      www      3776: #
1.103     harris41 3777: # Gathered now: all privileges that could apply, and condition number
1.52      www      3778: # 
                   3779: #
                   3780: # Full or no access?
                   3781: #
1.29      www      3782: 
1.52      www      3783:     if ($thisallowed=~/F/) {
                   3784: 	return 'F';
                   3785:     }
1.29      www      3786: 
1.52      www      3787:     unless ($thisallowed) {
                   3788:         return '';
                   3789:     }
1.29      www      3790: 
1.52      www      3791: # Restrictions exist, deal with them
                   3792: #
                   3793: #   C:according to course preferences
                   3794: #   R:according to resource settings
                   3795: #   L:unless locked
                   3796: #   X:according to user session state
                   3797: #
                   3798: 
                   3799: # Possibly locked functionality, check all courses
1.54      www      3800: # Locks might take effect only after 10 minutes cache expiration for other
                   3801: # courses, and 2 minutes for current course
1.52      www      3802: 
                   3803:     my $envkey;
                   3804:     if ($thisallowed=~/L/) {
1.620     albertel 3805:         foreach $envkey (keys %env) {
1.54      www      3806:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3807:                my $courseid=$2;
                   3808:                my $roleid=$1.'.'.$2;
1.92      www      3809:                $courseid=~s/^\///;
1.54      www      3810:                my $expiretime=600;
1.620     albertel 3811:                if ($env{'request.role'} eq $roleid) {
1.54      www      3812: 		  $expiretime=120;
                   3813:                }
                   3814: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3815:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3816:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3817: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3818:                }
1.620     albertel 3819:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3820:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3821: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3822:                        &log($env{'user.domain'},$env{'user.name'},
                   3823:                             $env{'user.home'},
1.57      www      3824:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3825:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3826:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3827: 		       return '';
                   3828:                    }
                   3829:                }
1.620     albertel 3830:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3831:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3832: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3833:                        &log($env{'user.domain'},$env{'user.name'},
                   3834:                             $env{'user.home'},
1.57      www      3835:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3836:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3837:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3838: 		       return '';
                   3839:                    }
                   3840:                }
                   3841: 	   }
1.29      www      3842:        }
1.52      www      3843:     }
                   3844:    
                   3845: #
                   3846: # Rest of the restrictions depend on selected course
                   3847: #
                   3848: 
1.620     albertel 3849:     unless ($env{'request.course.id'}) {
1.766     albertel 3850: 	if ($thisallowed eq 'A') {
                   3851: 	    return 'A';
                   3852: 	} else {
                   3853: 	    return '1';
                   3854: 	}
1.52      www      3855:     }
1.29      www      3856: 
1.52      www      3857: #
                   3858: # Now user is definitely in a course
                   3859: #
1.53      www      3860: 
                   3861: 
                   3862: # Course preferences
                   3863: 
                   3864:    if ($thisallowed=~/C/) {
1.620     albertel 3865:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3866:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3867:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3868: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3869: 	   if ($priv ne 'pch') { 
                   3870: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3871: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3872: 			$env{'request.course.id'});
                   3873: 	   }
1.237     www      3874:            return '';
                   3875:        }
                   3876: 
1.620     albertel 3877:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3878: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3879: 	   if ($priv ne 'pch') { 
                   3880: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3881: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3882: 			$env{'request.course.id'});
                   3883: 	   }
1.54      www      3884:            return '';
                   3885:        }
1.53      www      3886:    }
                   3887: 
                   3888: # Resource preferences
                   3889: 
                   3890:    if ($thisallowed=~/R/) {
1.620     albertel 3891:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3892:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3893: 	   if ($priv ne 'pch') { 
                   3894: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3895: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3896: 	   }
                   3897: 	   return '';
1.54      www      3898:        }
1.53      www      3899:    }
1.30      www      3900: 
1.246     www      3901: # Restricted by state or randomout?
1.30      www      3902: 
1.52      www      3903:    if ($thisallowed=~/X/) {
1.620     albertel 3904:       if ($env{'acc.randomout'}) {
1.579     albertel 3905: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3906:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3907:             return ''; 
                   3908:          }
1.247     www      3909:       }
                   3910:       if (&condval($statecond)) {
1.52      www      3911: 	 return '2';
                   3912:       } else {
                   3913:          return '';
                   3914:       }
                   3915:    }
1.30      www      3916: 
1.766     albertel 3917:     if ($thisallowed eq 'A') {
                   3918: 	return 'A';
                   3919:     }
1.52      www      3920:    return 'F';
1.232     www      3921: }
                   3922: 
1.710     albertel 3923: sub split_uri_for_cond {
                   3924:     my $uri=&deversion(&declutter(shift));
                   3925:     my @uriparts=split(/\//,$uri);
                   3926:     my $filename=pop(@uriparts);
                   3927:     my $pathname=join('/',@uriparts);
                   3928:     return ($pathname,$filename);
                   3929: }
1.232     www      3930: # --------------------------------------------------- Is a resource on the map?
                   3931: 
                   3932: sub is_on_map {
1.710     albertel 3933:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3934:     #Trying to find the conditional for the file
1.620     albertel 3935:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3936: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3937:     if ($match) {
1.289     bowersj2 3938: 	return (1,$1);
                   3939:     } else {
1.434     www      3940: 	return (0,0);
1.289     bowersj2 3941:     }
1.12      www      3942: }
                   3943: 
1.427     www      3944: # --------------------------------------------------------- Get symb from alias
                   3945: 
                   3946: sub get_symb_from_alias {
                   3947:     my $symb=shift;
                   3948:     my ($map,$resid,$url)=&decode_symb($symb);
                   3949: # Already is a symb
                   3950:     if ($url) { return $symb; }
                   3951: # Must be an alias
                   3952:     my $aliassymb='';
                   3953:     my %bighash;
1.620     albertel 3954:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3955:                             &GDBM_READER(),0640)) {
                   3956:         my $rid=$bighash{'mapalias_'.$symb};
                   3957: 	if ($rid) {
                   3958: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3959: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3960: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3961: 	}
                   3962:         untie %bighash;
                   3963:     }
                   3964:     return $aliassymb;
                   3965: }
                   3966: 
1.12      www      3967: # ----------------------------------------------------------------- Define Role
                   3968: 
                   3969: sub definerole {
                   3970:   if (allowed('mcr','/')) {
                   3971:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 3972:     foreach my $role (split(':',$sysrole)) {
                   3973: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3974:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3975:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3976: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3977:                return "refused:s:$crole&$cqual"; 
                   3978:             }
                   3979:         }
1.191     harris41 3980:     }
1.800     albertel 3981:     foreach my $role (split(':',$domrole)) {
                   3982: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3983:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3984:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3985: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3986:                return "refused:d:$crole&$cqual"; 
                   3987:             }
                   3988:         }
1.191     harris41 3989:     }
1.800     albertel 3990:     foreach my $role (split(':',$courole)) {
                   3991: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3992:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3993:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3994: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3995:                return "refused:c:$crole&$cqual"; 
                   3996:             }
                   3997:         }
1.191     harris41 3998:     }
1.620     albertel 3999:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4000:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4001: 	        "rolesdef_$rolename=".
                   4002:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4003:     return reply($command,$env{'user.home'});
1.12      www      4004:   } else {
                   4005:     return 'refused';
                   4006:   }
1.105     harris41 4007: }
                   4008: 
                   4009: # ---------------- Make a metadata query against the network of library servers
                   4010: 
                   4011: sub metadata_query {
1.244     matthew  4012:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4013:     my %rhash;
1.244     matthew  4014:     my @server_list = (defined($server_array) ? @$server_array
                   4015:                                               : keys(%libserv) );
                   4016:     for my $server (@server_list) {
1.118     harris41 4017: 	unless ($custom or $customshow) {
                   4018: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4019: 	    $rhash{$server}=$reply;
                   4020: 	}
                   4021: 	else {
                   4022: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4023: 			     &escape($custom).':'.&escape($customshow),
                   4024: 			     $server);
                   4025: 	    $rhash{$server}=$reply;
                   4026: 	}
1.112     harris41 4027:     }
1.118     harris41 4028:     return \%rhash;
1.240     www      4029: }
                   4030: 
                   4031: # ----------------------------------------- Send log queries and wait for reply
                   4032: 
                   4033: sub log_query {
                   4034:     my ($uname,$udom,$query,%filters)=@_;
                   4035:     my $uhome=&homeserver($uname,$udom);
                   4036:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4037:     my $uhost=$hostname{$uhome};
1.800     albertel 4038:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4039:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4040:                        $uhome);
1.479     albertel 4041:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4042:     return get_query_reply($queryid);
                   4043: }
                   4044: 
1.508     raeburn  4045: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4046: 
                   4047: sub fetch_enrollment_query {
1.511     raeburn  4048:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4049:     my $homeserver;
1.547     raeburn  4050:     my $maxtries = 1;
1.508     raeburn  4051:     if ($context eq 'automated') {
                   4052:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4053:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4054:     } else {
                   4055:         $homeserver = &homeserver($cnum,$dom);
                   4056:     }
1.506     raeburn  4057:     my $host=$hostname{$homeserver};
                   4058:     my $cmd = '';
1.800     albertel 4059:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4060:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4061:     }
                   4062:     $cmd =~ s/%%$//;
                   4063:     $cmd = &escape($cmd);
                   4064:     my $query = 'fetchenrollment';
1.620     albertel 4065:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4066:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4067:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4068:         return 'error: '.$queryid;
                   4069:     }
1.506     raeburn  4070:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4071:     my $tries = 1;
                   4072:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4073:         $reply = &get_query_reply($queryid);
                   4074:         $tries ++;
                   4075:     }
1.526     raeburn  4076:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4077:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4078:     } else {
1.515     raeburn  4079:         my @responses = split/:/,$reply;
                   4080:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4081:             foreach my $line (@responses) {
                   4082:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4083:                 $$replyref{$key} = $value;
                   4084:             }
                   4085:         } else {
1.506     raeburn  4086:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4087:             foreach my $line (@responses) {
                   4088:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4089:                 $$replyref{$key} = $value;
                   4090:                 if ($value > 0) {
1.800     albertel 4091:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4092:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4093:                         my $destname = $pathname.'/'.$filename;
                   4094:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4095:                         if ($xml_classlist =~ /^error/) {
                   4096:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4097:                         } else {
1.506     raeburn  4098:                             if ( open(FILE,">$destname") ) {
                   4099:                                 print FILE &unescape($xml_classlist);
                   4100:                                 close(FILE);
1.526     raeburn  4101:                             } else {
                   4102:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4103:                             }
                   4104:                         }
                   4105:                     }
                   4106:                 }
                   4107:             }
                   4108:         }
                   4109:         return 'ok';
                   4110:     }
                   4111:     return 'error';
                   4112: }
                   4113: 
1.242     www      4114: sub get_query_reply {
                   4115:     my $queryid=shift;
1.240     www      4116:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4117:     my $reply='';
                   4118:     for (1..100) {
                   4119: 	sleep 2;
                   4120:         if (-e $replyfile.'.end') {
1.448     albertel 4121: 	    if (open(my $fh,$replyfile)) {
1.240     www      4122:                $reply.=<$fh>;
1.448     albertel 4123:                close($fh);
1.240     www      4124: 	   } else { return 'error: reply_file_error'; }
1.242     www      4125:            return &unescape($reply);
                   4126: 	}
1.240     www      4127:     }
1.242     www      4128:     return 'timeout:'.$queryid;
1.240     www      4129: }
                   4130: 
                   4131: sub courselog_query {
1.241     www      4132: #
                   4133: # possible filters:
                   4134: # url: url or symb
                   4135: # username
                   4136: # domain
                   4137: # action: view, submit, grade
                   4138: # start: timestamp
                   4139: # end: timestamp
                   4140: #
1.240     www      4141:     my (%filters)=@_;
1.620     albertel 4142:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4143:     if ($filters{'url'}) {
                   4144: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4145:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4146:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4147:     }
1.620     albertel 4148:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4149:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4150:     return &log_query($cname,$cdom,'courselog',%filters);
                   4151: }
                   4152: 
                   4153: sub userlog_query {
                   4154:     my ($uname,$udom,%filters)=@_;
                   4155:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4156: }
                   4157: 
1.506     raeburn  4158: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4159: 
                   4160: sub auto_run {
1.508     raeburn  4161:     my ($cnum,$cdom) = @_;
                   4162:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4163:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4164:     return $response;
                   4165: }
1.776     albertel 4166: 
1.506     raeburn  4167: sub auto_get_sections {
1.508     raeburn  4168:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4169:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4170:     my @secs = ();
1.511     raeburn  4171:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4172:     unless ($response eq 'refused') {
                   4173:         @secs = split/:/,$response;
                   4174:     }
                   4175:     return @secs;
                   4176: }
1.776     albertel 4177: 
1.506     raeburn  4178: sub auto_new_course {
1.508     raeburn  4179:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4180:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4181:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4182:     return $response;
                   4183: }
1.776     albertel 4184: 
1.506     raeburn  4185: sub auto_validate_courseID {
1.508     raeburn  4186:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4187:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4188:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4189:     return $response;
                   4190: }
1.776     albertel 4191: 
1.506     raeburn  4192: sub auto_create_password {
1.508     raeburn  4193:     my ($cnum,$cdom,$authparam) = @_;
                   4194:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4195:     my $create_passwd = 0;
                   4196:     my $authchk = '';
1.511     raeburn  4197:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4198:     if ($response eq 'refused') {
                   4199:         $authchk = 'refused';
                   4200:     } else {
                   4201:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4202:     }
                   4203:     return ($authparam,$create_passwd,$authchk);
                   4204: }
                   4205: 
1.706     raeburn  4206: sub auto_photo_permission {
                   4207:     my ($cnum,$cdom,$students) = @_;
                   4208:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4209:     my ($outcome,$perm_reqd,$conditions) = 
                   4210: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4211:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4212: 	return (undef,undef);
                   4213:     }
1.706     raeburn  4214:     return ($outcome,$perm_reqd,$conditions);
                   4215: }
                   4216: 
                   4217: sub auto_checkphotos {
                   4218:     my ($uname,$udom,$pid) = @_;
                   4219:     my $homeserver = &homeserver($uname,$udom);
                   4220:     my ($result,$resulttype);
                   4221:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4222: 				   &escape($uname).':'.&escape($pid),
                   4223: 				   $homeserver));
1.709     albertel 4224:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4225: 	return (undef,undef);
                   4226:     }
1.706     raeburn  4227:     if ($outcome) {
                   4228:         ($result,$resulttype) = split(/:/,$outcome);
                   4229:     } 
                   4230:     return ($result,$resulttype);
                   4231: }
                   4232: 
                   4233: sub auto_photochoice {
                   4234:     my ($cnum,$cdom) = @_;
                   4235:     my $homeserver = &homeserver($cnum,$cdom);
                   4236:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4237: 						       &escape($cdom),
                   4238: 						       $homeserver)));
1.709     albertel 4239:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4240: 	return (undef,undef);
                   4241:     }
1.706     raeburn  4242:     return ($update,$comment);
                   4243: }
                   4244: 
                   4245: sub auto_photoupdate {
                   4246:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4247:     my $homeserver = &homeserver($cnum,$dom);
                   4248:     my $host=$hostname{$homeserver};
                   4249:     my $cmd = '';
                   4250:     my $maxtries = 1;
1.800     albertel 4251:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4252:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4253:     }
                   4254:     $cmd =~ s/%%$//;
                   4255:     $cmd = &escape($cmd);
                   4256:     my $query = 'institutionalphotos';
                   4257:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4258:     unless ($queryid=~/^\Q$host\E\_/) {
                   4259:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4260:         return 'error: '.$queryid;
                   4261:     }
                   4262:     my $reply = &get_query_reply($queryid);
                   4263:     my $tries = 1;
                   4264:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4265:         $reply = &get_query_reply($queryid);
                   4266:         $tries ++;
                   4267:     }
                   4268:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4269:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4270:     } else {
                   4271:         my @responses = split(/:/,$reply);
                   4272:         my $outcome = shift(@responses); 
                   4273:         foreach my $item (@responses) {
                   4274:             my ($key,$value) = split(/=/,$item);
                   4275:             $$photo{$key} = $value;
                   4276:         }
                   4277:         return $outcome;
                   4278:     }
                   4279:     return 'error';
                   4280: }
                   4281: 
1.521     raeburn  4282: sub auto_instcode_format {
1.793     albertel 4283:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4284: 	$cat_order) = @_;
1.521     raeburn  4285:     my $courses = '';
1.772     raeburn  4286:     my @homeservers;
1.521     raeburn  4287:     if ($caller eq 'global') {
1.793     albertel 4288:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4289:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4290:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4291:                     push(@homeservers,$tryserver);
                   4292:                 }
1.584     raeburn  4293:             }
                   4294:         }
1.521     raeburn  4295:     } else {
1.772     raeburn  4296:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4297:     }
1.793     albertel 4298:     foreach my $code (keys(%{$instcodes})) {
                   4299:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4300:     }
                   4301:     chop($courses);
1.772     raeburn  4302:     my $ok_response = 0;
                   4303:     my $response;
                   4304:     while (@homeservers > 0 && $ok_response == 0) {
                   4305:         my $server = shift(@homeservers); 
                   4306:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4307:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4308:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4309: 		split/:/,$response;
1.772     raeburn  4310:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4311:             push(@{$codetitles},&str2array($codetitles_str));
                   4312:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4313:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4314:             $ok_response = 1;
                   4315:         }
                   4316:     }
                   4317:     if ($ok_response) {
1.521     raeburn  4318:         return 'ok';
1.772     raeburn  4319:     } else {
                   4320:         return $response;
1.521     raeburn  4321:     }
                   4322: }
                   4323: 
1.792     raeburn  4324: sub auto_instcode_defaults {
                   4325:     my ($domain,$returnhash,$code_order) = @_;
                   4326:     my @homeservers;
1.793     albertel 4327:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4328:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4329:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4330:                 push(@homeservers,$tryserver);
                   4331:             }
                   4332:         }
                   4333:     }
                   4334:     my $ok_response = 0;
                   4335:     my $response;
                   4336:     while (@homeservers > 0 && $ok_response == 0) {
                   4337:         my $server = shift(@homeservers);
                   4338:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4339:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4340:             foreach my $pair (split(/\&/,$response)) {
                   4341:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4342:                 if ($name eq 'code_order') {
1.796     raeburn  4343:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4344:                 } else {
1.796     raeburn  4345:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4346:                 }
                   4347:             }
1.804     raeburn  4348:             $ok_response = 1;
1.792     raeburn  4349:         }
                   4350:     }
                   4351:     if ($ok_response) {
                   4352:         return 'ok';
                   4353:     } else {
                   4354:         return $response;
                   4355:     }
                   4356: } 
                   4357: 
1.777     albertel 4358: sub auto_validate_class_sec {
1.773     raeburn  4359:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4360:     my $homeserver = &homeserver($cnum,$cdom);
                   4361:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4362:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4363:     return $response;
                   4364: }
                   4365: 
1.679     raeburn  4366: # ------------------------------------------------------- Course Group routines
                   4367: 
                   4368: sub get_coursegroups {
1.683     raeburn  4369:     my ($cdom,$cnum,$group) = @_;
                   4370:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4371: }
                   4372: 
1.805     raeburn  4373: sub get_deleted_groups {
                   4374:     my ($cdom,$cnum,$group) = @_;
                   4375:     return(&dump('deleted_groups',$cdom,$cnum,$group));
                   4376: }
                   4377: 
1.679     raeburn  4378: sub modify_coursegroup {
                   4379:     my ($cdom,$cnum,$groupsettings) = @_;
                   4380:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4381: }
                   4382: 
1.805     raeburn  4383: sub delete_coursegroup {
                   4384:     my ($cdom,$cnum,$group) = @_;
                   4385:     my %curr_group = &get_coursegroups($cdom,$cnum,$group);
                   4386:     if (my $tmp = &error(%curr_group)) {
                   4387:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4388:         return ('read error',$tmp);
                   4389:     } else {
                   4390:         my %savedsettings = %curr_group; 
                   4391:         my $result = &put('deleted_groups',\%savedsettings,$cdom,$cnum);
                   4392:         my $deloutcome;
                   4393:         if ($result eq 'ok') {
                   4394:             $deloutcome = &del('coursegroups',[$group],$cdom,$cnum);
                   4395:         } else {
                   4396:             return ('write error',$result);
                   4397:         }
                   4398:         if ($deloutcome eq 'ok') {
                   4399:             return 'ok';
                   4400:         } else {
                   4401:             return ('delete error',$deloutcome);
                   4402:         }
                   4403:     }
                   4404: }
                   4405: 
1.679     raeburn  4406: sub modify_group_roles {
                   4407:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4408:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4409:     my $role = 'gr/'.&escape($userprivs);
                   4410:     my ($uname,$udom) = split(/:/,$user);
                   4411:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4412:     if ($result eq 'ok') {
                   4413:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4414:     }
1.679     raeburn  4415:     return $result;
                   4416: }
                   4417: 
                   4418: sub modify_coursegroup_membership {
                   4419:     my ($cdom,$cnum,$membership) = @_;
                   4420:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4421:     return $result;
                   4422: }
                   4423: 
1.682     raeburn  4424: sub get_active_groups {
                   4425:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4426:     my $now = time;
                   4427:     my %groups = ();
                   4428:     foreach my $key (keys(%env)) {
1.807   ! albertel 4429:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_username)/(\w+)$-) {
1.682     raeburn  4430:             my ($start,$end) = split(/\./,$env{$key});
                   4431:             if (($end!=0) && ($end<$now)) { next; }
                   4432:             if (($start!=0) && ($start>$now)) { next; }
                   4433:             if ($1 eq $cdom && $2 eq $cnum) {
                   4434:                 $groups{$3} = $env{$key} ;
                   4435:             }
                   4436:         }
                   4437:     }
                   4438:     return %groups;
                   4439: }
                   4440: 
1.683     raeburn  4441: sub get_group_membership {
                   4442:     my ($cdom,$cnum,$group) = @_;
                   4443:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4444: }
                   4445: 
                   4446: sub get_users_groups {
                   4447:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4448:     my @usersgroups;
1.683     raeburn  4449:     my $cachetime=1800;
                   4450: 
                   4451:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4452:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4453:     if (defined($cached)) {
1.734     albertel 4454:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4455:     } else {  
                   4456:         $grouplist = '';
                   4457:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4458:         my ($tmp) = keys(%roleshash);
                   4459:         if ($tmp=~/^error:/) {
                   4460:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4461:         } else {
                   4462:             my $access_end = $env{'course.'.$courseid.
                   4463:                                   '.default_enrollment_end_date'};
                   4464:             my $now = time;
1.734     albertel 4465:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4466:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4467:                     my $group = $1;
                   4468:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4469:                         my $start = $2;
                   4470:                         my $end = $1;
                   4471:                         if ($start == -1) { next; } # deleted from group
                   4472:                         if (($start!=0) && ($start>$now)) { next; }
                   4473:                         if (($end!=0) && ($end<$now)) {
                   4474:                             if ($access_end && $access_end < $now) {
                   4475:                                 if ($access_end - $end < 86400) {
                   4476:                                     push(@usersgroups,$group);
                   4477:                                 }
                   4478:                             }
                   4479:                             next;
                   4480:                         }
                   4481:                         push(@usersgroups,$group);
                   4482:                     }
1.683     raeburn  4483:                 }
                   4484:             }
1.733     raeburn  4485:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4486:             $grouplist = join(':',@usersgroups);
                   4487:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4488:         }
                   4489:     }
1.733     raeburn  4490:     return @usersgroups;
1.683     raeburn  4491: }
                   4492: 
                   4493: sub devalidate_getgroups_cache {
                   4494:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4495:     my $courseid = $cdom.'_'.$cnum;
1.807   ! albertel 4496: 
1.683     raeburn  4497:     my $hashid="$udom:$uname:$courseid";
                   4498:     &devalidate_cache_new('getgroups',$hashid);
                   4499: }
                   4500: 
1.12      www      4501: # ------------------------------------------------------------------ Plain Text
                   4502: 
                   4503: sub plaintext {
1.742     raeburn  4504:     my ($short,$type,$cid) = @_;
1.758     albertel 4505:     if ($short =~ /^cr/) {
                   4506: 	return (split('/',$short))[-1];
                   4507:     }
1.742     raeburn  4508:     if (!defined($cid)) {
                   4509:         $cid = $env{'request.course.id'};
                   4510:     }
                   4511:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4512:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4513:                                           '.plaintext'});
                   4514:     }
                   4515:     my %rolenames = (
                   4516:                       Course => 'std',
                   4517:                       Group => 'alt1',
                   4518:                     );
                   4519:     if (defined($type) && 
                   4520:          defined($rolenames{$type}) && 
                   4521:          defined($prp{$short}{$rolenames{$type}})) {
                   4522:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4523:     } else {
                   4524:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4525:     }
1.12      www      4526: }
                   4527: 
                   4528: # ----------------------------------------------------------------- Assign Role
                   4529: 
                   4530: sub assignrole {
1.357     www      4531:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4532:     my $mrole;
                   4533:     if ($role =~ /^cr\//) {
1.393     www      4534:         my $cwosec=$url;
1.807   ! albertel 4535:         $cwosec=~s/^\/($match_domain)\/($match_username)\/.*/$1\/$2/;
1.393     www      4536: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4537:            &logthis('Refused custom assignrole: '.
                   4538:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4539: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4540:            return 'refused'; 
                   4541:         }
1.21      www      4542:         $mrole='cr';
1.678     raeburn  4543:     } elsif ($role =~ /^gr\//) {
                   4544:         my $cwogrp=$url;
1.807   ! albertel 4545:         $cwogrp=~s{^/($match_domain)/($match_username)/.*}
        !          4546:                   {$1/$2}x;
1.678     raeburn  4547:         unless (&allowed('mdg',$cwogrp)) {
                   4548:             &logthis('Refused group assignrole: '.
                   4549:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4550:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4551:             return 'refused';
                   4552:         }
                   4553:         $mrole='gr';
1.21      www      4554:     } else {
1.82      www      4555:         my $cwosec=$url;
1.807   ! albertel 4556:         $cwosec=~s/^\/($match_domain)\/($match_username)\/.*/$1\/$2/;
1.373     www      4557:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4558:            &logthis('Refused assignrole: '.
                   4559:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4560: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4561:            return 'refused'; 
                   4562:         }
1.21      www      4563:         $mrole=$role;
                   4564:     }
1.620     albertel 4565:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4566:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4567:     if ($end) { $command.='_'.$end; }
1.21      www      4568:     if ($start) {
                   4569: 	if ($end) { 
1.81      www      4570:            $command.='_'.$start; 
1.21      www      4571:         } else {
1.81      www      4572:            $command.='_0_'.$start;
1.21      www      4573:         }
                   4574:     }
1.739     raeburn  4575:     my $origstart = $start;
                   4576:     my $origend = $end;
1.357     www      4577: # actually delete
                   4578:     if ($deleteflag) {
1.373     www      4579: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4580: # modify command to delete the role
1.620     albertel 4581:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4582:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4583: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4584: # set start and finish to negative values for userrolelog
                   4585:            $start=-1;
                   4586:            $end=-1;
                   4587:         }
                   4588:     }
                   4589: # send command
1.349     www      4590:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4591: # log new user role if status is ok
1.349     www      4592:     if ($answer eq 'ok') {
1.663     raeburn  4593: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4594: # for course roles, perform group memberships changes triggered by role change.
                   4595:         unless ($role =~ /^gr/) {
                   4596:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4597:                                              $origstart);
                   4598:         }
1.349     www      4599:     }
                   4600:     return $answer;
1.169     harris41 4601: }
                   4602: 
                   4603: # -------------------------------------------------- Modify user authentication
1.197     www      4604: # Overrides without validation
                   4605: 
1.169     harris41 4606: sub modifyuserauth {
                   4607:     my ($udom,$uname,$umode,$upass)=@_;
                   4608:     my $uhome=&homeserver($uname,$udom);
1.197     www      4609:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4610:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4611:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4612:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4613:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4614: 		     &escape($upass),$uhome);
1.620     albertel 4615:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4616:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4617:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4618:     &log($udom,,$uname,$uhome,
1.620     albertel 4619:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4620:                                      $env{'user.name'}.', '.$umode.
1.197     www      4621:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4622:     unless ($reply eq 'ok') {
1.197     www      4623:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4624: 	return 'error: '.$reply;
                   4625:     }   
1.170     harris41 4626:     return 'ok';
1.80      www      4627: }
                   4628: 
1.81      www      4629: # --------------------------------------------------------------- Modify a user
1.80      www      4630: 
1.81      www      4631: sub modifyuser {
1.206     matthew  4632:     my ($udom,    $uname, $uid,
                   4633:         $umode,   $upass, $first,
                   4634:         $middle,  $last,  $gene,
1.387     www      4635:         $forceid, $desiredhome, $email)=@_;
1.807   ! albertel 4636:     $udom= &LONCAPA::clean_domain($udom);
        !          4637:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4638:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4639:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4640: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4641:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4642:                                      ' desiredhome not specified'). 
1.620     albertel 4643:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4644:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4645:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4646: # ----------------------------------------------------------------- Create User
1.406     albertel 4647:     if (($uhome eq 'no_host') && 
                   4648: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4649:         my $unhome='';
1.209     matthew  4650:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4651:             $unhome = $desiredhome;
1.620     albertel 4652: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4653: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4654:         } else { # load balancing routine for determining $unhome
1.80      www      4655:             my $tryserver;
1.81      www      4656:             my $loadm=10000000;
1.80      www      4657:             foreach $tryserver (keys %libserv) {
                   4658: 	       if ($hostdom{$tryserver} eq $udom) {
                   4659:                   my $answer=reply('load',$tryserver);
                   4660:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4661: 		      $loadm=$answer;
                   4662:                       $unhome=$tryserver;
                   4663:                   }
                   4664: 	       }
                   4665: 	    }
                   4666:         }
                   4667:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4668: 	    return 'error: unable to find a home server for '.$uname.
                   4669:                    ' in domain '.$udom;
1.80      www      4670:         }
                   4671:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4672:                          &escape($upass),$unhome);
                   4673: 	unless ($reply eq 'ok') {
                   4674:             return 'error: '.$reply;
                   4675:         }   
1.230     stredwic 4676:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4677:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4678: 	    return 'error: unable verify users home machine.';
1.80      www      4679:         }
1.209     matthew  4680:     }   # End of creation of new user
1.80      www      4681: # ---------------------------------------------------------------------- Add ID
                   4682:     if ($uid) {
                   4683:        $uid=~tr/A-Z/a-z/;
                   4684:        my %uidhash=&idrget($udom,$uname);
1.196     www      4685:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4686:          && (!$forceid)) {
1.80      www      4687: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4688: 	      return 'error: user id "'.$uid.'" does not match '.
                   4689:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4690:           }
                   4691:        } else {
                   4692: 	  &idput($udom,($uname => $uid));
                   4693:        }
                   4694:     }
                   4695: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4696:     my @tmp=&get('environment',
1.134     albertel 4697: 		   ['firstname','middlename','lastname','generation'],
                   4698: 		   $udom,$uname);
1.313     matthew  4699:     my %names;
                   4700:     if ($tmp[0] =~ m/^error:.*/) { 
                   4701:         %names=(); 
                   4702:     } else {
                   4703:         %names = @tmp;
                   4704:     }
1.388     www      4705: #
                   4706: # Make sure to not trash student environment if instructor does not bother
                   4707: # to supply name and email information
                   4708: #
                   4709:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4710:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4711:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4712:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4713:     if ($email) {
                   4714:        $email=~s/[^\w\@\.\-\,]//gs;
                   4715:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4716: 			   $names{'critnotification'} = $email;
                   4717: 			   $names{'permanentemail'} = $email; }
                   4718:     }
1.134     albertel 4719:     my $reply = &put('environment', \%names, $udom,$uname);
                   4720:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4721:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4722:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4723:              $umode.', '.$first.', '.$middle.', '.
                   4724: 	     $last.', '.$gene.' by '.
1.620     albertel 4725:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4726:     return 'ok';
1.80      www      4727: }
                   4728: 
1.81      www      4729: # -------------------------------------------------------------- Modify student
1.80      www      4730: 
1.81      www      4731: sub modifystudent {
                   4732:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4733:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4734:     if (!$cid) {
1.620     albertel 4735: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4736: 	    return 'not_in_class';
                   4737: 	}
1.80      www      4738:     }
                   4739: # --------------------------------------------------------------- Make the user
1.81      www      4740:     my $reply=&modifyuser
1.209     matthew  4741: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4742:          $desiredhome,$email);
1.80      www      4743:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4744:     # This will cause &modify_student_enrollment to get the uid from the
                   4745:     # students environment
                   4746:     $uid = undef if (!$forceid);
1.455     albertel 4747:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4748: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4749:     return $reply;
                   4750: }
                   4751: 
                   4752: sub modify_student_enrollment {
1.515     raeburn  4753:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4754:     my ($cdom,$cnum,$chome);
                   4755:     if (!$cid) {
1.620     albertel 4756: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4757: 	    return 'not_in_class';
                   4758: 	}
1.620     albertel 4759: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4760: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4761:     } else {
                   4762: 	($cdom,$cnum)=split(/_/,$cid);
                   4763:     }
1.620     albertel 4764:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4765:     if (!$chome) {
1.457     raeburn  4766: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4767:     }
1.455     albertel 4768:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4769:     # Make sure the user exists
1.81      www      4770:     my $uhome=&homeserver($uname,$udom);
                   4771:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4772: 	return 'error: no such user';
                   4773:     }
1.297     matthew  4774:     # Get student data if we were not given enough information
                   4775:     if (!defined($first)  || $first  eq '' || 
                   4776:         !defined($last)   || $last   eq '' || 
                   4777:         !defined($uid)    || $uid    eq '' || 
                   4778:         !defined($middle) || $middle eq '' || 
                   4779:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4780:         # They did not supply us with enough data to enroll the student, so
                   4781:         # we need to pick up more information.
1.297     matthew  4782:         my %tmp = &get('environment',
1.294     matthew  4783:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4784:                        ,$udom,$uname);
                   4785: 
1.800     albertel 4786:         #foreach my $key (keys(%tmp)) {
                   4787:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4788:         #}
1.294     matthew  4789:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4790:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4791:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4792:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4793:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4794:     }
1.556     albertel 4795:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4796:     my $reply=cput('classlist',
                   4797: 		   {"$uname:$udom" => 
1.515     raeburn  4798: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4799: 		   $cdom,$cnum);
1.81      www      4800:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4801: 	return 'error: '.$reply;
1.652     albertel 4802:     } else {
                   4803: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4804:     }
1.297     matthew  4805:     # Add student role to user
1.83      www      4806:     my $uurl='/'.$cid;
1.81      www      4807:     $uurl=~s/\_/\//g;
                   4808:     if ($usec) {
                   4809: 	$uurl.='/'.$usec;
                   4810:     }
                   4811:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4812: }
                   4813: 
1.556     albertel 4814: sub format_name {
                   4815:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4816:     my $name;
                   4817:     if ($first ne 'lastname') {
                   4818: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4819:     } else {
                   4820: 	if ($lastname=~/\S/) {
                   4821: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4822: 	    $name=~s/\s+,/,/;
                   4823: 	} else {
                   4824: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4825: 	}
                   4826:     }
                   4827:     $name=~s/^\s+//;
                   4828:     $name=~s/\s+$//;
                   4829:     $name=~s/\s+/ /g;
                   4830:     return $name;
                   4831: }
                   4832: 
1.84      www      4833: # ------------------------------------------------- Write to course preferences
                   4834: 
                   4835: sub writecoursepref {
                   4836:     my ($courseid,%prefs)=@_;
                   4837:     $courseid=~s/^\///;
                   4838:     $courseid=~s/\_/\//g;
                   4839:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4840:     my $chome=homeserver($cnum,$cdomain);
                   4841:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4842: 	return 'error: no such course';
                   4843:     }
                   4844:     my $cstring='';
1.800     albertel 4845:     foreach my $pref (keys(%prefs)) {
                   4846: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4847:     }
1.84      www      4848:     $cstring=~s/\&$//;
                   4849:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4850: }
                   4851: 
                   4852: # ---------------------------------------------------------- Make/modify course
                   4853: 
                   4854: sub createcourse {
1.741     raeburn  4855:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4856:         $course_owner,$crstype)=@_;
1.84      www      4857:     $url=&declutter($url);
                   4858:     my $cid='';
1.264     matthew  4859:     unless (&allowed('ccc',$udom)) {
1.84      www      4860:         return 'refused';
                   4861:     }
                   4862: # ------------------------------------------------------------------- Create ID
1.674     www      4863:    my $uname=int(1+rand(9)).
                   4864:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4865:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4866:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4867: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4868:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4869:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4870:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4871:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4872:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4873:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4874:            return 'error: unable to generate unique course-ID';
                   4875:        } 
                   4876:    }
1.264     matthew  4877: # ------------------------------------------------ Check supplied server name
1.620     albertel 4878:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4879:     if (! exists($libserv{$course_server})) {
                   4880:         return 'error:bad server name '.$course_server;
                   4881:     }
1.84      www      4882: # ------------------------------------------------------------- Make the course
                   4883:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4884:                       $course_server);
1.84      www      4885:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4886:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4887:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4888: 	return 'error: no such course';
                   4889:     }
1.271     www      4890: # ----------------------------------------------------------------- Course made
1.516     raeburn  4891: # log existence
                   4892:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4893:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4894:                   &escape($crstype),$uhome);
1.358     www      4895:     &flushcourselogs();
                   4896: # set toplevel url
1.271     www      4897:     my $topurl=$url;
                   4898:     unless ($nonstandard) {
                   4899: # ------------------------------------------ For standard courses, make top url
                   4900:         my $mapurl=&clutter($url);
1.278     www      4901:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4902:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4903: <map>
                   4904: <resource id="1" type="start"></resource>
                   4905: <resource id="2" src="$mapurl"></resource>
                   4906: <resource id="3" type="finish"></resource>
                   4907: <link index="1" from="1" to="2"></link>
                   4908: <link index="2" from="2" to="3"></link>
                   4909: </map>
                   4910: ENDINITMAP
                   4911:         $topurl=&declutter(
1.638     albertel 4912:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4913:                           );
                   4914:     }
                   4915: # ----------------------------------------------------------- Write preferences
1.84      www      4916:     &writecoursepref($udom.'_'.$uname,
                   4917:                      ('description' => $description,
1.271     www      4918:                       'url'         => $topurl));
1.84      www      4919:     return '/'.$udom.'/'.$uname;
                   4920: }
                   4921: 
1.21      www      4922: # ---------------------------------------------------------- Assign Custom Role
                   4923: 
                   4924: sub assigncustomrole {
1.357     www      4925:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4926:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4927:                        $end,$start,$deleteflag);
1.21      www      4928: }
                   4929: 
                   4930: # ----------------------------------------------------------------- Revoke Role
                   4931: 
                   4932: sub revokerole {
1.357     www      4933:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4934:     my $now=time;
1.357     www      4935:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4936: }
                   4937: 
                   4938: # ---------------------------------------------------------- Revoke Custom Role
                   4939: 
                   4940: sub revokecustomrole {
1.357     www      4941:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4942:     my $now=time;
1.357     www      4943:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4944:            $deleteflag);
1.17      www      4945: }
                   4946: 
1.533     banghart 4947: # ------------------------------------------------------------ Disk usage
1.535     albertel 4948: sub diskusage {
1.533     banghart 4949:     my ($udom,$uname,$directoryRoot)=@_;
                   4950:     $directoryRoot =~ s/\/$//;
1.535     albertel 4951:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4952:     return $listing;
1.512     banghart 4953: }
                   4954: 
1.566     banghart 4955: sub is_locked {
                   4956:     my ($file_name, $domain, $user) = @_;
                   4957:     my @check;
                   4958:     my $is_locked;
                   4959:     push @check, $file_name;
1.613     albertel 4960:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4961: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4962:     my ($tmp)=keys(%locked);
                   4963:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4964:     
1.566     banghart 4965:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4966:         $is_locked = 'false';
                   4967:         foreach my $entry (@{$locked{$file_name}}) {
                   4968:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4969:                $is_locked = 'true';
                   4970:                last;
1.745     raeburn  4971:            }
                   4972:        }
1.566     banghart 4973:     } else {
                   4974:         $is_locked = 'false';
                   4975:     }
                   4976: }
                   4977: 
1.759     albertel 4978: sub declutter_portfile {
                   4979:     my ($file) = @_;
                   4980:     &logthis("got $file");
                   4981:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4982:     &logthis("ret $file");
                   4983:     return $file;
                   4984: }
                   4985: 
1.559     banghart 4986: # ------------------------------------------------------------- Mark as Read Only
                   4987: 
                   4988: sub mark_as_readonly {
                   4989:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4990:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4991:     my ($tmp)=keys(%current_permissions);
                   4992:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4993:     foreach my $file (@{$files}) {
1.759     albertel 4994: 	$file = &declutter_portfile($file);
1.561     banghart 4995:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4996:     }
1.613     albertel 4997:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4998:     return;
                   4999: }
                   5000: 
1.572     banghart 5001: # ------------------------------------------------------------Save Selected Files
                   5002: 
                   5003: sub save_selected_files {
                   5004:     my ($user, $path, @files) = @_;
                   5005:     my $filename = $user."savedfiles";
1.573     banghart 5006:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5007:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5008:     foreach my $file (@files) {
1.620     albertel 5009:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5010:     }
                   5011:     foreach my $file (@other_files) {
1.574     banghart 5012:         print (OUT $file."\n");
1.572     banghart 5013:     }
1.574     banghart 5014:     close (OUT);
1.572     banghart 5015:     return 'ok';
                   5016: }
                   5017: 
1.574     banghart 5018: sub clear_selected_files {
                   5019:     my ($user) = @_;
                   5020:     my $filename = $user."savedfiles";
                   5021:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5022:     print (OUT undef);
                   5023:     close (OUT);
                   5024:     return ("ok");    
                   5025: }
                   5026: 
1.572     banghart 5027: sub files_in_path {
                   5028:     my ($user, $path) = @_;
                   5029:     my $filename = $user."savedfiles";
                   5030:     my %return_files;
1.574     banghart 5031:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5032:     while (my $line_in = <IN>) {
1.574     banghart 5033:         chomp ($line_in);
                   5034:         my @paths_and_file = split (m!/!, $line_in);
                   5035:         my $file_part = pop (@paths_and_file);
                   5036:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5037:         $path_part.='/';
                   5038:         my $path_and_file = $path_part.$file_part;
                   5039:         if ($path_part eq $path) {
                   5040:             $return_files{$file_part}= 'selected';
                   5041:         }
                   5042:     }
1.574     banghart 5043:     close (IN);
                   5044:     return (\%return_files);
1.572     banghart 5045: }
                   5046: 
                   5047: # called in portfolio select mode, to show files selected NOT in current directory
                   5048: sub files_not_in_path {
                   5049:     my ($user, $path) = @_;
                   5050:     my $filename = $user."savedfiles";
                   5051:     my @return_files;
                   5052:     my $path_part;
1.800     albertel 5053:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5054:     while (my $line = <IN>) {
1.572     banghart 5055:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5056:         my @paths_and_file = split(m|/|, $line);
                   5057:         my $file_part = pop(@paths_and_file);
                   5058:         chomp($file_part);
                   5059:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5060:         $path_part .= '/';
                   5061:         my $path_and_file = $path_part.$file_part;
                   5062:         if ($path_part ne $path) {
1.800     albertel 5063:             push(@return_files, ($path_and_file));
1.572     banghart 5064:         }
                   5065:     }
1.800     albertel 5066:     close(OUT);
1.574     banghart 5067:     return (@return_files);
1.572     banghart 5068: }
                   5069: 
1.745     raeburn  5070: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5071: 
1.745     raeburn  5072: sub get_portfile_permissions {
                   5073:     my ($domain,$user) = @_;
1.613     albertel 5074:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5075:     my ($tmp)=keys(%current_permissions);
                   5076:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5077:     return \%current_permissions;
                   5078: }
                   5079: 
                   5080: #---------------------------------------------Get portfolio file access controls
                   5081: 
1.749     raeburn  5082: sub get_access_controls {
1.745     raeburn  5083:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5084:     my %access;
                   5085:     my $real_file = $file;
                   5086:     $file =~ s/\.meta$//;
1.745     raeburn  5087:     if (defined($file)) {
1.749     raeburn  5088:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5089:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5090:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5091:             }
                   5092:         }
1.745     raeburn  5093:     } else {
1.749     raeburn  5094:         foreach my $key (keys(%{$current_permissions})) {
                   5095:             if ($key =~ /\0accesscontrol$/) {
                   5096:                 if (defined($group)) {
                   5097:                     if ($key !~ m-^\Q$group\E/-) {
                   5098:                         next;
                   5099:                     }
                   5100:                 }
                   5101:                 my ($fullpath) = split(/\0/,$key);
                   5102:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5103:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5104:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5105:                     }
                   5106:                 }
                   5107:             }
                   5108:         }
                   5109:     }
                   5110:     return %access;
                   5111: }
                   5112: 
                   5113: sub modify_access_controls {
                   5114:     my ($file_name,$changes,$domain,$user)=@_;
                   5115:     my ($outcome,$deloutcome);
                   5116:     my %store_permissions;
                   5117:     my %new_values;
                   5118:     my %new_control;
                   5119:     my %translation;
                   5120:     my @deletions = ();
                   5121:     my $now = time;
                   5122:     if (exists($$changes{'activate'})) {
                   5123:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5124:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5125:             my $numnew = scalar(@newitems);
                   5126:             for (my $i=0; $i<$numnew; $i++) {
                   5127:                 my $newkey = $newitems[$i];
                   5128:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5129:                 if ($newkey =~ /^\d+:/) { 
                   5130:                     $newkey =~ s/^(\d+)/$newid/;
                   5131:                     $translation{$1} = $newid;
                   5132:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5133:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5134:                     $translation{$1} = $newid;
                   5135:                 }
1.749     raeburn  5136:                 $new_values{$file_name."\0".$newkey} = 
                   5137:                                           $$changes{'activate'}{$newitems[$i]};
                   5138:                 $new_control{$newkey} = $now;
                   5139:             }
                   5140:         }
                   5141:     }
                   5142:     my %todelete;
                   5143:     my %changed_items;
                   5144:     foreach my $action ('delete','update') {
                   5145:         if (exists($$changes{$action})) {
                   5146:             if (ref($$changes{$action}) eq 'HASH') {
                   5147:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5148:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5149:                     if ($action eq 'delete') { 
                   5150:                         $todelete{$itemnum} = 1;
                   5151:                     } else {
                   5152:                         $changed_items{$itemnum} = $key;
                   5153:                     }
                   5154:                 }
1.745     raeburn  5155:             }
                   5156:         }
1.749     raeburn  5157:     }
                   5158:     # get lock on access controls for file.
                   5159:     my $lockhash = {
                   5160:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5161:                                                        ':'.$env{'user.domain'},
                   5162:                    }; 
                   5163:     my $tries = 0;
                   5164:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5165:    
                   5166:     while (($gotlock ne 'ok') && $tries <3) {
                   5167:         $tries ++;
                   5168:         sleep 1;
                   5169:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5170:     }
                   5171:     if ($gotlock eq 'ok') {
                   5172:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5173:         my ($tmp)=keys(%curr_permissions);
                   5174:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5175:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5176:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5177:             if (ref($curr_controls) eq 'HASH') {
                   5178:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5179:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5180:                     if (defined($todelete{$itemnum})) {
                   5181:                         push(@deletions,$file_name."\0".$control_item);
                   5182:                     } else {
                   5183:                         if (defined($changed_items{$itemnum})) {
                   5184:                             $new_control{$changed_items{$itemnum}} = $now;
                   5185:                             push(@deletions,$file_name."\0".$control_item);
                   5186:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5187:                         } else {
                   5188:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5189:                         }
                   5190:                     }
1.745     raeburn  5191:                 }
                   5192:             }
                   5193:         }
1.749     raeburn  5194:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5195:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5196:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5197:         #  remove lock
                   5198:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5199:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5200:     } else {
                   5201:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5202:     }
1.749     raeburn  5203:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5204: }
                   5205: 
                   5206: #------------------------------------------------------Get Marked as Read Only
                   5207: 
                   5208: sub get_marked_as_readonly {
                   5209:     my ($domain,$user,$what,$group) = @_;
                   5210:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5211:     my @readonly_files;
1.629     banghart 5212:     my $cmp1=$what;
                   5213:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5214:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5215:         if (defined($group)) {
                   5216:             if ($file_name !~ m-^\Q$group\E/-) {
                   5217:                 next;
                   5218:             }
                   5219:         }
1.561     banghart 5220:         if (ref($value) eq "ARRAY"){
                   5221:             foreach my $stored_what (@{$value}) {
1.629     banghart 5222:                 my $cmp2=$stored_what;
1.759     albertel 5223:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5224:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5225:                 }
1.629     banghart 5226:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5227:                     push(@readonly_files, $file_name);
1.745     raeburn  5228:                     last;
1.563     banghart 5229:                 } elsif (!defined($what)) {
                   5230:                     push(@readonly_files, $file_name);
1.745     raeburn  5231:                     last;
1.561     banghart 5232:                 }
                   5233:             }
1.745     raeburn  5234:         }
1.561     banghart 5235:     }
                   5236:     return @readonly_files;
                   5237: }
1.577     banghart 5238: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5239: 
1.577     banghart 5240: sub get_marked_as_readonly_hash {
1.745     raeburn  5241:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5242:     my %readonly_files;
1.745     raeburn  5243:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5244:         if (defined($group)) {
                   5245:             if ($file_name !~ m-^\Q$group\E/-) {
                   5246:                 next;
                   5247:             }
                   5248:         }
1.577     banghart 5249:         if (ref($value) eq "ARRAY"){
                   5250:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5251:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5252:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5253:                         if ($lock_descriptor eq 'graded') {
                   5254:                             $readonly_files{$file_name} = 'graded';
                   5255:                         } elsif ($lock_descriptor eq 'handback') {
                   5256:                             $readonly_files{$file_name} = 'handback';
                   5257:                         } else {
                   5258:                             if (!exists($readonly_files{$file_name})) {
                   5259:                                 $readonly_files{$file_name} = 'locked';
                   5260:                             }
                   5261:                         }
1.745     raeburn  5262:                     }
1.750     banghart 5263:                 } 
1.577     banghart 5264:             }
                   5265:         } 
                   5266:     }
                   5267:     return %readonly_files;
                   5268: }
1.559     banghart 5269: # ------------------------------------------------------------ Unmark as Read Only
                   5270: 
                   5271: sub unmark_as_readonly {
1.629     banghart 5272:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5273:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5274:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5275:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5276:     my $symb_crs = $what;
                   5277:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5278:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5279:     my ($tmp)=keys(%current_permissions);
                   5280:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5281:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5282:     foreach my $file (@readonly_files) {
1.759     albertel 5283: 	my $clean_file = &declutter_portfile($file);
                   5284: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5285: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5286:         my @new_locks;
                   5287:         my @del_keys;
                   5288:         if (ref($current_locks) eq "ARRAY"){
                   5289:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5290:                 my $compare=$locker;
1.749     raeburn  5291:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5292:                     $compare=join('',@{$locker});
1.746     raeburn  5293:                     if ($compare ne $symb_crs) {
                   5294:                         push(@new_locks, $locker);
                   5295:                     }
1.563     banghart 5296:                 }
                   5297:             }
1.650     albertel 5298:             if (scalar(@new_locks) > 0) {
1.563     banghart 5299:                 $current_permissions{$file} = \@new_locks;
                   5300:             } else {
                   5301:                 push(@del_keys, $file);
1.613     albertel 5302:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5303:                 delete($current_permissions{$file});
1.563     banghart 5304:             }
                   5305:         }
1.561     banghart 5306:     }
1.613     albertel 5307:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5308:     return;
                   5309: }
1.512     banghart 5310: 
1.17      www      5311: # ------------------------------------------------------------ Directory lister
                   5312: 
                   5313: sub dirlist {
1.253     stredwic 5314:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5315: 
1.18      www      5316:     $uri=~s/^\///;
                   5317:     $uri=~s/\/$//;
1.253     stredwic 5318:     my ($udom, $uname);
                   5319:     (undef,$udom,$uname)=split(/\//,$uri);
                   5320:     if(defined($userdomain)) {
                   5321:         $udom = $userdomain;
                   5322:     }
                   5323:     if(defined($username)) {
                   5324:         $uname = $username;
                   5325:     }
                   5326: 
                   5327:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5328:     if(defined($alternateDirectoryRoot)) {
                   5329:         $dirRoot = $alternateDirectoryRoot;
                   5330:         $dirRoot =~ s/\/$//;
1.751     banghart 5331:     }
1.253     stredwic 5332: 
                   5333:     if($udom) {
                   5334:         if($uname) {
1.800     albertel 5335:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5336: 				 &homeserver($uname,$udom));
1.605     matthew  5337:             my @listing_results;
                   5338:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5339:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5340: 				  &homeserver($uname,$udom));
1.605     matthew  5341:                 @listing_results = split(/:/,$listing);
                   5342:             } else {
                   5343:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5344:             }
                   5345:             return @listing_results;
1.253     stredwic 5346:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5347:             my %allusers;
                   5348:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5349:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5350:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5351: 					 $udom, $tryserver);
1.605     matthew  5352:                     my @listing_results;
                   5353:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5354:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5355: 					  $udom, $tryserver);
1.605     matthew  5356:                         @listing_results = split(/:/,$listing);
                   5357:                     } else {
                   5358:                         @listing_results =
                   5359:                             map { &unescape($_); } split(/:/,$listing);
                   5360:                     }
                   5361:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5362:                         $listing_results[0] ne 'empty'       &&
                   5363:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5364:                         foreach my $line (@listing_results) {
                   5365:                             my ($entry) = split(/&/,$line,2);
                   5366:                             $allusers{$entry} = 1;
1.253     stredwic 5367:                         }
                   5368:                     }
1.191     harris41 5369:                 }
1.253     stredwic 5370:             }
                   5371:             my $alluserstr='';
1.800     albertel 5372:             foreach my $user (sort(keys(%allusers))) {
                   5373:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5374:             }
                   5375:             $alluserstr=~s/:$//;
                   5376:             return split(/:/,$alluserstr);
                   5377:         } else {
1.800     albertel 5378:             return ('missing user name');
1.253     stredwic 5379:         }
                   5380:     } elsif(!defined($alternateDirectoryRoot)) {
                   5381:         my $tryserver;
                   5382:         my %alldom=();
1.800     albertel 5383:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5384:             $alldom{$hostdom{$tryserver}}=1;
                   5385:         }
                   5386:         my $alldomstr='';
1.800     albertel 5387:         foreach my $domain (sort(keys(%alldom))) {
                   5388:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5389:         }
                   5390:         $alldomstr=~s/:$//;
                   5391:         return split(/:/,$alldomstr);       
                   5392:     } else {
1.800     albertel 5393:         return ('missing domain');
1.275     stredwic 5394:     }
                   5395: }
                   5396: 
                   5397: # --------------------------------------------- GetFileTimestamp
                   5398: # This function utilizes dirlist and returns the date stamp for
                   5399: # when it was last modified.  It will also return an error of -1
                   5400: # if an error occurs
                   5401: 
1.410     matthew  5402: ##
                   5403: ## FIXME: This subroutine assumes its caller knows something about the
                   5404: ## directory structure of the home server for the student ($root).
                   5405: ## Not a good assumption to make.  Since this is for looking up files
                   5406: ## in user directories, the full path should be constructed by lond, not
                   5407: ## whatever machine we request data from.
                   5408: ##
1.275     stredwic 5409: sub GetFileTimestamp {
                   5410:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807   ! albertel 5411:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
        !          5412:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5413:     my $subdir=$studentName.'__';
                   5414:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5415:     my $proname="$studentDomain/$subdir/$studentName";
                   5416:     $proname .= '/'.$filename;
1.375     matthew  5417:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5418:                                               $studentName, $root);
1.275     stredwic 5419:     my @stats = split('&', $fileStat);
                   5420:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5421:         # @stats contains first the filename, then the stat output
                   5422:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5423:     } else {
                   5424:         return -1;
1.253     stredwic 5425:     }
1.26      www      5426: }
                   5427: 
1.712     albertel 5428: sub stat_file {
                   5429:     my ($uri) = @_;
1.787     albertel 5430:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5431: 
1.712     albertel 5432:     my ($udom,$uname,$file,$dir);
                   5433:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5434: 	($udom,$uname,$file) =
1.807   ! albertel 5435: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_username)/?(.*)-);
1.712     albertel 5436: 	$file = 'userfiles/'.$file;
1.740     www      5437: 	$dir = &propath($udom,$uname);
1.712     albertel 5438:     }
                   5439:     if ($uri =~ m-^/res/-) {
                   5440: 	($udom,$uname) = 
1.807   ! albertel 5441: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5442: 	$file = $uri;
                   5443:     }
                   5444: 
                   5445:     if (!$udom || !$uname || !$file) {
                   5446: 	# unable to handle the uri
                   5447: 	return ();
                   5448:     }
                   5449: 
                   5450:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5451:     my @stats = split('&', $result);
1.721     banghart 5452:     
1.712     albertel 5453:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5454: 	shift(@stats); #filename is first
                   5455: 	return @stats;
                   5456:     }
                   5457:     return ();
                   5458: }
                   5459: 
1.26      www      5460: # -------------------------------------------------------- Value of a Condition
                   5461: 
1.713     albertel 5462: # gets the value of a specific preevaluated condition
                   5463: #    stored in the string  $env{user.state.<cid>}
                   5464: # or looks up a condition reference in the bighash and if if hasn't
                   5465: # already been evaluated recurses into docondval to get the value of
                   5466: # the condition, then memoizing it to 
                   5467: #   $env{user.state.<cid>.<condition>}
1.40      www      5468: sub directcondval {
                   5469:     my $number=shift;
1.620     albertel 5470:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5471: 	&Apache::lonuserstate::evalstate();
                   5472:     }
1.713     albertel 5473:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5474: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5475:     } elsif ($number =~ /^_/) {
                   5476: 	my $sub_condition;
                   5477: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5478: 		&GDBM_READER(),0640)) {
                   5479: 	    $sub_condition=$bighash{'conditions'.$number};
                   5480: 	    untie(%bighash);
                   5481: 	}
                   5482: 	my $value = &docondval($sub_condition);
                   5483: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5484: 	return $value;
                   5485:     }
1.620     albertel 5486:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5487:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5488:     } else {
                   5489:        return 2;
                   5490:     }
                   5491: }
                   5492: 
1.713     albertel 5493: # get the collection of conditions for this resource
1.26      www      5494: sub condval {
                   5495:     my $condidx=shift;
1.54      www      5496:     my $allpathcond='';
1.713     albertel 5497:     foreach my $cond (split(/\|/,$condidx)) {
                   5498: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5499: 	    $allpathcond.=
                   5500: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5501: 	}
1.191     harris41 5502:     }
1.54      www      5503:     $allpathcond=~s/\|$//;
1.713     albertel 5504:     return &docondval($allpathcond);
                   5505: }
                   5506: 
                   5507: #evaluates an expression of conditions
                   5508: sub docondval {
                   5509:     my ($allpathcond) = @_;
                   5510:     my $result=0;
                   5511:     if ($env{'request.course.id'}
                   5512: 	&& defined($allpathcond)) {
                   5513: 	my $operand='|';
                   5514: 	my @stack;
                   5515: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5516: 	    if ($chunk eq '(') {
                   5517: 		push @stack,($operand,$result);
                   5518: 	    } elsif ($chunk eq ')') {
                   5519: 		my $before=pop @stack;
                   5520: 		if (pop @stack eq '&') {
                   5521: 		    $result=$result>$before?$before:$result;
                   5522: 		} else {
                   5523: 		    $result=$result>$before?$result:$before;
                   5524: 		}
                   5525: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5526: 		$operand=$chunk;
                   5527: 	    } else {
                   5528: 		my $new=directcondval($chunk);
                   5529: 		if ($operand eq '&') {
                   5530: 		    $result=$result>$new?$new:$result;
                   5531: 		} else {
                   5532: 		    $result=$result>$new?$result:$new;
                   5533: 		}
                   5534: 	    }
                   5535: 	}
1.26      www      5536:     }
                   5537:     return $result;
1.421     albertel 5538: }
                   5539: 
                   5540: # ---------------------------------------------------- Devalidate courseresdata
                   5541: 
                   5542: sub devalidatecourseresdata {
                   5543:     my ($coursenum,$coursedomain)=@_;
                   5544:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5545:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5546: }
                   5547: 
1.763     www      5548: 
1.200     www      5549: # --------------------------------------------------- Course Resourcedata Query
                   5550: 
1.624     albertel 5551: sub get_courseresdata {
                   5552:     my ($coursenum,$coursedomain)=@_;
1.200     www      5553:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5554:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5555:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5556:     my %dumpreply;
1.417     albertel 5557:     unless (defined($cached)) {
1.624     albertel 5558: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5559: 	$result=\%dumpreply;
1.251     albertel 5560: 	my ($tmp) = keys(%dumpreply);
                   5561: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5562: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5563: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5564: 	    return $tmp;
1.416     albertel 5565: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5566: 	    $result=undef;
1.599     albertel 5567: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5568: 	}
                   5569:     }
1.624     albertel 5570:     return $result;
                   5571: }
                   5572: 
1.633     albertel 5573: sub devalidateuserresdata {
                   5574:     my ($uname,$udom)=@_;
                   5575:     my $hashid="$udom:$uname";
                   5576:     &devalidate_cache_new('userres',$hashid);
                   5577: }
                   5578: 
1.624     albertel 5579: sub get_userresdata {
                   5580:     my ($uname,$udom)=@_;
                   5581:     #most student don\'t have any data set, check if there is some data
                   5582:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5583: 
                   5584:     my $hashid="$udom:$uname";
                   5585:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5586:     if (!defined($cached)) {
                   5587: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5588: 	$result=\%resourcedata;
                   5589: 	&do_cache_new('userres',$hashid,$result,600);
                   5590:     }
                   5591:     my ($tmp)=keys(%$result);
                   5592:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5593: 	return $result;
                   5594:     }
                   5595:     #error 2 occurs when the .db doesn't exist
                   5596:     if ($tmp!~/error: 2 /) {
1.672     albertel 5597: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5598: 		 " Trying to get resource data for ".
                   5599: 		 $uname." at ".$udom.": ".
                   5600: 		 $tmp."</font>");
                   5601:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5602: 	#&EXT_cache_set($udom,$uname);
                   5603: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5604: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5605:     }
                   5606:     return $tmp;
                   5607: }
                   5608: 
                   5609: sub resdata {
                   5610:     my ($name,$domain,$type,@which)=@_;
                   5611:     my $result;
                   5612:     if ($type eq 'course') {
                   5613: 	$result=&get_courseresdata($name,$domain);
                   5614:     } elsif ($type eq 'user') {
                   5615: 	$result=&get_userresdata($name,$domain);
                   5616:     }
                   5617:     if (!ref($result)) { return $result; }    
1.251     albertel 5618:     foreach my $item (@which) {
1.417     albertel 5619: 	if (defined($result->{$item})) {
                   5620: 	    return $result->{$item};
1.251     albertel 5621: 	}
1.250     albertel 5622:     }
1.291     albertel 5623:     return undef;
1.200     www      5624: }
                   5625: 
1.379     matthew  5626: #
                   5627: # EXT resource caching routines
                   5628: #
                   5629: 
                   5630: sub clear_EXT_cache_status {
1.383     albertel 5631:     &delenv('cache.EXT.');
1.379     matthew  5632: }
                   5633: 
                   5634: sub EXT_cache_status {
                   5635:     my ($target_domain,$target_user) = @_;
1.383     albertel 5636:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5637:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5638:         # We know already the user has no data
                   5639:         return 1;
                   5640:     } else {
                   5641:         return 0;
                   5642:     }
                   5643: }
                   5644: 
                   5645: sub EXT_cache_set {
                   5646:     my ($target_domain,$target_user) = @_;
1.383     albertel 5647:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5648:     #&appenv($cachename => time);
1.379     matthew  5649: }
                   5650: 
1.28      www      5651: # --------------------------------------------------------- Value of a Variable
1.58      www      5652: sub EXT {
1.715     albertel 5653: 
1.395     albertel 5654:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5655:     unless ($varname) { return ''; }
1.218     albertel 5656:     #get real user name/domain, courseid and symb
                   5657:     my $courseid;
1.359     albertel 5658:     my $publicuser;
1.427     www      5659:     if ($symbparm) {
                   5660: 	$symbparm=&get_symb_from_alias($symbparm);
                   5661:     }
1.218     albertel 5662:     if (!($uname && $udom)) {
1.790     albertel 5663:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5664:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5665:     } else {
1.620     albertel 5666: 	$courseid=$env{'request.course.id'};
1.218     albertel 5667:     }
1.48      www      5668:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5669:     my $rest;
1.320     albertel 5670:     if (defined($therest[0])) {
1.48      www      5671:        $rest=join('.',@therest);
                   5672:     } else {
                   5673:        $rest='';
                   5674:     }
1.320     albertel 5675: 
1.57      www      5676:     my $qualifierrest=$qualifier;
                   5677:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5678:     my $spacequalifierrest=$space;
                   5679:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5680:     if ($realm eq 'user') {
1.48      www      5681: # --------------------------------------------------------------- user.resource
                   5682: 	if ($space eq 'resource') {
1.651     albertel 5683: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5684: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5685: 		 &&
1.744     albertel 5686: 		 ($symbparm eq &symbread()) ) {	
                   5687: 		# if we are in the middle of processing the resource the
                   5688: 		# get the value we are planning on committing
                   5689:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5690:                     return $Apache::lonhomework::results{$qualifierrest};
                   5691:                 } else {
                   5692:                     return $Apache::lonhomework::history{$qualifierrest};
                   5693:                 }
1.335     albertel 5694: 	    } else {
1.359     albertel 5695: 		my %restored;
1.620     albertel 5696: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5697: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5698: 		} else {
                   5699: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5700: 		}
1.335     albertel 5701: 		return $restored{$qualifierrest};
                   5702: 	    }
1.48      www      5703: # ----------------------------------------------------------------- user.access
                   5704:         } elsif ($space eq 'access') {
1.218     albertel 5705: 	    # FIXME - not supporting calls for a specific user
1.48      www      5706:             return &allowed($qualifier,$rest);
                   5707: # ------------------------------------------ user.preferences, user.environment
                   5708:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5709: 	    if (($uname eq $env{'user.name'}) &&
                   5710: 		($udom eq $env{'user.domain'})) {
                   5711: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5712: 	    } else {
1.359     albertel 5713: 		my %returnhash;
                   5714: 		if (!$publicuser) {
                   5715: 		    %returnhash=&userenvironment($udom,$uname,
                   5716: 						 $qualifierrest);
                   5717: 		}
1.218     albertel 5718: 		return $returnhash{$qualifierrest};
                   5719: 	    }
1.48      www      5720: # ----------------------------------------------------------------- user.course
                   5721:         } elsif ($space eq 'course') {
1.218     albertel 5722: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5723:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5724: # ------------------------------------------------------------------- user.role
                   5725:         } elsif ($space eq 'role') {
1.218     albertel 5726: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5727:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5728:             if ($qualifier eq 'value') {
                   5729: 		return $role;
                   5730:             } elsif ($qualifier eq 'extent') {
                   5731:                 return $where;
                   5732:             }
                   5733: # ----------------------------------------------------------------- user.domain
                   5734:         } elsif ($space eq 'domain') {
1.218     albertel 5735:             return $udom;
1.48      www      5736: # ------------------------------------------------------------------- user.name
                   5737:         } elsif ($space eq 'name') {
1.218     albertel 5738:             return $uname;
1.48      www      5739: # ---------------------------------------------------- Any other user namespace
1.29      www      5740:         } else {
1.359     albertel 5741: 	    my %reply;
                   5742: 	    if (!$publicuser) {
                   5743: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5744: 	    }
                   5745: 	    return $reply{$qualifierrest};
1.48      www      5746:         }
1.236     www      5747:     } elsif ($realm eq 'query') {
                   5748: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5749:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5750: 						[$spacequalifierrest]);
1.620     albertel 5751: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5752:    } elsif ($realm eq 'request') {
1.48      www      5753: # ------------------------------------------------------------- request.browser
                   5754:         if ($space eq 'browser') {
1.430     www      5755: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5756: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5757: 		    return 1;
                   5758: 		} else {
                   5759: 		    return 0;
                   5760: 		}
                   5761: 	    } else {
1.620     albertel 5762: 		return $env{'browser.'.$qualifier};
1.430     www      5763: 	    }
1.57      www      5764: # ------------------------------------------------------------ request.filename
                   5765:         } else {
1.620     albertel 5766:             return $env{'request.'.$spacequalifierrest};
1.29      www      5767:         }
1.28      www      5768:     } elsif ($realm eq 'course') {
1.48      www      5769: # ---------------------------------------------------------- course.description
1.620     albertel 5770:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5771:     } elsif ($realm eq 'resource') {
1.165     www      5772: 
1.620     albertel 5773: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5774: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5775: 	}
1.693     albertel 5776: 
                   5777: 	if ($space eq 'title') {
                   5778: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5779: 	    return &gettitle($symbparm);
                   5780: 	}
                   5781: 	
                   5782: 	if ($space eq 'map') {
                   5783: 	    my ($map) = &decode_symb($symbparm);
                   5784: 	    return &symbread($map);
                   5785: 	}
                   5786: 
                   5787: 	my ($section, $group, @groups);
1.593     albertel 5788: 	my ($courselevelm,$courselevel);
1.539     albertel 5789: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5790: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5791: 
1.218     albertel 5792: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5793: 
1.60      www      5794: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5795: 	    my $symbp=$symbparm;
1.735     albertel 5796: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5797: 
                   5798: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5799: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5800: 
1.620     albertel 5801: 	    if (($env{'user.name'} eq $uname) &&
                   5802: 		($env{'user.domain'} eq $udom)) {
                   5803: 		$section=$env{'request.course.sec'};
1.733     raeburn  5804:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5805:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5806: 	    } else {
1.539     albertel 5807: 		if (! defined($usection)) {
1.551     albertel 5808: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5809: 		} else {
                   5810: 		    $section = $usection;
                   5811: 		}
1.733     raeburn  5812:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5813: 	    }
                   5814: 
                   5815: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5816: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5817: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5818: 
1.593     albertel 5819: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5820: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5821: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5822: 
1.60      www      5823: # ----------------------------------------------------------- first, check user
1.624     albertel 5824: 
                   5825: 	    my $userreply=&resdata($uname,$udom,'user',
                   5826: 				       ($courselevelr,$courselevelm,
                   5827: 					$courselevel));
                   5828: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5829: 
1.594     albertel 5830: # ------------------------------------------------ second, check some of course
1.684     raeburn  5831:             my $coursereply;
1.691     raeburn  5832:             if (@groups > 0) {
                   5833:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5834:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5835:                 if (defined($coursereply)) { return $coursereply; }
                   5836:             }
1.96      www      5837: 
1.684     raeburn  5838: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5839: 				     $env{'course.'.$courseid.'.domain'},
                   5840: 				     'course',
                   5841: 				     ($seclevelr,$seclevelm,$seclevel,
                   5842: 				      $courselevelr));
1.287     albertel 5843: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5844: 
1.60      www      5845: # ------------------------------------------------------ third, check map parms
1.218     albertel 5846: 	    my %parmhash=();
                   5847: 	    my $thisparm='';
                   5848: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5849: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5850: 		    &GDBM_READER(),0640)) {
1.218     albertel 5851: 		$thisparm=$parmhash{$symbparm};
                   5852: 		untie(%parmhash);
                   5853: 	    }
                   5854: 	    if ($thisparm) { return $thisparm; }
                   5855: 	}
1.594     albertel 5856: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5857: 
1.218     albertel 5858: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5859: 	my $filename;
                   5860: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5861: 	if ($symbparm) {
1.409     www      5862: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5863: 	} else {
1.620     albertel 5864: 	    $filename=$env{'request.filename'};
1.282     albertel 5865: 	}
                   5866: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5867: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5868: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5869: 	if (defined($metadata)) { return $metadata; }
1.142     www      5870: 
1.594     albertel 5871: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5872: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5873: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5874: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5875: 				     $env{'course.'.$courseid.'.domain'},
                   5876: 				     'course',
                   5877: 				     ($courselevelm,$courselevel));
1.593     albertel 5878: 	    if (defined($coursereply)) { return $coursereply; }
                   5879: 	}
1.145     www      5880: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5881: 	unless ($space eq '0') {
1.336     albertel 5882: 	    my @parts=split(/_/,$space);
                   5883: 	    my $id=pop(@parts);
                   5884: 	    my $part=join('_',@parts);
                   5885: 	    if ($part eq '') { $part='0'; }
                   5886: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5887: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5888: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5889: 	}
1.395     albertel 5890: 	if ($recurse) { return undef; }
                   5891: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5892: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5893: 
1.48      www      5894: # ---------------------------------------------------- Any other user namespace
                   5895:     } elsif ($realm eq 'environment') {
                   5896: # ----------------------------------------------------------------- environment
1.620     albertel 5897: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5898: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5899: 	} else {
1.770     albertel 5900: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5901: 		return '';
                   5902: 	    }
1.219     albertel 5903: 	    my %returnhash=&userenvironment($udom,$uname,
                   5904: 					    $spacequalifierrest);
                   5905: 	    return $returnhash{$spacequalifierrest};
                   5906: 	}
1.28      www      5907:     } elsif ($realm eq 'system') {
1.48      www      5908: # ----------------------------------------------------------------- system.time
                   5909: 	if ($space eq 'time') {
                   5910: 	    return time;
                   5911:         }
1.696     albertel 5912:     } elsif ($realm eq 'server') {
                   5913: # ----------------------------------------------------------------- system.time
                   5914: 	if ($space eq 'name') {
                   5915: 	    return $ENV{'SERVER_NAME'};
                   5916:         }
1.28      www      5917:     }
1.48      www      5918:     return '';
1.61      www      5919: }
                   5920: 
1.691     raeburn  5921: sub check_group_parms {
                   5922:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5923:     my @groupitems = ();
                   5924:     my $resultitem;
                   5925:     my @levels = ($symbparm,$mapparm,$what);
                   5926:     foreach my $group (@{$groups}) {
                   5927:         foreach my $level (@levels) {
                   5928:              my $item = $courseid.'.['.$group.'].'.$level;
                   5929:              push(@groupitems,$item);
                   5930:         }
                   5931:     }
                   5932:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5933:                             $env{'course.'.$courseid.'.domain'},
                   5934:                                      'course',@groupitems);
                   5935:     return $coursereply;
                   5936: }
                   5937: 
                   5938: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5939:     my ($courseid,@groups) = @_;
                   5940:     @groups = sort(@groups);
1.691     raeburn  5941:     return @groups;
                   5942: }
                   5943: 
1.395     albertel 5944: sub packages_tab_default {
                   5945:     my ($uri,$varname)=@_;
                   5946:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5947: 
                   5948:     my (@extension,@specifics,$do_default);
                   5949:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5950: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5951: 	if ($pack_type eq 'default') {
                   5952: 	    $do_default=1;
                   5953: 	} elsif ($pack_type eq 'extension') {
                   5954: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5955: 	} else {
                   5956: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5957: 	}
                   5958:     }
                   5959:     # first look for a package that matches the requested part id
                   5960:     foreach my $package (@specifics) {
                   5961: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5962: 	next if ($pack_part ne $part);
                   5963: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5964: 	    return $packagetab{"$pack_type&$name&default"};
                   5965: 	}
                   5966:     }
                   5967:     # look for any possible matching non extension_ package
                   5968:     foreach my $package (@specifics) {
                   5969: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5970: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5971: 	    return $packagetab{"$pack_type&$name&default"};
                   5972: 	}
1.585     albertel 5973: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5974: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5975: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5976: 	}
                   5977:     }
1.738     albertel 5978:     # look for any posible extension_ match
                   5979:     foreach my $package (@extension) {
                   5980: 	my ($package,$pack_type)=@{$package};
                   5981: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5982: 	    return $packagetab{"$pack_type&$name&default"};
                   5983: 	}
                   5984: 	if (defined($packagetab{$package."&$name&default"})) {
                   5985: 	    return $packagetab{$package."&$name&default"};
                   5986: 	}
                   5987:     }
                   5988:     # look for a global default setting
                   5989:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5990: 	return $packagetab{"default&$name&default"};
                   5991:     }
1.395     albertel 5992:     return undef;
                   5993: }
                   5994: 
1.334     albertel 5995: sub add_prefix_and_part {
                   5996:     my ($prefix,$part)=@_;
                   5997:     my $keyroot;
                   5998:     if (defined($prefix) && $prefix !~ /^__/) {
                   5999: 	# prefix that has a part already
                   6000: 	$keyroot=$prefix;
                   6001:     } elsif (defined($prefix)) {
                   6002: 	# prefix that is missing a part
                   6003: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6004:     } else {
                   6005: 	# no prefix at all
                   6006: 	if (defined($part)) { $keyroot='_'.$part; }
                   6007:     }
                   6008:     return $keyroot;
                   6009: }
                   6010: 
1.71      www      6011: # ---------------------------------------------------------------- Get metadata
                   6012: 
1.599     albertel 6013: my %metaentry;
1.71      www      6014: sub metadata {
1.176     www      6015:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6016:     $uri=&declutter($uri);
1.288     albertel 6017:     # if it is a non metadata possible uri return quickly
1.529     albertel 6018:     if (($uri eq '') || 
                   6019: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6020: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6021:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807   ! albertel 6022: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6023: 	return undef;
1.288     albertel 6024:     }
1.73      www      6025:     my $filename=$uri;
                   6026:     $uri=~s/\.meta$//;
1.172     www      6027: #
                   6028: # Is the metadata already cached?
1.177     www      6029: # Look at timestamp of caching
1.172     www      6030: # Everything is cached by the main uri, libraries are never directly cached
                   6031: #
1.428     albertel 6032:     if (!defined($liburi)) {
1.599     albertel 6033: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6034: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6035:     }
                   6036:     {
1.172     www      6037: #
                   6038: # Is this a recursive call for a library?
                   6039: #
1.599     albertel 6040: #	if (! exists($metacache{$uri})) {
                   6041: #	    $metacache{$uri}={};
                   6042: #	}
1.171     www      6043:         if ($liburi) {
                   6044: 	    $liburi=&declutter($liburi);
                   6045:             $filename=$liburi;
1.401     bowersj2 6046:         } else {
1.599     albertel 6047: 	    &devalidate_cache_new('meta',$uri);
                   6048: 	    undef(%metaentry);
1.401     bowersj2 6049: 	}
1.140     www      6050:         my %metathesekeys=();
1.73      www      6051:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6052: 	my $metastring;
1.768     albertel 6053: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6054: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6055: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6056: 	    $metastring=&getfile($file);
1.489     albertel 6057: 	}
1.208     albertel 6058:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6059:         my $token;
1.140     www      6060:         undef %metathesekeys;
1.71      www      6061:         while ($token=$parser->get_token) {
1.339     albertel 6062: 	    if ($token->[0] eq 'S') {
                   6063: 		if (defined($token->[2]->{'package'})) {
1.172     www      6064: #
                   6065: # This is a package - get package info
                   6066: #
1.339     albertel 6067: 		    my $package=$token->[2]->{'package'};
                   6068: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6069: 		    if (defined($token->[2]->{'id'})) { 
                   6070: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6071: 		    }
1.599     albertel 6072: 		    if ($metaentry{':packages'}) {
                   6073: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6074: 		    } else {
1.599     albertel 6075: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6076: 		    }
1.736     albertel 6077: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6078: 			my $part=$keyroot;
                   6079: 			$part=~s/^\_//;
1.736     albertel 6080: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6081: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6082: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6083: 			    # ignore package.tab specified default values
                   6084:                             # here &package_tab_default() will fetch those
                   6085: 			    if ($subp eq 'default') { next; }
1.736     albertel 6086: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6087: 			    my $unikey;
                   6088: 			    if ($pack =~ /_0$/) {
                   6089: 				$unikey='parameter_0_'.$name;
                   6090: 				$part=0;
                   6091: 			    } else {
                   6092: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6093: 			    }
1.339     albertel 6094: 			    if ($subp eq 'display') {
                   6095: 				$value.=' [Part: '.$part.']';
                   6096: 			    }
1.599     albertel 6097: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6098: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6099: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6100: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6101: 			    }
1.599     albertel 6102: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6103: 				$metaentry{':'.$unikey}=
                   6104: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6105: 			    }
1.339     albertel 6106: 			}
                   6107: 		    }
                   6108: 		} else {
1.172     www      6109: #
                   6110: # This is not a package - some other kind of start tag
1.339     albertel 6111: #
                   6112: 		    my $entry=$token->[1];
                   6113: 		    my $unikey;
                   6114: 		    if ($entry eq 'import') {
                   6115: 			$unikey='';
                   6116: 		    } else {
                   6117: 			$unikey=$entry;
                   6118: 		    }
                   6119: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6120: 
                   6121: 		    if (defined($token->[2]->{'id'})) { 
                   6122: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6123: 		    }
1.175     www      6124: 
1.339     albertel 6125: 		    if ($entry eq 'import') {
1.175     www      6126: #
                   6127: # Importing a library here
1.339     albertel 6128: #
                   6129: 			if ($depthcount<20) {
                   6130: 			    my $location=$parser->get_text('/import');
                   6131: 			    my $dir=$filename;
                   6132: 			    $dir=~s|[^/]*$||;
                   6133: 			    $location=&filelocation($dir,$location);
1.736     albertel 6134: 			    my $metadata = 
                   6135: 				&metadata($uri,'keys', $location,$unikey,
                   6136: 					  $depthcount+1);
                   6137: 			    foreach my $meta (split(',',$metadata)) {
                   6138: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6139: 				$metathesekeys{$meta}=1;
1.339     albertel 6140: 			    }
                   6141: 			}
                   6142: 		    } else { 
                   6143: 			
                   6144: 			if (defined($token->[2]->{'name'})) { 
                   6145: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6146: 			}
                   6147: 			$metathesekeys{$unikey}=1;
1.736     albertel 6148: 			foreach my $param (@{$token->[3]}) {
                   6149: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6150: 				$token->[2]->{$param};
1.339     albertel 6151: 			}
                   6152: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6153: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6154: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6155: 		 # only ws inside the tag, and not in default, so use default
                   6156: 		 # as value
1.599     albertel 6157: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6158: 			} else {
1.321     albertel 6159: 		  # either something interesting inside the tag or default
                   6160:                   # uninteresting
1.599     albertel 6161: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6162: 			}
1.172     www      6163: # end of not-a-package not-a-library import
1.339     albertel 6164: 		    }
1.172     www      6165: # end of not-a-package start tag
1.339     albertel 6166: 		}
1.172     www      6167: # the next is the end of "start tag"
1.339     albertel 6168: 	    }
                   6169: 	}
1.483     albertel 6170: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6171: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6172: 	    #no specific packages #how's our extension
                   6173: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6174: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6175: 					 \%metathesekeys);
                   6176: 	}
1.599     albertel 6177: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6178: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6179: 		#no specific packages well let's get default then
                   6180: 		if ($key!~/^default&/) { next; }
1.488     albertel 6181: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6182: 					     \%metathesekeys);
                   6183: 	    }
                   6184: 	}
1.338     www      6185: # are there custom rights to evaluate
1.599     albertel 6186: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6187: 
1.338     www      6188:     #
                   6189:     # Importing a rights file here
1.339     albertel 6190:     #
                   6191: 	    unless ($depthcount) {
1.599     albertel 6192: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6193: 		my $dir=$filename;
                   6194: 		$dir=~s|[^/]*$||;
                   6195: 		$location=&filelocation($dir,$location);
1.736     albertel 6196: 		my $rights_metadata =
                   6197: 		    &metadata($uri,'keys',$location,'_rights',
                   6198: 			      $depthcount+1);
                   6199: 		foreach my $rights (split(',',$rights_metadata)) {
                   6200: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6201: 		    $metathesekeys{$rights}=1;
1.339     albertel 6202: 		}
                   6203: 	    }
                   6204: 	}
1.737     albertel 6205: 	# uniqifiy package listing
                   6206: 	my %seen;
                   6207: 	my @uniq_packages =
                   6208: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6209: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6210: 
                   6211: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6212: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6213: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6214: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6215: # this is the end of "was not already recently cached
1.71      www      6216:     }
1.599     albertel 6217:     return $metaentry{':'.$what};
1.261     albertel 6218: }
                   6219: 
1.488     albertel 6220: sub metadata_create_package_def {
1.483     albertel 6221:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6222:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6223:     if ($subp eq 'default') { next; }
                   6224:     
1.599     albertel 6225:     if (defined($metaentry{':packages'})) {
                   6226: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6227:     } else {
1.599     albertel 6228: 	$metaentry{':packages'}=$package;
1.483     albertel 6229:     }
                   6230:     my $value=$packagetab{$key};
                   6231:     my $unikey;
                   6232:     $unikey='parameter_0_'.$name;
1.599     albertel 6233:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6234:     $$metathesekeys{$unikey}=1;
1.599     albertel 6235:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6236: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6237:     }
1.599     albertel 6238:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6239: 	$metaentry{':'.$unikey}=
                   6240: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6241:     }
                   6242: }
                   6243: 
1.261     albertel 6244: sub metadata_generate_part0 {
                   6245:     my ($metadata,$metacache,$uri) = @_;
                   6246:     my %allnames;
1.737     albertel 6247:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6248: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6249: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6250: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6251: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6252: 	    $allnames{$name}=$part;
                   6253: 	  }
                   6254: 	}
                   6255:     }
                   6256:     foreach my $name (keys(%allnames)) {
                   6257:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6258:       my $key=":parameter_0_$name";
1.261     albertel 6259:       $$metacache{"$key.part"}='0';
                   6260:       $$metacache{"$key.name"}=$name;
1.428     albertel 6261:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6262: 					   $allnames{$name}.'_'.$name.
                   6263: 					   '.type'};
1.428     albertel 6264:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6265: 			     '.display'};
1.644     www      6266:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6267:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6268:       $$metacache{"$key.display"}=$olddis;
                   6269:     }
1.71      www      6270: }
                   6271: 
1.764     albertel 6272: # ------------------------------------------------------ Devalidate title cache
                   6273: 
                   6274: sub devalidate_title_cache {
                   6275:     my ($url)=@_;
                   6276:     if (!$env{'request.course.id'}) { return; }
                   6277:     my $symb=&symbread($url);
                   6278:     if (!$symb) { return; }
                   6279:     my $key=$env{'request.course.id'}."\0".$symb;
                   6280:     &devalidate_cache_new('title',$key);
                   6281: }
                   6282: 
1.301     www      6283: # ------------------------------------------------- Get the title of a resource
                   6284: 
                   6285: sub gettitle {
                   6286:     my $urlsymb=shift;
                   6287:     my $symb=&symbread($urlsymb);
1.534     albertel 6288:     if ($symb) {
1.620     albertel 6289: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6290: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6291: 	if (defined($cached)) { 
                   6292: 	    return $result;
                   6293: 	}
1.534     albertel 6294: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6295: 	my $title='';
                   6296: 	my %bighash;
1.620     albertel 6297: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6298: 		&GDBM_READER(),0640)) {
                   6299: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6300: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6301: 	    untie %bighash;
                   6302: 	}
                   6303: 	$title=~s/\&colon\;/\:/gs;
                   6304: 	if ($title) {
1.599     albertel 6305: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6306: 	}
                   6307: 	$urlsymb=$url;
                   6308:     }
                   6309:     my $title=&metadata($urlsymb,'title');
                   6310:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6311:     return $title;
1.301     www      6312: }
1.613     albertel 6313: 
1.614     albertel 6314: sub get_slot {
                   6315:     my ($which,$cnum,$cdom)=@_;
                   6316:     if (!$cnum || !$cdom) {
1.790     albertel 6317: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6318: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6319: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6320:     }
1.703     albertel 6321:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6322:     my %slotinfo;
                   6323:     if (exists($remembered{$key})) {
                   6324: 	$slotinfo{$which} = $remembered{$key};
                   6325:     } else {
                   6326: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6327: 	&Apache::lonhomework::showhash(%slotinfo);
                   6328: 	my ($tmp)=keys(%slotinfo);
                   6329: 	if ($tmp=~/^error:/) { return (); }
                   6330: 	$remembered{$key} = $slotinfo{$which};
                   6331:     }
1.616     albertel 6332:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6333: 	return %{$slotinfo{$which}};
                   6334:     }
                   6335:     return $slotinfo{$which};
1.614     albertel 6336: }
1.31      www      6337: # ------------------------------------------------- Update symbolic store links
                   6338: 
                   6339: sub symblist {
                   6340:     my ($mapname,%newhash)=@_;
1.438     www      6341:     $mapname=&deversion(&declutter($mapname));
1.31      www      6342:     my %hash;
1.620     albertel 6343:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6344:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6345:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6346: 	    foreach my $url (keys %newhash) {
                   6347: 		next if ($url eq 'last_known'
                   6348: 			 && $env{'form.no_update_last_known'});
                   6349: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6350: 						    $newhash{$url}->[1],
                   6351: 						    $newhash{$url}->[0]);
1.191     harris41 6352:             }
1.31      www      6353:             if (untie(%hash)) {
                   6354: 		return 'ok';
                   6355:             }
                   6356:         }
                   6357:     }
                   6358:     return 'error';
1.212     www      6359: }
                   6360: 
                   6361: # --------------------------------------------------------------- Verify a symb
                   6362: 
                   6363: sub symbverify {
1.510     www      6364:     my ($symb,$thisurl)=@_;
                   6365:     my $thisfn=$thisurl;
1.439     www      6366:     $thisfn=&declutter($thisfn);
1.215     www      6367: # direct jump to resource in page or to a sequence - will construct own symbs
                   6368:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6369: # check URL part
1.409     www      6370:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6371: 
1.431     www      6372:     unless ($url eq $thisfn) { return 0; }
1.213     www      6373: 
1.216     www      6374:     $symb=&symbclean($symb);
1.510     www      6375:     $thisurl=&deversion($thisurl);
1.439     www      6376:     $thisfn=&deversion($thisfn);
1.213     www      6377: 
                   6378:     my %bighash;
                   6379:     my $okay=0;
1.431     www      6380: 
1.620     albertel 6381:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6382:                             &GDBM_READER(),0640)) {
1.510     www      6383:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6384:         unless ($ids) { 
1.510     www      6385:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6386:         }
                   6387:         if ($ids) {
                   6388: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6389: 	    foreach my $id (split(/\,/,$ids)) {
                   6390: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6391:                if (
                   6392:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6393:    eq $symb) { 
1.620     albertel 6394: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6395: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6396: 		       $okay=1; 
                   6397: 		   }
                   6398: 	       }
1.216     www      6399: 	   }
                   6400:         }
1.213     www      6401: 	untie(%bighash);
                   6402:     }
                   6403:     return $okay;
1.31      www      6404: }
                   6405: 
1.210     www      6406: # --------------------------------------------------------------- Clean-up symb
                   6407: 
                   6408: sub symbclean {
                   6409:     my $symb=shift;
1.568     albertel 6410:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6411: # remove version from map
                   6412:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6413: 
1.210     www      6414: # remove version from URL
                   6415:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6416: 
1.507     www      6417: # remove wrapper
                   6418: 
1.510     www      6419:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6420:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6421:     return $symb;
1.409     www      6422: }
                   6423: 
                   6424: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6425: 
                   6426: sub encode_symb {
                   6427:     my ($map,$resid,$url)=@_;
                   6428:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6429: }
1.409     www      6430: 
                   6431: sub decode_symb {
1.568     albertel 6432:     my $symb=shift;
                   6433:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6434:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6435:     return (&fixversion($map),$resid,&fixversion($url));
                   6436: }
                   6437: 
                   6438: sub fixversion {
                   6439:     my $fn=shift;
1.609     banghart 6440:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6441:     my %bighash;
                   6442:     my $uri=&clutter($fn);
1.620     albertel 6443:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6444: # is this cached?
1.599     albertel 6445:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6446:     if (defined($cached)) { return $result; }
                   6447: # unfortunately not cached, or expired
1.620     albertel 6448:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6449: 	    &GDBM_READER(),0640)) {
                   6450:  	if ($bighash{'version_'.$uri}) {
                   6451:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6452:  	    unless (($version eq 'mostrecent') || 
                   6453: 		    ($version==&getversion($uri))) {
1.440     www      6454:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6455:  	    }
                   6456:  	}
                   6457:  	untie %bighash;
1.413     www      6458:     }
1.599     albertel 6459:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6460: }
                   6461: 
                   6462: sub deversion {
                   6463:     my $url=shift;
                   6464:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6465:     return $url;
1.210     www      6466: }
                   6467: 
1.31      www      6468: # ------------------------------------------------------ Return symb list entry
                   6469: 
                   6470: sub symbread {
1.249     www      6471:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6472:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6473:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6474: # no filename provided? try from environment
1.44      www      6475:     unless ($thisfn) {
1.620     albertel 6476:         if ($env{'request.symb'}) {
                   6477: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6478: 	}
1.620     albertel 6479: 	$thisfn=$env{'request.filename'};
1.44      www      6480:     }
1.569     albertel 6481:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6482: # is that filename actually a symb? Verify, clean, and return
                   6483:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6484: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6485: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6486: 	}
1.242     www      6487:     }
1.44      www      6488:     $thisfn=declutter($thisfn);
1.31      www      6489:     my %hash;
1.37      www      6490:     my %bighash;
                   6491:     my $syval='';
1.620     albertel 6492:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6493:         my $targetfn = $thisfn;
1.609     banghart 6494:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6495:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6496:         }
1.687     albertel 6497: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6498: 	    $targetfn=$1;
                   6499: 	}
1.620     albertel 6500:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6501:                       &GDBM_READER(),0640)) {
1.481     raeburn  6502: 	    $syval=$hash{$targetfn};
1.37      www      6503:             untie(%hash);
                   6504:         }
                   6505: # ---------------------------------------------------------- There was an entry
                   6506:         if ($syval) {
1.601     albertel 6507: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6508: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6509: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6510: 		    #return $env{$cache_str}='';
1.601     albertel 6511: 		#}    
                   6512: 		#$syval.=$1;
                   6513: 	    #}
1.37      www      6514:         } else {
                   6515: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6516:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6517:                             &GDBM_READER(),0640)) {
1.37      www      6518: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6519:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6520:               unless ($ids) { 
                   6521:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6522:               }
                   6523:               unless ($ids) {
                   6524: # alias?
                   6525: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6526:               }
1.37      www      6527:               if ($ids) {
                   6528: # ------------------------------------------------------------------- Has ID(s)
                   6529:                  my @possibilities=split(/\,/,$ids);
1.39      www      6530:                  if ($#possibilities==0) {
                   6531: # ----------------------------------------------- There is only one possibility
1.37      www      6532: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6533: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6534: 						    $resid,$thisfn);
1.249     www      6535:                  } elsif (!$donotrecurse) {
1.39      www      6536: # ------------------------------------------ There is more than one possibility
                   6537:                      my $realpossible=0;
1.800     albertel 6538:                      foreach my $id (@possibilities) {
                   6539: 			 my $file=$bighash{'src_'.$id};
1.39      www      6540:                          if (&allowed('bre',$file)) {
1.800     albertel 6541:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6542:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6543: 				$realpossible++;
1.626     albertel 6544:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6545: 						    $resid,$thisfn);
1.39      www      6546:                             }
                   6547: 			 }
1.191     harris41 6548:                      }
1.39      www      6549: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6550:                  } else {
                   6551:                      $syval='';
1.37      www      6552:                  }
                   6553: 	      }
                   6554:               untie(%bighash)
1.481     raeburn  6555:            }
1.31      www      6556:         }
1.62      www      6557:         if ($syval) {
1.620     albertel 6558: 	    return $env{$cache_str}=$syval;
1.62      www      6559:         }
1.31      www      6560:     }
1.44      www      6561:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6562:     return $env{$cache_str}='';
1.31      www      6563: }
                   6564: 
                   6565: # ---------------------------------------------------------- Return random seed
                   6566: 
1.32      www      6567: sub numval {
                   6568:     my $txt=shift;
                   6569:     $txt=~tr/A-J/0-9/;
                   6570:     $txt=~tr/a-j/0-9/;
                   6571:     $txt=~tr/K-T/0-9/;
                   6572:     $txt=~tr/k-t/0-9/;
                   6573:     $txt=~tr/U-Z/0-5/;
                   6574:     $txt=~tr/u-z/0-5/;
                   6575:     $txt=~s/\D//g;
1.564     albertel 6576:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6577:     return int($txt);
1.368     albertel 6578: }
                   6579: 
1.484     albertel 6580: sub numval2 {
                   6581:     my $txt=shift;
                   6582:     $txt=~tr/A-J/0-9/;
                   6583:     $txt=~tr/a-j/0-9/;
                   6584:     $txt=~tr/K-T/0-9/;
                   6585:     $txt=~tr/k-t/0-9/;
                   6586:     $txt=~tr/U-Z/0-5/;
                   6587:     $txt=~tr/u-z/0-5/;
                   6588:     $txt=~s/\D//g;
                   6589:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6590:     my $total;
                   6591:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6592:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6593:     return int($total);
                   6594: }
                   6595: 
1.575     albertel 6596: sub numval3 {
                   6597:     use integer;
                   6598:     my $txt=shift;
                   6599:     $txt=~tr/A-J/0-9/;
                   6600:     $txt=~tr/a-j/0-9/;
                   6601:     $txt=~tr/K-T/0-9/;
                   6602:     $txt=~tr/k-t/0-9/;
                   6603:     $txt=~tr/U-Z/0-5/;
                   6604:     $txt=~tr/u-z/0-5/;
                   6605:     $txt=~s/\D//g;
                   6606:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6607:     my $total;
                   6608:     foreach my $val (@txts) { $total+=$val; }
                   6609:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6610:     return $total;
                   6611: }
                   6612: 
1.675     albertel 6613: sub digest {
                   6614:     my ($data)=@_;
                   6615:     my $digest=&Digest::MD5::md5($data);
                   6616:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6617:     my ($e,$f);
                   6618:     {
                   6619:         use integer;
                   6620:         $e=($a+$b);
                   6621:         $f=($c+$d);
                   6622:         if ($_64bit) {
                   6623:             $e=(($e<<32)>>32);
                   6624:             $f=(($f<<32)>>32);
                   6625:         }
                   6626:     }
                   6627:     if (wantarray) {
                   6628: 	return ($e,$f);
                   6629:     } else {
                   6630: 	my $g;
                   6631: 	{
                   6632: 	    use integer;
                   6633: 	    $g=($e+$f);
                   6634: 	    if ($_64bit) {
                   6635: 		$g=(($g<<32)>>32);
                   6636: 	    }
                   6637: 	}
                   6638: 	return $g;
                   6639:     }
                   6640: }
                   6641: 
1.368     albertel 6642: sub latest_rnd_algorithm_id {
1.675     albertel 6643:     return '64bit5';
1.366     albertel 6644: }
1.32      www      6645: 
1.503     albertel 6646: sub get_rand_alg {
                   6647:     my ($courseid)=@_;
1.790     albertel 6648:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6649:     if ($courseid) {
1.620     albertel 6650: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6651:     }
                   6652:     return &latest_rnd_algorithm_id();
                   6653: }
                   6654: 
1.562     albertel 6655: sub validCODE {
                   6656:     my ($CODE)=@_;
                   6657:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6658:     return 0;
                   6659: }
                   6660: 
1.491     albertel 6661: sub getCODE {
1.620     albertel 6662:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6663:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6664: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6665: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6666: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6667:     }
                   6668:     return undef;
                   6669: }
                   6670: 
1.31      www      6671: sub rndseed {
1.155     albertel 6672:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6673: 
1.790     albertel 6674:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6675:     if (!$symb) {
1.366     albertel 6676: 	unless ($symb=$wsymb) { return time; }
                   6677:     }
                   6678:     if (!$courseid) { $courseid=$wcourseid; }
                   6679:     if (!$domain) { $domain=$wdomain; }
                   6680:     if (!$username) { $username=$wusername }
1.503     albertel 6681:     my $which=&get_rand_alg();
1.803     albertel 6682: 
1.491     albertel 6683:     if (defined(&getCODE())) {
1.675     albertel 6684: 	if ($which eq '64bit5') {
                   6685: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6686: 	} elsif ($which eq '64bit4') {
1.575     albertel 6687: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6688: 	} else {
                   6689: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6690: 	}
1.675     albertel 6691:     } elsif ($which eq '64bit5') {
                   6692: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6693:     } elsif ($which eq '64bit4') {
                   6694: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6695:     } elsif ($which eq '64bit3') {
                   6696: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6697:     } elsif ($which eq '64bit2') {
                   6698: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6699:     } elsif ($which eq '64bit') {
                   6700: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6701:     }
                   6702:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6703: }
                   6704: 
                   6705: sub rndseed_32bit {
                   6706:     my ($symb,$courseid,$domain,$username)=@_;
                   6707:     {
                   6708: 	use integer;
                   6709: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6710: 	my $symbseed=numval($symb) << 22;
                   6711: 	my $namechck=unpack("%32C*",$username) << 17;
                   6712: 	my $nameseed=numval($username) << 12;
                   6713: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6714: 	my $courseseed=unpack("%32C*",$courseid);
                   6715: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6716: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6717: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6718: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6719: 	return $num;
                   6720:     }
                   6721: }
                   6722: 
                   6723: sub rndseed_64bit {
                   6724:     my ($symb,$courseid,$domain,$username)=@_;
                   6725:     {
                   6726: 	use integer;
                   6727: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6728: 	my $symbseed=numval($symb) << 10;
                   6729: 	my $namechck=unpack("%32S*",$username);
                   6730: 	
                   6731: 	my $nameseed=numval($username) << 21;
                   6732: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6733: 	my $courseseed=unpack("%32S*",$courseid);
                   6734: 	
                   6735: 	my $num1=$symbchck+$symbseed+$namechck;
                   6736: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6737: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6738: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6739: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6740: 	return "$num1,$num2";
1.155     albertel 6741:     }
1.366     albertel 6742: }
                   6743: 
1.443     albertel 6744: sub rndseed_64bit2 {
                   6745:     my ($symb,$courseid,$domain,$username)=@_;
                   6746:     {
                   6747: 	use integer;
                   6748: 	# strings need to be an even # of cahracters long, it it is odd the
                   6749:         # last characters gets thrown away
                   6750: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6751: 	my $symbseed=numval($symb) << 10;
                   6752: 	my $namechck=unpack("%32S*",$username.' ');
                   6753: 	
                   6754: 	my $nameseed=numval($username) << 21;
1.501     albertel 6755: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6756: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6757: 	
                   6758: 	my $num1=$symbchck+$symbseed+$namechck;
                   6759: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6760: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6761: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6762: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6763: 	return "$num1,$num2";
                   6764:     }
                   6765: }
                   6766: 
                   6767: sub rndseed_64bit3 {
                   6768:     my ($symb,$courseid,$domain,$username)=@_;
                   6769:     {
                   6770: 	use integer;
                   6771: 	# strings need to be an even # of cahracters long, it it is odd the
                   6772:         # last characters gets thrown away
                   6773: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6774: 	my $symbseed=numval2($symb) << 10;
                   6775: 	my $namechck=unpack("%32S*",$username.' ');
                   6776: 	
                   6777: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6778: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6779: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6780: 	
                   6781: 	my $num1=$symbchck+$symbseed+$namechck;
                   6782: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6783: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6784: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6785: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6786: 	
1.503     albertel 6787: 	return "$num1:$num2";
1.443     albertel 6788:     }
                   6789: }
                   6790: 
1.575     albertel 6791: sub rndseed_64bit4 {
                   6792:     my ($symb,$courseid,$domain,$username)=@_;
                   6793:     {
                   6794: 	use integer;
                   6795: 	# strings need to be an even # of cahracters long, it it is odd the
                   6796:         # last characters gets thrown away
                   6797: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6798: 	my $symbseed=numval3($symb) << 10;
                   6799: 	my $namechck=unpack("%32S*",$username.' ');
                   6800: 	
                   6801: 	my $nameseed=numval3($username) << 21;
                   6802: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6803: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6804: 	
                   6805: 	my $num1=$symbchck+$symbseed+$namechck;
                   6806: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6807: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6808: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6809: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6810: 	
                   6811: 	return "$num1:$num2";
                   6812:     }
                   6813: }
                   6814: 
1.675     albertel 6815: sub rndseed_64bit5 {
                   6816:     my ($symb,$courseid,$domain,$username)=@_;
                   6817:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6818:     return "$num1:$num2";
                   6819: }
                   6820: 
1.366     albertel 6821: sub rndseed_CODE_64bit {
                   6822:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6823:     {
1.366     albertel 6824: 	use integer;
1.443     albertel 6825: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6826: 	my $symbseed=numval2($symb);
1.491     albertel 6827: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6828: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6829: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6830: 	my $num1=$symbseed+$CODEchck;
                   6831: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6832: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6833: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6834: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6835: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6836: 	return "$num1:$num2";
1.366     albertel 6837:     }
                   6838: }
                   6839: 
1.575     albertel 6840: sub rndseed_CODE_64bit4 {
                   6841:     my ($symb,$courseid,$domain,$username)=@_;
                   6842:     {
                   6843: 	use integer;
                   6844: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6845: 	my $symbseed=numval3($symb);
                   6846: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6847: 	my $CODEseed=numval3(&getCODE());
                   6848: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6849: 	my $num1=$symbseed+$CODEchck;
                   6850: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6851: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6852: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6853: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6854: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6855: 	return "$num1:$num2";
                   6856:     }
                   6857: }
                   6858: 
1.675     albertel 6859: sub rndseed_CODE_64bit5 {
                   6860:     my ($symb,$courseid,$domain,$username)=@_;
                   6861:     my $code = &getCODE();
                   6862:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6863:     return "$num1:$num2";
                   6864: }
                   6865: 
1.366     albertel 6866: sub setup_random_from_rndseed {
                   6867:     my ($rndseed)=@_;
1.503     albertel 6868:     if ($rndseed =~/([,:])/) {
                   6869: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6870: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6871:     } else {
                   6872: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6873:     }
1.36      albertel 6874: }
                   6875: 
1.474     albertel 6876: sub latest_receipt_algorithm_id {
                   6877:     return 'receipt2';
                   6878: }
                   6879: 
1.480     www      6880: sub recunique {
                   6881:     my $fucourseid=shift;
                   6882:     my $unique;
1.620     albertel 6883:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6884: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6885:     } else {
                   6886: 	$unique=$perlvar{'lonReceipt'};
                   6887:     }
                   6888:     return unpack("%32C*",$unique);
                   6889: }
                   6890: 
                   6891: sub recprefix {
                   6892:     my $fucourseid=shift;
                   6893:     my $prefix;
1.620     albertel 6894:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6895: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6896:     } else {
                   6897: 	$prefix=$perlvar{'lonHostID'};
                   6898:     }
                   6899:     return unpack("%32C*",$prefix);
                   6900: }
                   6901: 
1.76      www      6902: sub ireceipt {
1.474     albertel 6903:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6904:     my $cuname=unpack("%32C*",$funame);
                   6905:     my $cudom=unpack("%32C*",$fudom);
                   6906:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6907:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6908:     my $cunique=&recunique($fucourseid);
1.474     albertel 6909:     my $cpart=unpack("%32S*",$part);
1.480     www      6910:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6911:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6912: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6913: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6914: 			       
                   6915: 	$return.= ($cunique%$cuname+
                   6916: 		   $cunique%$cudom+
                   6917: 		   $cusymb%$cuname+
                   6918: 		   $cusymb%$cudom+
                   6919: 		   $cucourseid%$cuname+
                   6920: 		   $cucourseid%$cudom+
                   6921: 		   $cpart%$cuname+
                   6922: 		   $cpart%$cudom);
                   6923:     } else {
                   6924: 	$return.= ($cunique%$cuname+
                   6925: 		   $cunique%$cudom+
                   6926: 		   $cusymb%$cuname+
                   6927: 		   $cusymb%$cudom+
                   6928: 		   $cucourseid%$cuname+
                   6929: 		   $cucourseid%$cudom);
                   6930:     }
                   6931:     return $return;
1.76      www      6932: }
                   6933: 
                   6934: sub receipt {
1.474     albertel 6935:     my ($part)=@_;
1.790     albertel 6936:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6937:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6938: }
1.260     ng       6939: 
1.790     albertel 6940: sub whichuser {
                   6941:     my ($passedsymb)=@_;
                   6942:     my ($symb,$courseid,$domain,$name,$publicuser);
                   6943:     if (defined($env{'form.grade_symb'})) {
                   6944: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   6945: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   6946: 	if (!$allowed &&
                   6947: 	    exists($env{'request.course.sec'}) &&
                   6948: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   6949: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   6950: 			      '/'.$env{'request.course.sec'});
                   6951: 	}
                   6952: 	if ($allowed) {
                   6953: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   6954: 	    $courseid=$tmp_courseid;
                   6955: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   6956: 	    ($name)=&get_env_multiple('form.grade_username');
                   6957: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   6958: 	}
                   6959:     }
                   6960:     if (!$passedsymb) {
                   6961: 	$symb=&symbread();
                   6962:     } else {
                   6963: 	$symb=$passedsymb;
                   6964:     }
                   6965:     $courseid=$env{'request.course.id'};
                   6966:     $domain=$env{'user.domain'};
                   6967:     $name=$env{'user.name'};
                   6968:     if ($name eq 'public' && $domain eq 'public') {
                   6969: 	if (!defined($env{'form.username'})) {
                   6970: 	    $env{'form.username'}.=time.rand(10000000);
                   6971: 	}
                   6972: 	$name.=$env{'form.username'};
                   6973:     }
                   6974:     return ($symb,$courseid,$domain,$name,$publicuser);
                   6975: 
                   6976: }
                   6977: 
1.36      albertel 6978: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6979: # returns either the contents of the file or 
                   6980: # -1 if the file doesn't exist
1.481     raeburn  6981: #
                   6982: # if the target is a file that was uploaded via DOCS, 
                   6983: # a check will be made to see if a current copy exists on the local server,
                   6984: # if it does this will be served, otherwise a copy will be retrieved from
                   6985: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6986: # the local server.   
1.472     albertel 6987: 
1.36      albertel 6988: sub getfile {
1.538     albertel 6989:     my ($file) = @_;
1.609     banghart 6990:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6991:     &repcopy($file);
                   6992:     return &readfile($file);
                   6993: }
                   6994: 
                   6995: sub repcopy_userfile {
                   6996:     my ($file)=@_;
1.609     banghart 6997:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6998:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6999:     my ($cdom,$cnum,$filename) = 
1.807   ! albertel 7000: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_username)/+(.*)|);
1.538     albertel 7001:     my ($info,$rtncode);
                   7002:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7003:     if (-e "$file") {
                   7004: 	my @fileinfo = stat($file);
                   7005: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7006: 	if ($lwpresp ne 'ok') {
                   7007: 	    if ($rtncode eq '404') {
1.538     albertel 7008: 		unlink($file);
1.482     albertel 7009: 	    }
1.517     albertel 7010: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7011: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7012: 	    #my $response=$ua->request($request);
                   7013: 	    #if ($response->is_success()) {
                   7014: 	#	return $response->content;
                   7015: 	#    } else {
                   7016: 	#	return -1;
                   7017: 	#    }
1.482     albertel 7018: 	    return -1;
                   7019: 	}
                   7020: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7021: 	    return 'ok';
1.482     albertel 7022: 	}
                   7023: 	$info = '';
1.538     albertel 7024: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7025: 	if ($lwpresp ne 'ok') {
                   7026: 	    return -1;
                   7027: 	}
                   7028:     } else {
1.538     albertel 7029: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7030: 	if ($lwpresp ne 'ok') {
1.517     albertel 7031: 	    my $ua=new LWP::UserAgent;
1.538     albertel 7032: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7033: 	    my $response=$ua->request($request);
                   7034: 	    if ($response->is_success()) {
1.538     albertel 7035: 		$info=$response->content;
1.517     albertel 7036: 	    } else {
                   7037: 		return -1;
                   7038: 	    }
1.482     albertel 7039: 	}
                   7040: 	my @parts = ($cdom,$cnum); 
                   7041: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7042: 	    push @parts, split(/\//,$1);
1.518     albertel 7043: 	}
1.538     albertel 7044: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7045: 	foreach my $part (@parts) {
                   7046: 	    $path .= '/'.$part;
                   7047: 	    if (!-e $path) {
                   7048: 		mkdir($path,0770);
                   7049: 	    }
                   7050: 	}
                   7051:     }
1.538     albertel 7052:     open(FILE,">$file");
1.482     albertel 7053:     print FILE $info;
                   7054:     close(FILE);
1.607     raeburn  7055:     return 'ok';
1.481     raeburn  7056: }
                   7057: 
1.517     albertel 7058: sub tokenwrapper {
                   7059:     my $uri=shift;
1.552     albertel 7060:     $uri=~s|^http\://([^/]+)||;
                   7061:     $uri=~s|^/||;
1.620     albertel 7062:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7063:     my $token=$1;
1.552     albertel 7064:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7065:     if ($udom && $uname && $file) {
                   7066: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7067:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7068:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7069:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7070:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7071:     } else {
                   7072:         return '/adm/notfound.html';
                   7073:     }
                   7074: }
                   7075: 
1.481     raeburn  7076: sub getuploaded {
                   7077:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7078:     $uri=~s/^\///;
                   7079:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7080:     my $ua=new LWP::UserAgent;
                   7081:     my $request=new HTTP::Request($reqtype,$uri);
                   7082:     my $response=$ua->request($request);
                   7083:     $$rtncode = $response->code;
1.482     albertel 7084:     if (! $response->is_success()) {
                   7085: 	return 'failed';
                   7086:     }      
                   7087:     if ($reqtype eq 'HEAD') {
1.486     www      7088: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7089:     } elsif ($reqtype eq 'GET') {
                   7090: 	$$info = $response->content;
1.472     albertel 7091:     }
1.482     albertel 7092:     return 'ok';
1.36      albertel 7093: }
                   7094: 
1.481     raeburn  7095: sub readfile {
                   7096:     my $file = shift;
                   7097:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7098:     my $fh;
                   7099:     open($fh,"<$file");
                   7100:     my $a='';
1.800     albertel 7101:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7102:     return $a;
                   7103: }
                   7104: 
1.36      albertel 7105: sub filelocation {
1.590     banghart 7106:     my ($dir,$file) = @_;
                   7107:     my $location;
                   7108:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7109: 
                   7110:     if ($file =~ m-^/adm/-) {
                   7111: 	$file=~s-^/adm/wrapper/-/-;
                   7112: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7113:     }
1.590     banghart 7114:     if ($file=~m:^/~:) { # is a contruction space reference
                   7115:         $location = $file;
                   7116:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807   ! albertel 7117:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7118: 	# is a correct contruction space reference
                   7119:         $location = $file;
1.609     banghart 7120:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7121:         my ($udom,$uname,$filename)=
1.807   ! albertel 7122:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_username)/+(.*)$-);
1.590     banghart 7123:         my $home=&homeserver($uname,$udom);
                   7124:         my $is_me=0;
                   7125:         my @ids=&current_machine_ids();
                   7126:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7127:         if ($is_me) {
1.740     www      7128:   	    $location=&propath($udom,$uname).
1.590     banghart 7129:   	      '/userfiles/'.$filename;
                   7130:         } else {
                   7131:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7132:   	      $udom.'/'.$uname.'/'.$filename;
                   7133:         }
                   7134:     } else {
                   7135:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7136:         $file=~s:^/res/:/:;
                   7137:         if ( !( $file =~ m:^/:) ) {
                   7138:             $location = $dir. '/'.$file;
                   7139:         } else {
                   7140:             $location = '/home/httpd/html/res'.$file;
                   7141:         }
1.59      albertel 7142:     }
1.590     banghart 7143:     $location=~s://+:/:g; # remove duplicate /
                   7144:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7145:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7146:     return $location;
1.46      www      7147: }
1.36      albertel 7148: 
1.46      www      7149: sub hreflocation {
                   7150:     my ($dir,$file)=@_;
1.460     albertel 7151:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7152: 	$file=filelocation($dir,$file);
1.700     albertel 7153:     } elsif ($file=~m-^/adm/-) {
                   7154: 	$file=~s-^/adm/wrapper/-/-;
                   7155: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7156:     }
                   7157:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7158: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807   ! albertel 7159:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
        !          7160: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7161:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.807   ! albertel 7162: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_username)/userfiles/
1.666     albertel 7163: 	    -/uploaded/$1/$2/-x;
1.46      www      7164:     }
1.462     albertel 7165:     return $file;
1.465     albertel 7166: }
                   7167: 
                   7168: sub current_machine_domains {
                   7169:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7170:     my @domains;
                   7171:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7172: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7173: 	if ($hostname eq $name) {
                   7174: 	    push(@domains,$hostdom{$id});
                   7175: 	}
                   7176:     }
                   7177:     return @domains;
                   7178: }
                   7179: 
                   7180: sub current_machine_ids {
                   7181:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7182:     my @ids;
                   7183:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7184: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7185: 	if ($hostname eq $name) {
                   7186: 	    push(@ids,$id);
                   7187: 	}
                   7188:     }
                   7189:     return @ids;
1.31      www      7190: }
                   7191: 
                   7192: # ------------------------------------------------------------- Declutters URLs
                   7193: 
                   7194: sub declutter {
                   7195:     my $thisfn=shift;
1.569     albertel 7196:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7197:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7198:     $thisfn=~s/^\///;
1.697     albertel 7199:     $thisfn=~s|^adm/wrapper/||;
                   7200:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7201:     $thisfn=~s/^res\///;
1.235     www      7202:     $thisfn=~s/\?.+$//;
1.268     www      7203:     return $thisfn;
                   7204: }
                   7205: 
                   7206: # ------------------------------------------------------------- Clutter up URLs
                   7207: 
                   7208: sub clutter {
                   7209:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7210:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7211:        $thisfn='/res'.$thisfn; 
                   7212:     }
1.694     albertel 7213:     if ($thisfn !~m|/adm|) {
1.695     albertel 7214: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7215: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7216: 	} else {
                   7217: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7218: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7219: 	    if ($embstyle eq 'ssi'
                   7220: 		|| ($embstyle eq 'hdn')
                   7221: 		|| ($embstyle eq 'rat')
                   7222: 		|| ($embstyle eq 'prv')
                   7223: 		|| ($embstyle eq 'ign')) {
                   7224: 		#do nothing with these
                   7225: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7226: 		|| ($embstyle eq 'emb')
                   7227: 		|| ($embstyle eq 'wrp')) {
                   7228: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7229: 	    } elsif ($embstyle eq 'unk'
                   7230: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7231: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7232: 	    } else {
1.718     www      7233: #		&logthis("Got a blank emb style");
1.695     albertel 7234: 	    }
1.694     albertel 7235: 	}
                   7236:     }
1.31      www      7237:     return $thisfn;
1.12      www      7238: }
                   7239: 
1.787     albertel 7240: sub clutter_with_no_wrapper {
                   7241:     my $uri = &clutter(shift);
                   7242:     if ($uri =~ m-^/adm/-) {
                   7243: 	$uri =~ s-^/adm/wrapper/-/-;
                   7244: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7245:     }
                   7246:     return $uri;
                   7247: }
                   7248: 
1.557     albertel 7249: sub freeze_escape {
                   7250:     my ($value)=@_;
                   7251:     if (ref($value)) {
                   7252: 	$value=&nfreeze($value);
                   7253: 	return '__FROZEN__'.&escape($value);
                   7254:     }
                   7255:     return &escape($value);
                   7256: }
                   7257: 
1.11      www      7258: 
1.557     albertel 7259: sub thaw_unescape {
                   7260:     my ($value)=@_;
                   7261:     if ($value =~ /^__FROZEN__/) {
                   7262: 	substr($value,0,10,undef);
                   7263: 	$value=&unescape($value);
                   7264: 	return &thaw($value);
                   7265:     }
                   7266:     return &unescape($value);
                   7267: }
                   7268: 
1.436     albertel 7269: sub correct_line_ends {
                   7270:     my ($result)=@_;
                   7271:     $$result =~s/\r\n/\n/mg;
                   7272:     $$result =~s/\r/\n/mg;
1.415     albertel 7273: }
1.1       albertel 7274: # ================================================================ Main Program
                   7275: 
1.184     www      7276: sub goodbye {
1.204     albertel 7277:    &logthis("Starting Shut down");
1.443     albertel 7278: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7279:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7280: #converted
1.599     albertel 7281: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7282:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7283: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7284: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7285: #1.1 only
1.599     albertel 7286: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7287: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7288: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7289: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7290:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7291:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7292:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7293:    &flushcourselogs();
                   7294:    &logthis("Shutting down");
                   7295: }
                   7296: 
1.179     www      7297: BEGIN {
1.228     harris41 7298: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7299:     unless ($readit) {
1.217     harris41 7300: {
1.781     raeburn  7301:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7302:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7303: }
1.1       albertel 7304: 
1.327     albertel 7305: # ------------------------------------------------------------ Read domain file
                   7306: {
                   7307:     %domaindescription = ();
                   7308:     %domain_auth_def = ();
                   7309:     %domain_auth_arg_def = ();
1.448     albertel 7310:     my $fh;
                   7311:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7312: 	while (my $line = <$fh>) {
                   7313:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7314: #           next if /^\#/;
1.801     foxr     7315:            chomp $line;
1.403     www      7316:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7317: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7318: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7319:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7320: 	   $domaindescription{$domain}=$domain_description;
                   7321: 	   $domain_lang_def{$domain}=$def_lang;
                   7322: 	   $domain_city{$domain}=$city;
                   7323: 	   $domain_longi{$domain}=$longi;
                   7324: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7325:            $domain_primary{$domain}=$primary;
1.403     www      7326: 
1.448     albertel 7327:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7328: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7329: 	}
1.327     albertel 7330:     }
1.448     albertel 7331:     close ($fh);
1.327     albertel 7332: }
                   7333: 
                   7334: 
1.1       albertel 7335: # ------------------------------------------------------------- Read hosts file
                   7336: {
1.448     albertel 7337:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7338: 
                   7339:     while (my $configline=<$config>) {
1.303     matthew  7340:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7341:        chomp($configline);
1.595     albertel 7342:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7343:        $name=~s/\s//g;
1.595     albertel 7344:        if ($id && $domain && $role && $name) {
1.252     albertel 7345: 	 $hostname{$id}=$name;
                   7346: 	 $hostdom{$id}=$domain;
                   7347: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7348:        }
1.1       albertel 7349:     }
1.448     albertel 7350:     close($config);
1.619     albertel 7351:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7352:     #&get_iphost();
1.1       albertel 7353: }
                   7354: 
1.598     albertel 7355: sub get_iphost {
                   7356:     if (%iphost) { return %iphost; }
1.653     albertel 7357:     my %name_to_ip;
1.598     albertel 7358:     foreach my $id (keys(%hostname)) {
                   7359: 	my $name=$hostname{$id};
1.653     albertel 7360: 	my $ip;
                   7361: 	if (!exists($name_to_ip{$name})) {
                   7362: 	    $ip = gethostbyname($name);
                   7363: 	    if (!$ip || length($ip) ne 4) {
                   7364: 		&logthis("Skipping host $id name $name no IP found\n");
                   7365: 		next;
                   7366: 	    }
                   7367: 	    $ip=inet_ntoa($ip);
                   7368: 	    $name_to_ip{$name} = $ip;
                   7369: 	} else {
                   7370: 	    $ip = $name_to_ip{$name};
1.598     albertel 7371: 	}
                   7372: 	push(@{$iphost{$ip}},$id);
                   7373:     }
                   7374:     return %iphost;
                   7375: }
                   7376: 
1.1       albertel 7377: # ------------------------------------------------------ Read spare server file
                   7378: {
1.448     albertel 7379:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7380: 
                   7381:     while (my $configline=<$config>) {
                   7382:        chomp($configline);
1.284     matthew  7383:        if ($configline) {
1.784     albertel 7384: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7385: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7386: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7387:        }
                   7388:     }
1.448     albertel 7389:     close($config);
1.1       albertel 7390: }
1.11      www      7391: # ------------------------------------------------------------ Read permissions
                   7392: {
1.448     albertel 7393:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7394: 
                   7395:     while (my $configline=<$config>) {
1.448     albertel 7396: 	chomp($configline);
                   7397: 	if ($configline) {
                   7398: 	    my ($role,$perm)=split(/ /,$configline);
                   7399: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7400: 	}
1.11      www      7401:     }
1.448     albertel 7402:     close($config);
1.11      www      7403: }
                   7404: 
                   7405: # -------------------------------------------- Read plain texts for permissions
                   7406: {
1.448     albertel 7407:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7408: 
                   7409:     while (my $configline=<$config>) {
1.448     albertel 7410: 	chomp($configline);
                   7411: 	if ($configline) {
1.742     raeburn  7412: 	    my ($short,@plain)=split(/:/,$configline);
                   7413:             %{$prp{$short}} = ();
                   7414: 	    if (@plain > 0) {
                   7415:                 $prp{$short}{'std'} = $plain[0];
                   7416:                 for (my $i=1; $i<@plain; $i++) {
                   7417:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7418:                 }
                   7419:             }
1.448     albertel 7420: 	}
1.135     www      7421:     }
1.448     albertel 7422:     close($config);
1.135     www      7423: }
                   7424: 
                   7425: # ---------------------------------------------------------- Read package table
                   7426: {
1.448     albertel 7427:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7428: 
                   7429:     while (my $configline=<$config>) {
1.483     albertel 7430: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7431: 	chomp($configline);
                   7432: 	my ($short,$plain)=split(/:/,$configline);
                   7433: 	my ($pack,$name)=split(/\&/,$short);
                   7434: 	if ($plain ne '') {
                   7435: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7436: 	    $packagetab{$short}=$plain; 
                   7437: 	}
1.11      www      7438:     }
1.448     albertel 7439:     close($config);
1.329     matthew  7440: }
                   7441: 
                   7442: # ------------- set up temporary directory
                   7443: {
                   7444:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7445: 
1.11      www      7446: }
                   7447: 
1.794     albertel 7448: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7449: 				'compress_threshold'=> 20_000,
                   7450:  			        });
1.185     www      7451: 
1.281     www      7452: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7453: $dumpcount=0;
1.22      www      7454: 
1.163     harris41 7455: &logtouch();
1.672     albertel 7456: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7457: $readit=1;
1.564     albertel 7458:     {
                   7459: 	use integer;
                   7460: 	my $test=(2**32)+1;
1.568     albertel 7461: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7462: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7463:     }
1.195     www      7464: }
1.1       albertel 7465: }
1.179     www      7466: 
1.1       albertel 7467: 1;
1.191     harris41 7468: __END__
                   7469: 
1.243     albertel 7470: =pod
                   7471: 
1.191     harris41 7472: =head1 NAME
                   7473: 
1.243     albertel 7474: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7475: 
                   7476: =head1 SYNOPSIS
                   7477: 
1.243     albertel 7478: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7479: 
                   7480:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7481: 
1.243     albertel 7482: Common parameters:
                   7483: 
                   7484: =over 4
                   7485: 
                   7486: =item *
                   7487: 
                   7488: $uname : an internal username (if $cname expecting a course Id specifically)
                   7489: 
                   7490: =item *
                   7491: 
                   7492: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7493: 
                   7494: =item *
                   7495: 
                   7496: $symb : a resource instance identifier
                   7497: 
                   7498: =item *
                   7499: 
                   7500: $namespace : the name of a .db file that contains the data needed or
                   7501: being set.
                   7502: 
                   7503: =back
                   7504: 
1.394     bowersj2 7505: =head1 OVERVIEW
1.191     harris41 7506: 
1.394     bowersj2 7507: lonnet provides subroutines which interact with the
                   7508: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7509: about classes, users, and resources.
1.243     albertel 7510: 
                   7511: For many of these objects you can also use this to store data about
                   7512: them or modify them in various ways.
1.191     harris41 7513: 
1.394     bowersj2 7514: =head2 Symbs
1.191     harris41 7515: 
1.394     bowersj2 7516: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7517: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7518: map, the resource number of the resource in the map, and the URL of
                   7519: the resource itself. The latter is somewhat redundant, but might help
                   7520: if maps change.
                   7521: 
                   7522: An example is
                   7523: 
                   7524:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7525: 
                   7526: The respective map entry is
                   7527: 
                   7528:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7529:   title="Problem 2">
                   7530:  </resource>
                   7531: 
                   7532: Symbs are used by the random number generator, as well as to store and
                   7533: restore data specific to a certain instance of for example a problem.
                   7534: 
                   7535: =head2 Storing And Retrieving Data
                   7536: 
                   7537: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7538: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7539: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7540: is is the non-critical message twin of cstore. These functions are for
                   7541: handlers to store a perl hash to a user's permanent data space in an
                   7542: easy manner, and to retrieve it again on another call. It is expected
                   7543: that a handler would use this once at the beginning to retrieve data,
                   7544: and then again once at the end to send only the new data back.
                   7545: 
                   7546: The data is stored in the user's data directory on the user's
                   7547: homeserver under the ID of the course.
                   7548: 
                   7549: The hash that is returned by restore will have all of the previous
                   7550: value for all of the elements of the hash.
                   7551: 
                   7552: Example:
                   7553: 
                   7554:  #creating a hash
                   7555:  my %hash;
                   7556:  $hash{'foo'}='bar';
                   7557: 
                   7558:  #storing it
                   7559:  &Apache::lonnet::cstore(\%hash);
                   7560: 
                   7561:  #changing a value
                   7562:  $hash{'foo'}='notbar';
                   7563: 
                   7564:  #adding a new value
                   7565:  $hash{'bar'}='foo';
                   7566:  &Apache::lonnet::cstore(\%hash);
                   7567: 
                   7568:  #retrieving the hash
                   7569:  my %history=&Apache::lonnet::restore();
                   7570: 
                   7571:  #print the hash
                   7572:  foreach my $key (sort(keys(%history))) {
                   7573:    print("\%history{$key} = $history{$key}");
                   7574:  }
                   7575: 
                   7576: Will print out:
1.191     harris41 7577: 
1.394     bowersj2 7578:  %history{1:foo} = bar
                   7579:  %history{1:keys} = foo:timestamp
                   7580:  %history{1:timestamp} = 990455579
                   7581:  %history{2:bar} = foo
                   7582:  %history{2:foo} = notbar
                   7583:  %history{2:keys} = foo:bar:timestamp
                   7584:  %history{2:timestamp} = 990455580
                   7585:  %history{bar} = foo
                   7586:  %history{foo} = notbar
                   7587:  %history{timestamp} = 990455580
                   7588:  %history{version} = 2
                   7589: 
                   7590: Note that the special hash entries C<keys>, C<version> and
                   7591: C<timestamp> were added to the hash. C<version> will be equal to the
                   7592: total number of versions of the data that have been stored. The
                   7593: C<timestamp> attribute will be the UNIX time the hash was
                   7594: stored. C<keys> is available in every historical section to list which
                   7595: keys were added or changed at a specific historical revision of a
                   7596: hash.
                   7597: 
                   7598: B<Warning>: do not store the hash that restore returns directly. This
                   7599: will cause a mess since it will restore the historical keys as if the
                   7600: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7601: 
1.394     bowersj2 7602: Calling convention:
1.191     harris41 7603: 
1.394     bowersj2 7604:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7605:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7606: 
1.394     bowersj2 7607: For more detailed information, see lonnet specific documentation.
1.191     harris41 7608: 
1.394     bowersj2 7609: =head1 RETURN MESSAGES
1.191     harris41 7610: 
1.394     bowersj2 7611: =over 4
1.191     harris41 7612: 
1.394     bowersj2 7613: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7614: 
1.394     bowersj2 7615: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7616: when the connection is brought back up
1.191     harris41 7617: 
1.394     bowersj2 7618: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7619: for later delivery
1.191     harris41 7620: 
1.394     bowersj2 7621: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7622: 
1.394     bowersj2 7623: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7624: that was requested
1.191     harris41 7625: 
1.243     albertel 7626: =back
1.191     harris41 7627: 
1.243     albertel 7628: =head1 PUBLIC SUBROUTINES
1.191     harris41 7629: 
1.243     albertel 7630: =head2 Session Environment Functions
1.191     harris41 7631: 
1.243     albertel 7632: =over 4
1.191     harris41 7633: 
1.394     bowersj2 7634: =item * 
                   7635: X<appenv()>
                   7636: B<appenv(%hash)>: the value of %hash is written to
                   7637: the user envirnoment file, and will be restored for each access this
1.620     albertel 7638: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7639: process
1.191     harris41 7640: 
                   7641: =item *
1.394     bowersj2 7642: X<delenv()>
                   7643: B<delenv($regexp)>: removes all items from the session
                   7644: environment file that matches the regular expression in $regexp. The
1.620     albertel 7645: values are also delted from the current processes %env.
1.191     harris41 7646: 
1.795     albertel 7647: =item * get_env_multiple($name) 
                   7648: 
                   7649: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7650: values may be defined and end up as an array ref.
                   7651: 
                   7652: returns an array of values
                   7653: 
1.243     albertel 7654: =back
                   7655: 
                   7656: =head2 User Information
1.191     harris41 7657: 
1.243     albertel 7658: =over 4
1.191     harris41 7659: 
                   7660: =item *
1.394     bowersj2 7661: X<queryauthenticate()>
                   7662: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7663: authentication scheme
                   7664: 
                   7665: =item *
1.394     bowersj2 7666: X<authenticate()>
                   7667: B<authenticate($uname,$upass,$udom)>: try to
                   7668: authenticate user from domain's lib servers (first use the current
                   7669: one). C<$upass> should be the users password.
1.191     harris41 7670: 
                   7671: =item *
1.394     bowersj2 7672: X<homeserver()>
                   7673: B<homeserver($uname,$udom)>: find the server which has
                   7674: the user's directory and files (there must be only one), this caches
                   7675: the answer, and also caches if there is a borken connection.
1.191     harris41 7676: 
                   7677: =item *
1.394     bowersj2 7678: X<idget()>
                   7679: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7680: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7681: username, and only 1 username per ID in a specific domain) (returns
                   7682: hash: id=>name,id=>name)
1.191     harris41 7683: 
                   7684: =item *
1.394     bowersj2 7685: X<idrget()>
                   7686: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7687: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7688: 
                   7689: =item *
1.394     bowersj2 7690: X<idput()>
                   7691: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7692: 
                   7693: =item *
1.394     bowersj2 7694: X<rolesinit()>
                   7695: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7696: 
                   7697: =item *
1.551     albertel 7698: X<getsection()>
                   7699: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7700: course $cname, return section name/number or '' for "not in course"
                   7701: and '-1' for "no section"
                   7702: 
                   7703: =item *
1.394     bowersj2 7704: X<userenvironment()>
                   7705: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7706: passed in @what from the requested user's environment, returns a hash
                   7707: 
                   7708: =back
                   7709: 
                   7710: =head2 User Roles
                   7711: 
                   7712: =over 4
                   7713: 
                   7714: =item *
                   7715: 
                   7716: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7717: actions
                   7718:  F: full access
                   7719:  U,I,K: authentication modes (cxx only)
                   7720:  '': forbidden
                   7721:  1: user needs to choose course
                   7722:  2: browse allowed
1.766     albertel 7723:  A: passphrase authentication needed
1.243     albertel 7724: 
                   7725: =item *
                   7726: 
                   7727: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7728: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7729: and course level
                   7730: 
                   7731: =item *
                   7732: 
                   7733: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7734: explanation of a user role term
                   7735: 
                   7736: =back
                   7737: 
                   7738: =head2 User Modification
                   7739: 
                   7740: =over 4
                   7741: 
                   7742: =item *
                   7743: 
                   7744: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7745: user for the level given by URL.  Optional start and end dates (leave empty
                   7746: string or zero for "no date")
1.191     harris41 7747: 
                   7748: =item *
                   7749: 
1.243     albertel 7750: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7751: change a users, password, possible return values are: ok,
                   7752: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7753: refused
1.191     harris41 7754: 
                   7755: =item *
                   7756: 
1.243     albertel 7757: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7758: 
                   7759: =item *
                   7760: 
1.243     albertel 7761: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7762: modify user
1.191     harris41 7763: 
                   7764: =item *
                   7765: 
1.286     matthew  7766: modifystudent
                   7767: 
                   7768: modify a students enrollment and identification information.
                   7769: The course id is resolved based on the current users environment.  
                   7770: This means the envoking user must be a course coordinator or otherwise
                   7771: associated with a course.
                   7772: 
1.297     matthew  7773: This call is essentially a wrapper for lonnet::modifyuser and
                   7774: lonnet::modify_student_enrollment
1.286     matthew  7775: 
                   7776: Inputs: 
                   7777: 
                   7778: =over 4
                   7779: 
                   7780: =item B<$udom> Students loncapa domain
                   7781: 
                   7782: =item B<$uname> Students loncapa login name
                   7783: 
                   7784: =item B<$uid> Students id/student number
                   7785: 
                   7786: =item B<$umode> Students authentication mode
                   7787: 
                   7788: =item B<$upass> Students password
                   7789: 
                   7790: =item B<$first> Students first name
                   7791: 
                   7792: =item B<$middle> Students middle name
                   7793: 
                   7794: =item B<$last> Students last name
                   7795: 
                   7796: =item B<$gene> Students generation
                   7797: 
                   7798: =item B<$usec> Students section in course
                   7799: 
                   7800: =item B<$end> Unix time of the roles expiration
                   7801: 
                   7802: =item B<$start> Unix time of the roles start date
                   7803: 
                   7804: =item B<$forceid> If defined, allow $uid to be changed
                   7805: 
                   7806: =item B<$desiredhome> server to use as home server for student
                   7807: 
                   7808: =back
1.297     matthew  7809: 
                   7810: =item *
                   7811: 
                   7812: modify_student_enrollment
                   7813: 
                   7814: Change a students enrollment status in a class.  The environment variable
                   7815: 'role.request.course' must be defined for this function to proceed.
                   7816: 
                   7817: Inputs:
                   7818: 
                   7819: =over 4
                   7820: 
                   7821: =item $udom, students domain
                   7822: 
                   7823: =item $uname, students name
                   7824: 
                   7825: =item $uid, students user id
                   7826: 
                   7827: =item $first, students first name
                   7828: 
                   7829: =item $middle
                   7830: 
                   7831: =item $last
                   7832: 
                   7833: =item $gene
                   7834: 
                   7835: =item $usec
                   7836: 
                   7837: =item $end
                   7838: 
                   7839: =item $start
                   7840: 
                   7841: =back
                   7842: 
1.191     harris41 7843: 
                   7844: =item *
                   7845: 
1.243     albertel 7846: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7847: custom role; give a custom role to a user for the level given by URL.  Specify
                   7848: name and domain of role author, and role name
1.191     harris41 7849: 
                   7850: =item *
                   7851: 
1.243     albertel 7852: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7853: 
                   7854: =item *
                   7855: 
1.243     albertel 7856: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7857: 
                   7858: =back
                   7859: 
                   7860: =head2 Course Infomation
                   7861: 
                   7862: =over 4
1.191     harris41 7863: 
                   7864: =item *
                   7865: 
1.631     albertel 7866: coursedescription($courseid) : returns a hash of information about the
                   7867: specified course id, including all environment settings for the
                   7868: course, the description of the course will be in the hash under the
                   7869: key 'description'
1.191     harris41 7870: 
                   7871: =item *
                   7872: 
1.624     albertel 7873: resdata($name,$domain,$type,@which) : request for current parameter
                   7874: setting for a specific $type, where $type is either 'course' or 'user',
                   7875: @what should be a list of parameters to ask about. This routine caches
                   7876: answers for 5 minutes.
1.243     albertel 7877: 
                   7878: =back
                   7879: 
                   7880: =head2 Course Modification
                   7881: 
                   7882: =over 4
1.191     harris41 7883: 
                   7884: =item *
                   7885: 
1.243     albertel 7886: writecoursepref($courseid,%prefs) : write preferences (environment
                   7887: database) for a course
1.191     harris41 7888: 
                   7889: =item *
                   7890: 
1.243     albertel 7891: createcourse($udom,$description,$url) : make/modify course
                   7892: 
                   7893: =back
                   7894: 
                   7895: =head2 Resource Subroutines
                   7896: 
                   7897: =over 4
1.191     harris41 7898: 
                   7899: =item *
                   7900: 
1.243     albertel 7901: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7902: 
                   7903: =item *
                   7904: 
1.243     albertel 7905: repcopy($filename) : subscribes to the requested file, and attempts to
                   7906: replicate from the owning library server, Might return
1.607     raeburn  7907: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7908: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7909: resource. Expects the local filesystem pathname
                   7910: (/home/httpd/html/res/....)
                   7911: 
                   7912: =back
                   7913: 
                   7914: =head2 Resource Information
                   7915: 
                   7916: =over 4
1.191     harris41 7917: 
                   7918: =item *
                   7919: 
1.243     albertel 7920: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7921: a vairety of different possible values, $varname should be a request
                   7922: string, and the other parameters can be used to specify who and what
                   7923: one is asking about.
                   7924: 
                   7925: Possible values for $varname are environment.lastname (or other item
                   7926: from the envirnment hash), user.name (or someother aspect about the
                   7927: user), resource.0.maxtries (or some other part and parameter of a
                   7928: resource)
1.204     albertel 7929: 
                   7930: =item *
                   7931: 
1.243     albertel 7932: directcondval($number) : get current value of a condition; reads from a state
                   7933: string
1.204     albertel 7934: 
                   7935: =item *
                   7936: 
1.243     albertel 7937: condval($condidx) : value of condition index based on state
1.204     albertel 7938: 
                   7939: =item *
                   7940: 
1.243     albertel 7941: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7942: resource's metadata, $what should be either a specific key, or either
                   7943: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7944: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7945: 
                   7946: this function automatically caches all requests
1.191     harris41 7947: 
                   7948: =item *
                   7949: 
1.243     albertel 7950: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7951: network of library servers; returns file handle of where SQL and regex results
                   7952: will be stored for query
1.191     harris41 7953: 
                   7954: =item *
                   7955: 
1.243     albertel 7956: symbread($filename) : return symbolic list entry (filename argument optional);
                   7957: returns the data handle
1.191     harris41 7958: 
                   7959: =item *
                   7960: 
1.243     albertel 7961: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7962: a possible symb for the URL in $thisfn, and if is an encryypted
                   7963: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7964: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7965: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7966: 
1.191     harris41 7967: 
                   7968: =item *
                   7969: 
1.243     albertel 7970: symbclean($symb) : removes versions numbers from a symb, returns the
                   7971: cleaned symb
1.191     harris41 7972: 
                   7973: =item *
                   7974: 
1.243     albertel 7975: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7976: course map, user must be in a course for it to work.
1.191     harris41 7977: 
                   7978: =item *
                   7979: 
1.243     albertel 7980: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7981: 
                   7982: =item *
                   7983: 
1.243     albertel 7984: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7985: a random seed, all arguments are optional, if they aren't sent it uses the
                   7986: environment to derive them. Note: if symb isn't sent and it can't get one
                   7987: from &symbread it will use the current time as its return value
1.191     harris41 7988: 
                   7989: =item *
                   7990: 
1.243     albertel 7991: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7992: unfakeable, receipt
1.191     harris41 7993: 
                   7994: =item *
                   7995: 
1.620     albertel 7996: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7997: 
                   7998: =item *
                   7999: 
1.243     albertel 8000: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8001: 
                   8002: =item *
                   8003: 
1.243     albertel 8004: 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 8005: 
                   8006: =item *
                   8007: 
1.243     albertel 8008: 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 8009: 
                   8010: =item *
                   8011: 
1.243     albertel 8012: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8013: 
                   8014: =item *
                   8015: 
1.243     albertel 8016: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8017: forcing spreadsheet to reevaluate the resource scores next time.
                   8018: 
                   8019: =back
                   8020: 
                   8021: =head2 Storing/Retreiving Data
                   8022: 
                   8023: =over 4
1.191     harris41 8024: 
                   8025: =item *
                   8026: 
1.243     albertel 8027: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8028: for this url; hashref needs to be given and should be a \%hashname; the
                   8029: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8030: be derived from the env
1.191     harris41 8031: 
                   8032: =item *
                   8033: 
1.243     albertel 8034: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8035: uses critical subroutine
1.191     harris41 8036: 
                   8037: =item *
                   8038: 
1.243     albertel 8039: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8040: all args are optional
1.191     harris41 8041: 
                   8042: =item *
                   8043: 
1.717     albertel 8044: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8045: dumps the complete (or key matching regexp) namespace into a hash
                   8046: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8047: normally &store()ed into
                   8048: 
                   8049: $range should be either an integer '100' (give me the first 100
                   8050:                                            matching records)
                   8051:               or be  two integers sperated by a - with no spaces
                   8052:                  '30-50' (give me the 30th through the 50th matching
                   8053:                           records)
                   8054: 
                   8055: 
                   8056: =item *
                   8057: 
                   8058: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8059: replaces a &store() version of data with a replacement set of data
                   8060: for a particular resource in a namespace passed in the $storehash hash 
                   8061: reference
                   8062: 
                   8063: =item *
                   8064: 
1.243     albertel 8065: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8066: works very similar to store/cstore, but all data is stored in a
                   8067: temporary location and can be reset using tmpreset, $storehash should
                   8068: be a hash reference, returns nothing on success
1.191     harris41 8069: 
                   8070: =item *
                   8071: 
1.243     albertel 8072: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8073: similar to restore, but all data is stored in a temporary location and
                   8074: can be reset using tmpreset. Returns a hash of values on success,
                   8075: error string otherwise.
1.191     harris41 8076: 
                   8077: =item *
                   8078: 
1.243     albertel 8079: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8080: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8081: 
                   8082: =item *
                   8083: 
1.243     albertel 8084: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8085: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8086: 
                   8087: =item *
                   8088: 
1.243     albertel 8089: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8090: namesp ($udom and $uname are optional)
1.191     harris41 8091: 
                   8092: =item *
                   8093: 
1.702     albertel 8094: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8095: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8096: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8097: 
1.702     albertel 8098: $range should be either an integer '100' (give me the first 100
                   8099:                                            matching records)
                   8100:               or be  two integers sperated by a - with no spaces
                   8101:                  '30-50' (give me the 30th through the 50th matching
                   8102:                           records)
1.449     matthew  8103: =item *
                   8104: 
                   8105: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8106: $store can be a scalar, an array reference, or if the amount to be 
                   8107: incremented is > 1, a hash reference.
                   8108: 
                   8109: ($udom and $uname are optional)
1.191     harris41 8110: 
                   8111: =item *
                   8112: 
1.243     albertel 8113: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8114: ($udom and $uname are optional)
1.191     harris41 8115: 
                   8116: =item *
                   8117: 
1.243     albertel 8118: cput($namespace,$storehash,$udom,$uname) : critical put
                   8119: ($udom and $uname are optional)
1.191     harris41 8120: 
                   8121: =item *
                   8122: 
1.748     albertel 8123: newput($namespace,$storehash,$udom,$uname) :
                   8124: 
                   8125: Attempts to store the items in the $storehash, but only if they don't
                   8126: currently exist, if this succeeds you can be certain that you have 
                   8127: successfully created a new key value pair in the $namespace db.
                   8128: 
                   8129: 
                   8130: Args:
                   8131:  $namespace: name of database to store values to
                   8132:  $storehash: hashref to store to the db
                   8133:  $udom: (optional) domain of user containing the db
                   8134:  $uname: (optional) name of user caontaining the db
                   8135: 
                   8136: Returns:
                   8137:  'ok' -> succeeded in storing all keys of $storehash
                   8138:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8139:                         least <key> already existed in the db (other
                   8140:                         requested keys may also already exist)
                   8141:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8142:  'con_lost' -> unable to contact request server
                   8143:  'refused' -> action was not allowed by remote machine
                   8144: 
                   8145: 
                   8146: =item *
                   8147: 
1.243     albertel 8148: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8149: reference filled in from namesp (encrypts the return communication)
                   8150: ($udom and $uname are optional)
1.191     harris41 8151: 
                   8152: =item *
                   8153: 
1.243     albertel 8154: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8155: critical subroutine
                   8156: 
1.806     raeburn  8157: =item *
                   8158: 
                   8159: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8160: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8161: 
                   8162: =item *
                   8163: 
                   8164: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8165: 
1.243     albertel 8166: =back
                   8167: 
                   8168: =head2 Network Status Functions
                   8169: 
                   8170: =over 4
1.191     harris41 8171: 
                   8172: =item *
                   8173: 
                   8174: dirlist($uri) : return directory list based on URI
                   8175: 
                   8176: =item *
                   8177: 
1.243     albertel 8178: spareserver() : find server with least workload from spare.tab
                   8179: 
                   8180: =back
                   8181: 
                   8182: =head2 Apache Request
                   8183: 
                   8184: =over 4
1.191     harris41 8185: 
                   8186: =item *
                   8187: 
1.243     albertel 8188: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8189: localhost, posts hash
                   8190: 
                   8191: =back
                   8192: 
                   8193: =head2 Data to String to Data
                   8194: 
                   8195: =over 4
1.191     harris41 8196: 
                   8197: =item *
                   8198: 
1.243     albertel 8199: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8200: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8201: 
                   8202: =item *
                   8203: 
1.243     albertel 8204: hashref2str($hashref) : convert a hashref into a string complete with
                   8205: escaping and '=' and '&' separators, supports elements that are
                   8206: arrayrefs and hashrefs
1.191     harris41 8207: 
                   8208: =item *
                   8209: 
1.243     albertel 8210: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8211: with escaping and '&' separators, supports elements that are arrayrefs
                   8212: and hashrefs
1.191     harris41 8213: 
                   8214: =item *
                   8215: 
1.243     albertel 8216: str2hash($string) : convert string to hash using unescaping and
                   8217: splitting on '=' and '&', supports elements that are arrayrefs and
                   8218: hashrefs
1.191     harris41 8219: 
                   8220: =item *
                   8221: 
1.243     albertel 8222: str2array($string) : convert string to hash using unescaping and
                   8223: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8224: 
                   8225: =back
                   8226: 
                   8227: =head2 Logging Routines
                   8228: 
                   8229: =over 4
                   8230: 
                   8231: These routines allow one to make log messages in the lonnet.log and
                   8232: lonnet.perm logfiles.
1.191     harris41 8233: 
                   8234: =item *
                   8235: 
1.243     albertel 8236: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8237: 
                   8238: =item *
                   8239: 
1.243     albertel 8240: logthis() : append message to the normal lonnet.log file, it gets
                   8241: preiodically rolled over and deleted.
1.191     harris41 8242: 
                   8243: =item *
                   8244: 
1.243     albertel 8245: logperm() : append a permanent message to lonnet.perm.log, this log
                   8246: file never gets deleted by any automated portion of the system, only
                   8247: messages of critical importance should go in here.
                   8248: 
                   8249: =back
                   8250: 
                   8251: =head2 General File Helper Routines
                   8252: 
                   8253: =over 4
1.191     harris41 8254: 
                   8255: =item *
                   8256: 
1.481     raeburn  8257: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8258: (a) files in /uploaded
                   8259:   (i) If a local copy of the file exists - 
                   8260:       compares modification date of local copy with last-modified date for 
                   8261:       definitive version stored on home server for course. If local copy is 
                   8262:       stale, requests a new version from the home server and stores it. 
                   8263:       If the original has been removed from the home server, then local copy 
                   8264:       is unlinked.
                   8265:   (ii) If local copy does not exist -
                   8266:       requests the file from the home server and stores it. 
                   8267:   
                   8268:   If $caller is 'uploadrep':  
                   8269:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8270:     for request for files originally uploaded via DOCS. 
                   8271:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8272:   
                   8273:   Otherwise:
                   8274:      This indicates a call from the content generation phase of the request.
                   8275:      -  returns the entire contents of the file or -1.
                   8276:      
                   8277: (b) files in /res
                   8278:    - returns the entire contents of a file or -1; 
                   8279:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8280: 
1.712     albertel 8281: 
                   8282: =item *
                   8283: 
                   8284: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8285:                   reference
                   8286: 
                   8287: returns either a stat() list of data about the file or an empty list
                   8288: if the file doesn't exist or couldn't find out about it (connection
                   8289: problems or user unknown)
                   8290: 
1.191     harris41 8291: =item *
                   8292: 
1.243     albertel 8293: filelocation($dir,$file) : returns file system location of a file
                   8294: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8295: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8296: and a file of ../bob will become /a/bob)
1.191     harris41 8297: 
                   8298: =item *
                   8299: 
                   8300: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8301: filelocation except for hrefs
                   8302: 
                   8303: =item *
                   8304: 
                   8305: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8306: 
1.243     albertel 8307: =back
                   8308: 
1.608     albertel 8309: =head2 Usererfile file routines (/uploaded*)
                   8310: 
                   8311: =over 4
                   8312: 
                   8313: =item *
                   8314: 
                   8315: userfileupload(): main rotine for putting a file in a user or course's
                   8316:                   filespace, arguments are,
                   8317: 
1.620     albertel 8318:  formname - required - this is the name of the element in $env where the
1.608     albertel 8319:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8320:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8321:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8322:  coursedoc - if true, store the file in the course of the active role
                   8323:              of the current user
                   8324:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8325:          if undefined, it will be placed in "unknown"
                   8326: 
                   8327:  (This routine calls clean_filename() to remove any dangerous
                   8328:  characters from the filename, and then calls finuserfileupload() to
                   8329:  complete the transaction)
                   8330: 
                   8331:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8332:  and /adm/notfound.html if unsuccessful
                   8333: 
                   8334: =item *
                   8335: 
                   8336: clean_filename(): routine for cleaing a filename up for storage in
                   8337:                  userfile space, argument is:
                   8338: 
                   8339:  filename - proposed filename
                   8340: 
                   8341: returns: the new clean filename
                   8342: 
                   8343: =item *
                   8344: 
                   8345: finishuserfileupload(): routine that creaes and sends the file to
                   8346: userspace, probably shouldn't be called directly
                   8347: 
                   8348:   docuname: username or courseid of destination for the file
                   8349:   docudom: domain of user/course of destination for the file
                   8350:   formname: same as for userfileupload()
                   8351:   fname: filename (inculding subdirectories) for the file
                   8352: 
                   8353:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8354:  and /adm/notfound.html if unsuccessful
                   8355: 
                   8356: =item *
                   8357: 
                   8358: renameuserfile(): renames an existing userfile to a new name
                   8359: 
                   8360:   Args:
                   8361:    docuname: username or courseid of destination for the file
                   8362:    docudom: domain of user/course of destination for the file
                   8363:    old: current file name (including any subdirs under userfiles)
                   8364:    new: desired file name (including any subdirs under userfiles)
                   8365: 
                   8366: =item *
                   8367: 
                   8368: mkdiruserfile(): creates a directory is a userfiles dir
                   8369: 
                   8370:   Args:
                   8371:    docuname: username or courseid of destination for the file
                   8372:    docudom: domain of user/course of destination for the file
                   8373:    dir: dir to create (including any subdirs under userfiles)
                   8374: 
                   8375: =item *
                   8376: 
                   8377: removeuserfile(): removes a file that exists in userfiles
                   8378: 
                   8379:   Args:
                   8380:    docuname: username or courseid of destination for the file
                   8381:    docudom: domain of user/course of destination for the file
                   8382:    fname: filname to delete (including any subdirs under userfiles)
                   8383: 
                   8384: =item *
                   8385: 
                   8386: removeuploadedurl(): convience function for removeuserfile()
                   8387: 
                   8388:   Args:
                   8389:    url:  a full /uploaded/... url to delete
                   8390: 
1.747     albertel 8391: =item * 
                   8392: 
                   8393: get_portfile_permissions():
                   8394:   Args:
                   8395:     domain: domain of user or course contain the portfolio files
                   8396:     user: name of user or num of course contain the portfolio files
                   8397:   Returns:
                   8398:     hashref of a dump of the proper file_permissions.db
                   8399:    
                   8400: 
                   8401: =item * 
                   8402: 
                   8403: get_access_controls():
                   8404: 
                   8405: Args:
                   8406:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8407:   group: (optional) the group you want the files associated with
                   8408:   file: (optional) the file you want access info on
                   8409: 
                   8410: Returns:
1.749     raeburn  8411:     a hash (keys are file names) of hashes containing
                   8412:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8413:         values are XML containing access control settings (see below) 
1.747     albertel 8414: 
                   8415: Internal notes:
                   8416: 
1.749     raeburn  8417:  access controls are stored in file_permissions.db as key=value pairs.
                   8418:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8419:         where scope -> public,guest,course,group,domains or users.
                   8420:               end -> UNIX time for end of access (0 -> no end date)
                   8421:               start -> UNIX time for start of access
                   8422: 
                   8423:     value -> XML description of access control
                   8424:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8425:             <start></start>
                   8426:             <end></end>
                   8427: 
                   8428:             <password></password>  for scope type = guest
                   8429: 
                   8430:             <domain></domain>     for scope type = course or group
                   8431:             <number></number>
                   8432:             <roles id="">
                   8433:              <role></role>
                   8434:              <access></access>
                   8435:              <section></section>
                   8436:              <group></group>
                   8437:             </roles>
                   8438: 
                   8439:             <dom></dom>         for scope type = domains
                   8440: 
                   8441:             <users>             for scope type = users
                   8442:              <user>
                   8443:               <uname></uname>
                   8444:               <udom></udom>
                   8445:              </user>
                   8446:             </users>
                   8447:            </scope> 
                   8448:               
                   8449:  Access data is also aggregated for each file in an additional key=value pair:
                   8450:  key -> path to file/file_name\0accesscontrol 
                   8451:  value -> reference to hash
                   8452:           hash contains key = value pairs
                   8453:           where key = uniqueID:scope_end_start
                   8454:                 value = UNIX time record was last updated
                   8455: 
                   8456:           Used to improve speed of look-ups of access controls for each file.  
                   8457:  
                   8458:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8459: 
                   8460: modify_access_controls():
                   8461: 
                   8462: Modifies access controls for a portfolio file
                   8463: Args
                   8464: 1. file name
                   8465: 2. reference to hash of required changes,
                   8466: 3. domain
                   8467: 4. username
                   8468:   where domain,username are the domain of the portfolio owner 
                   8469:   (either a user or a course) 
                   8470: 
                   8471: Returns:
                   8472: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8473: 2. result of deletions ('ok' or 'error', with error message).
                   8474: 3. reference to hash of any new or updated access controls.
                   8475: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8476:    key = integer (inbound ID)
                   8477:    value = uniqueID  
1.747     albertel 8478: 
1.608     albertel 8479: =back
                   8480: 
1.243     albertel 8481: =head2 HTTP Helper Routines
                   8482: 
                   8483: =over 4
                   8484: 
1.191     harris41 8485: =item *
                   8486: 
                   8487: escape() : unpack non-word characters into CGI-compatible hex codes
                   8488: 
                   8489: =item *
                   8490: 
                   8491: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8492: 
1.243     albertel 8493: =back
                   8494: 
                   8495: =head1 PRIVATE SUBROUTINES
                   8496: 
                   8497: =head2 Underlying communication routines (Shouldn't call)
                   8498: 
                   8499: =over 4
                   8500: 
                   8501: =item *
                   8502: 
                   8503: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8504: 
                   8505: =item *
                   8506: 
                   8507: reply() : uses subreply to send a message to remote machine, logs all failures
                   8508: 
                   8509: =item *
                   8510: 
                   8511: critical() : passes a critical message to another server; if cannot
                   8512: get through then place message in connection buffer directory and
                   8513: returns con_delayed, if incapable of saving message, returns
                   8514: con_failed
                   8515: 
                   8516: =item *
                   8517: 
                   8518: reconlonc() : tries to reconnect lonc client processes.
                   8519: 
                   8520: =back
                   8521: 
                   8522: =head2 Resource Access Logging
                   8523: 
                   8524: =over 4
                   8525: 
                   8526: =item *
                   8527: 
                   8528: flushcourselogs() : flush (save) buffer logs and access logs
                   8529: 
                   8530: =item *
                   8531: 
                   8532: courselog($what) : save message for course in hash
                   8533: 
                   8534: =item *
                   8535: 
                   8536: courseacclog($what) : save message for course using &courselog().  Perform
                   8537: special processing for specific resource types (problems, exams, quizzes, etc).
                   8538: 
1.191     harris41 8539: =item *
                   8540: 
                   8541: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8542: as a PerlChildExitHandler
1.243     albertel 8543: 
                   8544: =back
                   8545: 
                   8546: =head2 Other
                   8547: 
                   8548: =over 4
                   8549: 
                   8550: =item *
                   8551: 
                   8552: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8553: 
                   8554: =back
                   8555: 
                   8556: =cut

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