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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.813   ! albertel    4: # $Id: lonnet.pm,v 1.812 2006/12/04 16:24:11 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.205     www       193:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  194:     my $answer=subreply($cmd,$server);
1.65      www       195:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  196:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       197:                 " $cmd to $server returned $answer</font>");
                    198:     }
1.1       albertel  199:     return $answer;
                    200: }
                    201: 
                    202: # ----------------------------------------------------------- Send USR1 to lonc
                    203: 
                    204: sub reconlonc {
                    205:     my $peerfile=shift;
                    206:     &logthis("Trying to reconnect for $peerfile");
                    207:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  208:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  209: 	my $loncpid=<$fh>;
                    210:         chomp($loncpid);
                    211:         if (kill 0 => $loncpid) {
                    212: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    213:             kill USR1 => $loncpid;
                    214:             sleep 1;
                    215:             if (-e "$peerfile") { return; }
                    216:             &logthis("$peerfile still not there, give it another try");
                    217:             sleep 5;
                    218:             if (-e "$peerfile") { return; }
1.12      www       219:             &logthis(
1.672     albertel  220:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  221:         } else {
1.12      www       222: 	    &logthis(
1.672     albertel  223:                "<font color=\"blue\">WARNING:".
1.12      www       224:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  225:         }
                    226:     } else {
1.672     albertel  227:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  228:     }
                    229: }
                    230: 
                    231: # ------------------------------------------------------ Critical communication
1.12      www       232: 
1.1       albertel  233: sub critical {
                    234:     my ($cmd,$server)=@_;
1.89      www       235:     unless ($hostname{$server}) {
1.672     albertel  236:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       237:                " Critical message to unknown server ($server)</font>");
                    238:         return 'no_such_host';
                    239:     }
1.1       albertel  240:     my $answer=reply($cmd,$server);
                    241:     if ($answer eq 'con_lost') {
                    242: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  243: 	my $answer=reply($cmd,$server);
1.1       albertel  244:         if ($answer eq 'con_lost') {
                    245:             my $now=time;
                    246:             my $middlename=$cmd;
1.5       www       247:             $middlename=substr($middlename,0,16);
1.1       albertel  248:             $middlename=~s/\W//g;
                    249:             my $dfilename=
1.305     www       250:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    251:             $dumpcount++;
1.1       albertel  252:             {
1.448     albertel  253: 		my $dfh;
                    254: 		if (open($dfh,">$dfilename")) {
                    255: 		    print $dfh "$cmd\n"; 
                    256: 		    close($dfh);
                    257: 		}
1.1       albertel  258:             }
                    259:             sleep 2;
                    260:             my $wcmd='';
                    261:             {
1.448     albertel  262: 		my $dfh;
                    263: 		if (open($dfh,"<$dfilename")) {
                    264: 		    $wcmd=<$dfh>; 
                    265: 		    close($dfh);
                    266: 		}
1.1       albertel  267:             }
                    268:             chomp($wcmd);
1.7       www       269:             if ($wcmd eq $cmd) {
1.672     albertel  270: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       271:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  272:                 &logperm("D:$server:$cmd");
                    273: 	        return 'con_delayed';
                    274:             } else {
1.672     albertel  275:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       276:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  277:                 &logperm("F:$server:$cmd");
                    278:                 return 'con_failed';
                    279:             }
                    280:         }
                    281:     }
                    282:     return $answer;
1.405     albertel  283: }
                    284: 
1.755     albertel  285: # ------------------------------------------- check if return value is an error
                    286: 
                    287: sub error {
                    288:     my ($result) = @_;
1.756     albertel  289:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  290: 	if ($2 == 2) { return undef; }
                    291: 	return $1;
                    292:     }
                    293:     return undef;
                    294: }
                    295: 
1.783     albertel  296: sub convert_and_load_session_env {
                    297:     my ($lonidsdir,$handle)=@_;
                    298:     my @profile;
                    299:     {
                    300: 	open(my $idf,"$lonidsdir/$handle.id");
                    301: 	flock($idf,LOCK_SH);
                    302: 	@profile=<$idf>;
                    303: 	close($idf);
                    304:     }
                    305:     my %temp_env;
                    306:     foreach my $line (@profile) {
1.786     albertel  307: 	if ($line !~ m/=/) {
                    308: 	    return 0;
                    309: 	}
1.783     albertel  310: 	chomp($line);
                    311: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    312: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    313:     }
                    314:     unlink("$lonidsdir/$handle.id");
                    315:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    316: 	    0640)) {
                    317: 	%disk_env = %temp_env;
                    318: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    319: 	untie(%disk_env);
                    320:     }
1.786     albertel  321:     return 1;
1.783     albertel  322: }
                    323: 
1.374     www       324: # ------------------------------------------- Transfer profile into environment
1.780     albertel  325: my $env_loaded;
                    326: sub transfer_profile_to_env {
1.788     albertel  327:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    328:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       329: 
1.720     albertel  330:     if (!defined($lonidsdir)) {
                    331: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    332:     }
                    333:     if (!defined($handle)) {
                    334:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    335:     }
                    336: 
1.786     albertel  337:     my $convert;
                    338:     {
                    339:     	open(my $idf,"$lonidsdir/$handle.id");
                    340: 	flock($idf,LOCK_SH);
                    341: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    342: 		&GDBM_READER(),0640)) {
                    343: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    344: 	    untie(%disk_env);
                    345: 	} else {
                    346: 	    $convert = 1;
                    347: 	}
                    348:     }
                    349:     if ($convert) {
                    350: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    351: 	    &logthis("Failed to load session, or convert session.");
                    352: 	}
1.374     www       353:     }
1.783     albertel  354: 
1.786     albertel  355:     my %remove;
1.783     albertel  356:     while ( my $envname = each(%env) ) {
1.433     matthew   357:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    358:             if ($time < time-300) {
1.783     albertel  359:                 $remove{$key}++;
1.433     matthew   360:             }
                    361:         }
                    362:     }
1.783     albertel  363: 
1.619     albertel  364:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  365:     $env_loaded=1;
1.783     albertel  366:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   367:         &delenv($expired_key);
1.374     www       368:     }
1.1       albertel  369: }
                    370: 
1.5       www       371: # ---------------------------------------------------------- Append Environment
                    372: 
                    373: sub appenv {
1.6       www       374:     my %newenv=@_;
1.692     albertel  375:     foreach my $key (keys(%newenv)) {
                    376: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  377:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  378:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       379:                 .'</font>');
1.692     albertel  380: 	    delete($newenv{$key});
1.35      www       381:         } else {
1.692     albertel  382:             $env{$key}=$newenv{$key};
1.35      www       383:         }
1.191     harris41  384:     }
1.783     albertel  385:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    386: 	    0640)) {
                    387: 	while (my ($key,$value) = each(%newenv)) {
                    388: 	    $disk_env{$key} = $value;
1.448     albertel  389: 	}
1.783     albertel  390: 	untie(%disk_env);
1.56      www       391:     }
                    392:     return 'ok';
                    393: }
                    394: # ----------------------------------------------------- Delete from Environment
                    395: 
                    396: sub delenv {
                    397:     my $delthis=shift;
                    398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  399:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       400:                 "Attempt to delete from environment ".$delthis);
                    401:         return 'error';
                    402:     }
1.783     albertel  403:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    404: 	    0640)) {
                    405: 	foreach my $key (keys(%disk_env)) {
                    406: 	    if ($key=~/^$delthis/) { 
1.619     albertel  407:                 delete($env{$key});
1.783     albertel  408:                 delete($disk_env{$key});
1.473     matthew   409:             }
1.448     albertel  410: 	}
1.783     albertel  411: 	untie(%disk_env);
1.5       www       412:     }
                    413:     return 'ok';
1.369     albertel  414: }
                    415: 
1.790     albertel  416: sub get_env_multiple {
                    417:     my ($name) = @_;
                    418:     my @values;
                    419:     if (defined($env{$name})) {
                    420:         # exists is it an array
                    421:         if (ref($env{$name})) {
                    422:             @values=@{ $env{$name} };
                    423:         } else {
                    424:             $values[0]=$env{$name};
                    425:         }
                    426:     }
                    427:     return(@values);
                    428: }
                    429: 
1.369     albertel  430: # ------------------------------------------ Find out current server userload
                    431: # there is a copy in lond
                    432: sub userload {
                    433:     my $numusers=0;
                    434:     {
                    435: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    436: 	my $filename;
                    437: 	my $curtime=time;
                    438: 	while ($filename=readdir(LONIDS)) {
                    439: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  440: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  441: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  442: 	}
                    443: 	closedir(LONIDS);
                    444:     }
                    445:     my $userloadpercent=0;
                    446:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    447:     if ($maxuserload) {
1.371     albertel  448: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  449:     }
1.372     albertel  450:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  451:     return $userloadpercent;
1.283     www       452: }
                    453: 
                    454: # ------------------------------------------ Fight off request when overloaded
                    455: 
                    456: sub overloaderror {
                    457:     my ($r,$checkserver)=@_;
                    458:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    459:     my $loadavg;
                    460:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  461:        open(my $loadfile,'/proc/loadavg');
1.283     www       462:        $loadavg=<$loadfile>;
                    463:        $loadavg =~ s/\s.*//g;
1.285     matthew   464:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  465:        close($loadfile);
1.283     www       466:     } else {
                    467:        $loadavg=&reply('load',$checkserver);
                    468:     }
1.285     matthew   469:     my $overload=$loadavg-100;
1.283     www       470:     if ($overload>0) {
1.285     matthew   471: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       472:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       473:         return 413;
1.283     www       474:     }    
                    475:     return '';
1.5       www       476: }
1.1       albertel  477: 
                    478: # ------------------------------ Find server with least workload from spare.tab
1.11      www       479: 
1.1       albertel  480: sub spareserver {
1.670     albertel  481:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  482:     my $spare_server;
1.370     albertel  483:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  484:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    485:                                                      :  $userloadpercent;
                    486:     
                    487:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    488: 	($spare_server, $lowest_load) =
                    489: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    490:     }
                    491: 
                    492:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    493: 
                    494:     if (!$found_server) {
                    495: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    496: 	    ($spare_server, $lowest_load) =
                    497: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    498: 	}
                    499:     }
                    500: 
                    501:     if (!$want_server_name) {
                    502: 	$spare_server="http://$hostname{$spare_server}";
                    503:     }
                    504:     return $spare_server;
                    505: }
                    506: 
                    507: sub compare_server_load {
                    508:     my ($try_server, $spare_server, $lowest_load) = @_;
                    509: 
                    510:     my $loadans     = &reply('load',    $try_server);
                    511:     my $userloadans = &reply('userload',$try_server);
                    512: 
                    513:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    514: 	next; #didn't get a number from the server
                    515:     }
                    516: 
                    517:     my $load;
                    518:     if ($loadans =~ /\d/) {
                    519: 	if ($userloadans =~ /\d/) {
                    520: 	    #both are numbers, pick the bigger one
                    521: 	    $load = ($loadans > $userloadans) ? $loadans 
                    522: 		                              : $userloadans;
1.411     albertel  523: 	} else {
1.784     albertel  524: 	    $load = $loadans;
1.411     albertel  525: 	}
1.784     albertel  526:     } else {
                    527: 	$load = $userloadans;
                    528:     }
                    529: 
                    530:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    531: 	$spare_server = $try_server;
                    532: 	$lowest_load  = $load;
1.370     albertel  533:     }
1.784     albertel  534:     return ($spare_server,$lowest_load);
1.202     matthew   535: }
                    536: # --------------------------------------------- Try to change a user's password
                    537: 
                    538: sub changepass {
1.799     raeburn   539:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   540:     $currentpass = &escape($currentpass);
                    541:     $newpass     = &escape($newpass);
1.799     raeburn   542:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   543: 		       $server);
                    544:     if (! $answer) {
                    545: 	&logthis("No reply on password change request to $server ".
                    546: 		 "by $uname in domain $udom.");
                    547:     } elsif ($answer =~ "^ok") {
                    548:         &logthis("$uname in $udom successfully changed their password ".
                    549: 		 "on $server.");
                    550:     } elsif ($answer =~ "^pwchange_failure") {
                    551: 	&logthis("$uname in $udom was unable to change their password ".
                    552: 		 "on $server.  The action was blocked by either lcpasswd ".
                    553: 		 "or pwchange");
                    554:     } elsif ($answer =~ "^non_authorized") {
                    555:         &logthis("$uname in $udom did not get their password correct when ".
                    556: 		 "attempting to change it on $server.");
                    557:     } elsif ($answer =~ "^auth_mode_error") {
                    558:         &logthis("$uname in $udom attempted to change their password despite ".
                    559: 		 "not being locally or internally authenticated on $server.");
                    560:     } elsif ($answer =~ "^unknown_user") {
                    561:         &logthis("$uname in $udom attempted to change their password ".
                    562: 		 "on $server but were unable to because $server is not ".
                    563: 		 "their home server.");
                    564:     } elsif ($answer =~ "^refused") {
                    565: 	&logthis("$server refused to change $uname in $udom password because ".
                    566: 		 "it was sent an unencrypted request to change the password.");
                    567:     }
                    568:     return $answer;
1.1       albertel  569: }
                    570: 
1.169     harris41  571: # ----------------------- Try to determine user's current authentication scheme
                    572: 
                    573: sub queryauthenticate {
                    574:     my ($uname,$udom)=@_;
1.456     albertel  575:     my $uhome=&homeserver($uname,$udom);
                    576:     if (!$uhome) {
                    577: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    578: 	return 'no_host';
                    579:     }
                    580:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    581:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    582: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  583:     }
1.456     albertel  584:     return $answer;
1.169     harris41  585: }
                    586: 
1.1       albertel  587: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       588: 
1.1       albertel  589: sub authenticate {
                    590:     my ($uname,$upass,$udom)=@_;
1.807     albertel  591:     $upass=&escape($upass);
                    592:     $uname= &LONCAPA::clean_username($uname);
1.471     albertel  593:     my $uhome=&homeserver($uname,$udom);
                    594:     if (!$uhome) {
                    595: 	&logthis("User $uname at $udom is unknown in authenticate");
                    596: 	return 'no_host';
1.1       albertel  597:     }
1.471     albertel  598:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    599:     if ($answer eq 'authorized') {
                    600: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    601: 	return $uhome; 
                    602:     }
                    603:     if ($answer eq 'non_authorized') {
                    604: 	&logthis("User $uname at $udom rejected by $uhome");
                    605: 	return 'no_host'; 
1.9       www       606:     }
1.471     albertel  607:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  608:     return 'no_host';
                    609: }
                    610: 
                    611: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       612: 
1.599     albertel  613: my %homecache;
1.1       albertel  614: sub homeserver {
1.230     stredwic  615:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  616:     my $index="$uname:$udom";
1.426     albertel  617: 
1.599     albertel  618:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  619:     my $tryserver;
                    620:     foreach $tryserver (keys %libserv) {
1.230     stredwic  621:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  622: 		 exists($badServerCache{$tryserver}));
1.1       albertel  623: 	if ($hostdom{$tryserver} eq $udom) {
                    624:            my $answer=reply("home:$udom:$uname",$tryserver);
                    625:            if ($answer eq 'found') { 
1.599     albertel  626: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  627:            } elsif ($answer eq 'no_host') {
                    628: 	       $badServerCache{$tryserver}=1;
1.221     matthew   629:            }
1.1       albertel  630:        }
                    631:     }    
                    632:     return 'no_host';
1.70      www       633: }
                    634: 
                    635: # ------------------------------------- Find the usernames behind a list of IDs
                    636: 
                    637: sub idget {
                    638:     my ($udom,@ids)=@_;
                    639:     my %returnhash=();
                    640:     
                    641:     my $tryserver;
                    642:     foreach $tryserver (keys %libserv) {
                    643:        if ($hostdom{$tryserver} eq $udom) {
                    644: 	  my $idlist=join('&',@ids);
                    645:           $idlist=~tr/A-Z/a-z/; 
                    646: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    647:           my @answer=();
1.76      www       648:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       649: 	      @answer=split(/\&/,$reply);
                    650:           }                    ;
                    651:           my $i;
                    652:           for ($i=0;$i<=$#ids;$i++) {
                    653:               if ($answer[$i]) {
                    654: 		  $returnhash{$ids[$i]}=$answer[$i];
                    655:               } 
                    656:           }
                    657:        }
                    658:     }    
                    659:     return %returnhash;
                    660: }
                    661: 
                    662: # ------------------------------------- Find the IDs behind a list of usernames
                    663: 
                    664: sub idrget {
                    665:     my ($udom,@unames)=@_;
                    666:     my %returnhash=();
1.800     albertel  667:     foreach my $uname (@unames) {
                    668:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  669:     }
1.70      www       670:     return %returnhash;
                    671: }
                    672: 
                    673: # ------------------------------- Store away a list of names and associated IDs
                    674: 
                    675: sub idput {
                    676:     my ($udom,%ids)=@_;
                    677:     my %servers=();
1.800     albertel  678:     foreach my $uname (keys(%ids)) {
                    679: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    680:         my $uhom=&homeserver($uname,$udom);
1.70      www       681:         if ($uhom ne 'no_host') {
1.800     albertel  682:             my $id=&escape($ids{$uname});
1.70      www       683:             $id=~tr/A-Z/a-z/;
1.800     albertel  684:             my $esc_unam=&escape($uname);
1.70      www       685: 	    if ($servers{$uhom}) {
1.800     albertel  686: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       687:             } else {
1.800     albertel  688:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       689:             }
                    690:         }
1.191     harris41  691:     }
1.800     albertel  692:     foreach my $server (keys(%servers)) {
                    693:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  694:     }
1.344     www       695: }
                    696: 
1.806     raeburn   697: # ------------------------------------------- get items from domain db files   
                    698: 
                    699: sub get_dom {
                    700:     my ($namespace,$storearr,$udom)=@_;
                    701:     my $items='';
                    702:     foreach my $item (@$storearr) {
                    703:         $items.=&escape($item).'&';
                    704:     }
                    705:     $items=~s/\&$//;
                    706:     if (!$udom) { $udom=$env{'user.domain'}; }
                    707:     if (exists($domain_primary{$udom})) {
                    708:         my $uhome=$domain_primary{$udom};
                    709:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    710:         my @pairs=split(/\&/,$rep);
                    711:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    712:             return @pairs;
                    713:         }
                    714:         my %returnhash=();
                    715:         my $i=0;
                    716:         foreach my $item (@$storearr) {
                    717:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    718:             $i++;
                    719:         }
                    720:         return %returnhash;
                    721:     } else {
                    722:         &logthis("get_dom failed - no primary domain server for $udom");
                    723:     }
                    724: }
                    725: 
                    726: # -------------------------------------------- put items in domain db files 
                    727: 
                    728: sub put_dom {
                    729:     my ($namespace,$storehash,$udom)=@_;
                    730:     if (!$udom) { $udom=$env{'user.domain'}; }
                    731:     if (exists($domain_primary{$udom})) {
                    732:         my $uhome=$domain_primary{$udom};
                    733:         my $items='';
                    734:         foreach my $item (keys(%$storehash)) {
                    735:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    736:         }
                    737:         $items=~s/\&$//;
                    738:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    739:     } else {
                    740:         &logthis("put_dom failed - no primary domain server for $udom");
                    741:     }
                    742: }
                    743: 
1.344     www       744: # --------------------------------------------------- Assign a key to a student
                    745: 
                    746: sub assign_access_key {
1.364     www       747: #
                    748: # a valid key looks like uname:udom#comments
                    749: # comments are being appended
                    750: #
1.498     www       751:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    752:     $kdom=
1.620     albertel  753:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       754:     $knum=
1.620     albertel  755:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       756:     $cdom=
1.620     albertel  757:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       758:     $cnum=
1.620     albertel  759:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    760:     $udom=$env{'user.name'} unless (defined($udom));
                    761:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       762:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       763:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  764:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       765:                                                   # assigned to this person
                    766:                                                   # - this should not happen,
1.345     www       767:                                                   # unless something went wrong
                    768:                                                   # the first time around
                    769: # ready to assign
1.364     www       770:         $logentry=$1.'; '.$logentry;
1.496     www       771:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       772:                                                  $kdom,$knum) eq 'ok') {
1.345     www       773: # key now belongs to user
1.346     www       774: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       775:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    776:                 &appenv('environment.'.$envkey => $ckey);
                    777:                 return 'ok';
                    778:             } else {
                    779:                 return 
                    780:   'error: Count not permanently assign key, will need to be re-entered later.';
                    781: 	    }
                    782:         } else {
                    783:             return 'error: Could not assign key, try again later.';
                    784:         }
1.364     www       785:     } elsif (!$existing{$ckey}) {
1.345     www       786: # the key does not exist
                    787: 	return 'error: The key does not exist';
                    788:     } else {
                    789: # the key is somebody else's
                    790: 	return 'error: The key is already in use';
                    791:     }
1.344     www       792: }
                    793: 
1.364     www       794: # ------------------------------------------ put an additional comment on a key
                    795: 
                    796: sub comment_access_key {
                    797: #
                    798: # a valid key looks like uname:udom#comments
                    799: # comments are being appended
                    800: #
                    801:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    802:     $cdom=
1.620     albertel  803:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       804:     $cnum=
1.620     albertel  805:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       806:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    807:     if ($existing{$ckey}) {
                    808:         $existing{$ckey}.='; '.$logentry;
                    809: # ready to assign
1.367     www       810:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       811:                                                  $cdom,$cnum) eq 'ok') {
                    812: 	    return 'ok';
                    813:         } else {
                    814: 	    return 'error: Count not store comment.';
                    815:         }
                    816:     } else {
                    817: # the key does not exist
                    818: 	return 'error: The key does not exist';
                    819:     }
                    820: }
                    821: 
1.344     www       822: # ------------------------------------------------------ Generate a set of keys
                    823: 
                    824: sub generate_access_keys {
1.364     www       825:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       826:     $cdom=
1.620     albertel  827:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       828:     $cnum=
1.620     albertel  829:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       830:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       831:     unless (($cdom) && ($cnum)) { return 0; }
                    832:     if ($number>10000) { return 0; }
                    833:     sleep(2); # make sure don't get same seed twice
                    834:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    835:     my $total=0;
                    836:     for (my $i=1;$i<=$number;$i++) {
                    837:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    838:                   sprintf("%lx",int(100000*rand)).'-'.
                    839:                   sprintf("%lx",int(100000*rand));
                    840:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    841:        $newkey=~s/0/h/g; # and also 0 and O
                    842:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    843:        if ($existing{$newkey}) {
                    844:            $i--;
                    845:        } else {
1.364     www       846: 	  if (&put('accesskeys',
                    847:               { $newkey => '# generated '.localtime().
1.620     albertel  848:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       849:                            '; '.$logentry },
                    850: 		   $cdom,$cnum) eq 'ok') {
1.344     www       851:               $total++;
                    852: 	  }
                    853:        }
                    854:     }
1.620     albertel  855:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       856:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    857:     return $total;
                    858: }
                    859: 
                    860: # ------------------------------------------------------- Validate an accesskey
                    861: 
                    862: sub validate_access_key {
                    863:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    864:     $cdom=
1.620     albertel  865:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       866:     $cnum=
1.620     albertel  867:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    868:     $udom=$env{'user.domain'} unless (defined($udom));
                    869:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       870:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  871:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       872: }
                    873: 
                    874: # ------------------------------------- Find the section of student in a course
1.652     albertel  875: sub devalidate_getsection_cache {
                    876:     my ($udom,$unam,$courseid)=@_;
                    877:     my $hashid="$udom:$unam:$courseid";
                    878:     &devalidate_cache_new('getsection',$hashid);
                    879: }
1.298     matthew   880: 
                    881: sub getsection {
                    882:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  883:     my $cachetime=1800;
1.551     albertel  884: 
                    885:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  886:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  887:     if (defined($cached)) { return $result; }
                    888: 
1.298     matthew   889:     my %Pending; 
                    890:     my %Expired;
                    891:     #
                    892:     # Each role can either have not started yet (pending), be active, 
                    893:     #    or have expired.
                    894:     #
                    895:     # If there is an active role, we are done.
                    896:     #
                    897:     # If there is more than one role which has not started yet, 
                    898:     #     choose the one which will start sooner
                    899:     # If there is one role which has not started yet, return it.
                    900:     #
                    901:     # If there is more than one expired role, choose the one which ended last.
                    902:     # If there is a role which has expired, return it.
                    903:     #
1.800     albertel  904:     foreach my $line (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    905: 					&homeserver($unam,$udom)))) {
                    906:         my ($key,$value)=split(/\=/,$line,2);
1.298     matthew   907:         $key=&unescape($key);
1.479     albertel  908:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   909:         my $section=$1;
                    910:         if ($key eq $courseid.'_st') { $section=''; }
                    911:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    912:         my $now=time;
1.548     albertel  913:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   914:             $Expired{$end}=$section;
                    915:             next;
                    916:         }
1.548     albertel  917:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   918:             $Pending{$start}=$section;
                    919:             next;
                    920:         }
1.599     albertel  921:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   922:     }
                    923:     #
                    924:     # Presumedly there will be few matching roles from the above
                    925:     # loop and the sorting time will be negligible.
                    926:     if (scalar(keys(%Pending))) {
                    927:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  928:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   929:     } 
                    930:     if (scalar(keys(%Expired))) {
                    931:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    932:         my $time = pop(@sorted);
1.599     albertel  933:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   934:     }
1.599     albertel  935:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   936: }
1.70      www       937: 
1.599     albertel  938: sub save_cache {
                    939:     &purge_remembered();
1.722     albertel  940:     #&Apache::loncommon::validate_page();
1.620     albertel  941:     undef(%env);
1.780     albertel  942:     undef($env_loaded);
1.599     albertel  943: }
1.452     albertel  944: 
1.599     albertel  945: my $to_remember=-1;
                    946: my %remembered;
                    947: my %accessed;
                    948: my $kicks=0;
                    949: my $hits=0;
                    950: sub devalidate_cache_new {
                    951:     my ($name,$id,$debug) = @_;
                    952:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    953:     $id=&escape($name.':'.$id);
                    954:     $memcache->delete($id);
                    955:     delete($remembered{$id});
                    956:     delete($accessed{$id});
                    957: }
                    958: 
                    959: sub is_cached_new {
                    960:     my ($name,$id,$debug) = @_;
                    961:     $id=&escape($name.':'.$id);
                    962:     if (exists($remembered{$id})) {
                    963: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    964: 	$accessed{$id}=[&gettimeofday()];
                    965: 	$hits++;
                    966: 	return ($remembered{$id},1);
                    967:     }
                    968:     my $value = $memcache->get($id);
                    969:     if (!(defined($value))) {
                    970: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  971: 	return (undef,undef);
1.416     albertel  972:     }
1.599     albertel  973:     if ($value eq '__undef__') {
                    974: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    975: 	$value=undef;
                    976:     }
                    977:     &make_room($id,$value,$debug);
                    978:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    979:     return ($value,1);
                    980: }
                    981: 
                    982: sub do_cache_new {
                    983:     my ($name,$id,$value,$time,$debug) = @_;
                    984:     $id=&escape($name.':'.$id);
                    985:     my $setvalue=$value;
                    986:     if (!defined($setvalue)) {
                    987: 	$setvalue='__undef__';
                    988:     }
1.623     albertel  989:     if (!defined($time) ) {
                    990: 	$time=600;
                    991:     }
1.599     albertel  992:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  993:     $memcache->set($id,$setvalue,$time);
                    994:     # need to make a copy of $value
                    995:     #&make_room($id,$value,$debug);
1.599     albertel  996:     return $value;
                    997: }
                    998: 
                    999: sub make_room {
                   1000:     my ($id,$value,$debug)=@_;
                   1001:     $remembered{$id}=$value;
                   1002:     if ($to_remember<0) { return; }
                   1003:     $accessed{$id}=[&gettimeofday()];
                   1004:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1005:     my $to_kick;
                   1006:     my $max_time=0;
                   1007:     foreach my $other (keys(%accessed)) {
                   1008: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1009: 	    $to_kick=$other;
                   1010: 	    $max_time=&tv_interval($accessed{$other});
                   1011: 	}
                   1012:     }
                   1013:     delete($remembered{$to_kick});
                   1014:     delete($accessed{$to_kick});
                   1015:     $kicks++;
                   1016:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1017:     return;
                   1018: }
                   1019: 
1.599     albertel 1020: sub purge_remembered {
1.604     albertel 1021:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1022:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1023:     undef(%remembered);
                   1024:     undef(%accessed);
1.428     albertel 1025: }
1.70      www      1026: # ------------------------------------- Read an entry from a user's environment
                   1027: 
                   1028: sub userenvironment {
                   1029:     my ($udom,$unam,@what)=@_;
                   1030:     my %returnhash=();
                   1031:     my @answer=split(/\&/,
                   1032:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1033:                       &homeserver($unam,$udom)));
                   1034:     my $i;
                   1035:     for ($i=0;$i<=$#what;$i++) {
                   1036: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1037:     }
                   1038:     return %returnhash;
1.1       albertel 1039: }
                   1040: 
1.617     albertel 1041: # ---------------------------------------------------------- Get a studentphoto
                   1042: sub studentphoto {
                   1043:     my ($udom,$unam,$ext) = @_;
                   1044:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1045:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1046:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1047:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1048:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1049:             } else {
                   1050:                 my ($result,$perm_reqd)=
1.707     albertel 1051: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1052:                 if ($result eq 'ok') {
                   1053:                     if (!($perm_reqd eq 'yes')) {
                   1054:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1055:                     }
                   1056:                 }
                   1057:             }
                   1058:         }
                   1059:     } else {
                   1060:         my ($result,$perm_reqd) = 
1.707     albertel 1061: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1062:         if ($result eq 'ok') {
                   1063:             if (!($perm_reqd eq 'yes')) {
                   1064:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1065:             }
                   1066:         }
                   1067:     }
                   1068:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1069: }
                   1070: 
                   1071: sub retrievestudentphoto {
                   1072:     my ($udom,$unam,$ext,$type) = @_;
                   1073:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1074:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1075:     if ($ret eq 'ok') {
                   1076:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1077:         if ($type eq 'thumbnail') {
                   1078:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1079:         }
                   1080:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1081:         return $tokenurl;
                   1082:     } else {
                   1083:         if ($type eq 'thumbnail') {
                   1084:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1085:         } else { 
                   1086:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1087:         }
1.617     albertel 1088:     }
                   1089: }
                   1090: 
1.263     www      1091: # -------------------------------------------------------------------- New chat
                   1092: 
                   1093: sub chatsend {
1.724     raeburn  1094:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1095:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1096:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1097:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1098:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1099: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1100: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1101: }
                   1102: 
                   1103: # ------------------------------------------ Find current version of a resource
                   1104: 
                   1105: sub getversion {
                   1106:     my $fname=&clutter(shift);
                   1107:     unless ($fname=~/^\/res\//) { return -1; }
                   1108:     return &currentversion(&filelocation('',$fname));
                   1109: }
                   1110: 
                   1111: sub currentversion {
                   1112:     my $fname=shift;
1.599     albertel 1113:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1114:     if (defined($cached)) { return $result; }
1.292     www      1115:     my $author=$fname;
                   1116:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1117:     my ($udom,$uname)=split(/\//,$author);
                   1118:     my $home=homeserver($uname,$udom);
                   1119:     if ($home eq 'no_host') { 
                   1120:         return -1; 
                   1121:     }
                   1122:     my $answer=reply("currentversion:$fname",$home);
                   1123:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1124: 	return -1;
                   1125:     }
1.599     albertel 1126:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1127: }
                   1128: 
1.1       albertel 1129: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1130: 
1.1       albertel 1131: sub subscribe {
                   1132:     my $fname=shift;
1.761     raeburn  1133:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1134:     $fname=~s/[\n\r]//g;
1.1       albertel 1135:     my $author=$fname;
                   1136:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1137:     my ($udom,$uname)=split(/\//,$author);
                   1138:     my $home=homeserver($uname,$udom);
1.335     albertel 1139:     if ($home eq 'no_host') {
                   1140:         return 'not_found';
1.1       albertel 1141:     }
                   1142:     my $answer=reply("sub:$fname",$home);
1.64      www      1143:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1144: 	$answer.=' by '.$home;
                   1145:     }
1.1       albertel 1146:     return $answer;
                   1147: }
                   1148:     
1.8       www      1149: # -------------------------------------------------------------- Replicate file
                   1150: 
                   1151: sub repcopy {
                   1152:     my $filename=shift;
1.23      www      1153:     $filename=~s/\/+/\//g;
1.607     raeburn  1154:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1155:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1156:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1157: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1158: 	return &repcopy_userfile($filename);
                   1159:     }
1.532     albertel 1160:     $filename=~s/[\n\r]//g;
1.8       www      1161:     my $transname="$filename.in.transfer";
1.607     raeburn  1162:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1163:     my $remoteurl=subscribe($filename);
1.64      www      1164:     if ($remoteurl =~ /^con_lost by/) {
                   1165: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1166:            return 'unavailable';
1.8       www      1167:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1168: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1169: 	   return 'not_found';
1.64      www      1170:     } elsif ($remoteurl =~ /^rejected by/) {
                   1171: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1172:            return 'forbidden';
1.20      www      1173:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1174:            return 'ok';
1.8       www      1175:     } else {
1.290     www      1176:         my $author=$filename;
                   1177:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1178:         my ($udom,$uname)=split(/\//,$author);
                   1179:         my $home=homeserver($uname,$udom);
                   1180:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1181:            my @parts=split(/\//,$filename);
                   1182:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1183:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1184:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1185: 	       return 'bad_request';
1.8       www      1186:            }
                   1187:            my $count;
                   1188:            for ($count=5;$count<$#parts;$count++) {
                   1189:                $path.="/$parts[$count]";
                   1190:                if ((-e $path)!=1) {
                   1191: 		   mkdir($path,0777);
                   1192:                }
                   1193:            }
                   1194:            my $ua=new LWP::UserAgent;
                   1195:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1196:            my $response=$ua->request($request,$transname);
                   1197:            if ($response->is_error()) {
                   1198: 	       unlink($transname);
                   1199:                my $message=$response->status_line;
1.672     albertel 1200:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1201:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1202:                return 'unavailable';
1.8       www      1203:            } else {
1.16      www      1204: 	       if ($remoteurl!~/\.meta$/) {
                   1205:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1206:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1207:                   if ($mresponse->is_error()) {
                   1208: 		      unlink($filename.'.meta');
                   1209:                       &logthis(
1.672     albertel 1210:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1211:                   }
                   1212: 	       }
1.8       www      1213:                rename($transname,$filename);
1.607     raeburn  1214:                return 'ok';
1.8       www      1215:            }
1.290     www      1216:        }
1.8       www      1217:     }
1.330     www      1218: }
                   1219: 
                   1220: # ------------------------------------------------ Get server side include body
                   1221: sub ssi_body {
1.381     albertel 1222:     my ($filelink,%form)=@_;
1.606     matthew  1223:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1224:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1225:     }
1.330     www      1226:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1227:                                      &ssi($filelink,%form));
1.778     albertel 1228:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1229:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1230:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1231:     return $output;
1.8       www      1232: }
                   1233: 
1.15      www      1234: # --------------------------------------------------------- Server Side Include
                   1235: 
1.782     albertel 1236: sub absolute_url {
                   1237:     my ($host_name) = @_;
                   1238:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1239:     if ($host_name eq '') {
                   1240: 	$host_name = $ENV{'SERVER_NAME'};
                   1241:     }
                   1242:     return $protocol.$host_name;
                   1243: }
                   1244: 
1.15      www      1245: sub ssi {
                   1246: 
1.23      www      1247:     my ($fn,%form)=@_;
1.15      www      1248: 
                   1249:     my $ua=new LWP::UserAgent;
1.23      www      1250:     
                   1251:     my $request;
1.711     albertel 1252: 
                   1253:     $form{'no_update_last_known'}=1;
                   1254: 
1.23      www      1255:     if (%form) {
1.782     albertel 1256:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1257:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1258:     } else {
1.782     albertel 1259:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1260:     }
                   1261: 
1.15      www      1262:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1263:     my $response=$ua->request($request);
                   1264: 
1.324     www      1265:     return $response->content;
                   1266: }
                   1267: 
                   1268: sub externalssi {
                   1269:     my ($url)=@_;
                   1270:     my $ua=new LWP::UserAgent;
                   1271:     my $request=new HTTP::Request('GET',$url);
                   1272:     my $response=$ua->request($request);
1.15      www      1273:     return $response->content;
                   1274: }
1.254     www      1275: 
1.492     albertel 1276: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1277: 
                   1278: sub allowuploaded {
                   1279:     my ($srcurl,$url)=@_;
                   1280:     $url=&clutter(&declutter($url));
                   1281:     my $dir=$url;
                   1282:     $dir=~s/\/[^\/]+$//;
                   1283:     my %httpref=();
                   1284:     my $httpurl=&hreflocation('',$url);
                   1285:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1286:     &Apache::lonnet::appenv(%httpref);
1.254     www      1287: }
1.477     raeburn  1288: 
1.478     albertel 1289: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1290: # input: action, courseID, current domain, intended
1.637     raeburn  1291: #        path to file, source of file, instruction to parse file for objects,
                   1292: #        ref to hash for embedded objects,
                   1293: #        ref to hash for codebase of java objects.
                   1294: #
1.485     raeburn  1295: # output: url to file (if action was uploaddoc), 
                   1296: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1297: #
1.478     albertel 1298: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1299: # course.
1.477     raeburn  1300: #
1.478     albertel 1301: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1302: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1303: #          course's home server.
1.477     raeburn  1304: #
1.478     albertel 1305: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1306: #          be copied from $source (current location) to 
                   1307: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1308: #         and will then be copied to
                   1309: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1310: #         course's home server.
1.485     raeburn  1311: #
1.481     raeburn  1312: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1313: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1314: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1315: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1316: #         in course's home server.
1.637     raeburn  1317: #
1.477     raeburn  1318: 
                   1319: sub process_coursefile {
1.638     albertel 1320:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1321:     my $fetchresult;
1.638     albertel 1322:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1323:     if ($action eq 'propagate') {
1.638     albertel 1324:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1325: 			     $home);
1.481     raeburn  1326:     } else {
1.477     raeburn  1327:         my $fpath = '';
                   1328:         my $fname = $file;
1.478     albertel 1329:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1330:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1331:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1332:         if ($action eq 'copy') {
                   1333:             if ($source eq '') {
                   1334:                 $fetchresult = 'no source file';
                   1335:                 return $fetchresult;
                   1336:             } else {
                   1337:                 my $destination = $filepath.'/'.$fname;
                   1338:                 rename($source,$destination);
                   1339:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1340:                                  $home);
1.481     raeburn  1341:             }
                   1342:         } elsif ($action eq 'uploaddoc') {
                   1343:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1344:             print $fh $env{'form.'.$source};
1.481     raeburn  1345:             close($fh);
1.637     raeburn  1346:             if ($parser eq 'parse') {
                   1347:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1348:                 unless ($parse_result eq 'ok') {
                   1349:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1350:                 }
                   1351:             }
1.477     raeburn  1352:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1353:                                  $home);
1.481     raeburn  1354:             if ($fetchresult eq 'ok') {
                   1355:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1356:             } else {
                   1357:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1358:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1359:                 return '/adm/notfound.html';
                   1360:             }
1.477     raeburn  1361:         }
                   1362:     }
1.485     raeburn  1363:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1364:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1365:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1366:     }
                   1367:     return $fetchresult;
                   1368: }
                   1369: 
1.637     raeburn  1370: sub build_filepath {
                   1371:     my ($fpath) = @_;
                   1372:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1373:     unless ($fpath eq '') {
                   1374:         my @parts=split('/',$fpath);
                   1375:         foreach my $part (@parts) {
                   1376:             $filepath.= '/'.$part;
                   1377:             if ((-e $filepath)!=1) {
                   1378:                 mkdir($filepath,0777);
                   1379:             }
                   1380:         }
                   1381:     }
                   1382:     return $filepath;
                   1383: }
                   1384: 
                   1385: sub store_edited_file {
1.638     albertel 1386:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1387:     my $file = $primary_url;
                   1388:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1389:     my $fpath = '';
                   1390:     my $fname = $file;
                   1391:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1392:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1393:     my $filepath = &build_filepath($fpath);
                   1394:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1395:     print $fh $content;
                   1396:     close($fh);
1.638     albertel 1397:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1398:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1399: 			  $home);
1.637     raeburn  1400:     if ($$fetchresult eq 'ok') {
                   1401:         return '/uploaded/'.$fpath.'/'.$fname;
                   1402:     } else {
1.638     albertel 1403:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1404: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1405:         return '/adm/notfound.html';
                   1406:     }
                   1407: }
                   1408: 
1.531     albertel 1409: sub clean_filename {
                   1410:     my ($fname)=@_;
1.315     www      1411: # Replace Windows backslashes by forward slashes
1.257     www      1412:     $fname=~s/\\/\//g;
1.315     www      1413: # Get rid of everything but the actual filename
1.257     www      1414:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1415: # Replace spaces by underscores
                   1416:     $fname=~s/\s+/\_/g;
                   1417: # Replace all other weird characters by nothing
1.317     www      1418:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1419: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1420: # numbers
                   1421:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1422:     return $fname;
                   1423: }
                   1424: 
1.608     albertel 1425: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1426: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1427: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1428: #        $coursedoc - if true up to the current course
                   1429: #                     if false
                   1430: #        $subdir - directory in userfile to store the file into
                   1431: #        $parser, $allfiles, $codebase - unknown
                   1432: #
                   1433: # output: url of file in userspace, or error: <message> 
                   1434: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1435: 
                   1436: 
1.531     albertel 1437: sub userfileupload {
1.719     banghart 1438:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1439:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1440:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1441:     $fname=&clean_filename($fname);
1.315     www      1442: # See if there is anything left
1.257     www      1443:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1444:     chop($env{'form.'.$formname});
1.523     raeburn  1445:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1446:         my $now = time;
                   1447:         my $filepath = 'tmp/helprequests/'.$now;
                   1448:         my @parts=split(/\//,$filepath);
                   1449:         my $fullpath = $perlvar{'lonDaemons'};
                   1450:         for (my $i=0;$i<@parts;$i++) {
                   1451:             $fullpath .= '/'.$parts[$i];
                   1452:             if ((-e $fullpath)!=1) {
                   1453:                 mkdir($fullpath,0777);
                   1454:             }
                   1455:         }
                   1456:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1457:         print $fh $env{'form.'.$formname};
1.523     raeburn  1458:         close($fh);
1.741     raeburn  1459:         return $fullpath.'/'.$fname;
                   1460:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1461:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1462:                        '_'.$env{'user.domain'}.'/pending';
                   1463:         my @parts=split(/\//,$filepath);
                   1464:         my $fullpath = $perlvar{'lonDaemons'};
                   1465:         for (my $i=0;$i<@parts;$i++) {
                   1466:             $fullpath .= '/'.$parts[$i];
                   1467:             if ((-e $fullpath)!=1) {
                   1468:                 mkdir($fullpath,0777);
                   1469:             }
                   1470:         }
                   1471:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1472:         print $fh $env{'form.'.$formname};
                   1473:         close($fh);
                   1474:         return $fullpath.'/'.$fname;
1.523     raeburn  1475:     }
1.719     banghart 1476:     
1.258     www      1477: # Create the directory if not present
1.493     albertel 1478:     $fname="$subdir/$fname";
1.259     www      1479:     if ($coursedoc) {
1.638     albertel 1480: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1481: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1482:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1483:             return &finishuserfileupload($docuname,$docudom,
                   1484: 					 $formname,$fname,$parser,$allfiles,
                   1485: 					 $codebase);
1.481     raeburn  1486:         } else {
1.620     albertel 1487:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1488:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1489: 				       $fname,$formname,$parser,
                   1490: 				       $allfiles,$codebase);
1.481     raeburn  1491:         }
1.719     banghart 1492:     } elsif (defined($destuname)) {
                   1493:         my $docuname=$destuname;
                   1494:         my $docudom=$destudom;
                   1495: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1496: 				     $fname,$parser,$allfiles,$codebase);
                   1497:         
1.259     www      1498:     } else {
1.638     albertel 1499:         my $docuname=$env{'user.name'};
                   1500:         my $docudom=$env{'user.domain'};
1.714     raeburn  1501:         if (exists($env{'form.group'})) {
                   1502:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1503:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1504:         }
1.638     albertel 1505: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1506: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1507:     }
1.271     www      1508: }
                   1509: 
                   1510: sub finishuserfileupload {
1.638     albertel 1511:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1512:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1513:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1514:     my ($fnamepath,$file);
                   1515:     $file=$fname;
                   1516:     if ($fname=~m|/|) {
                   1517:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1518: 	$path.=$fnamepath.'/';
                   1519:     }
1.259     www      1520:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1521:     my $count;
                   1522:     for ($count=4;$count<=$#parts;$count++) {
                   1523:         $filepath.="/$parts[$count]";
                   1524:         if ((-e $filepath)!=1) {
                   1525: 	    mkdir($filepath,0777);
                   1526:         }
                   1527:     }
                   1528: # Save the file
                   1529:     {
1.701     albertel 1530: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1531: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1532: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1533: 	    return '/adm/notfound.html';
                   1534: 	}
                   1535: 	if (!print FH ($env{'form.'.$formname})) {
                   1536: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1537: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1538: 	    return '/adm/notfound.html';
                   1539: 	}
1.570     albertel 1540: 	close(FH);
1.258     www      1541:     }
1.637     raeburn  1542:     if ($parser eq 'parse') {
1.638     albertel 1543:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1544: 						   $codebase);
1.637     raeburn  1545:         unless ($parse_result eq 'ok') {
1.638     albertel 1546:             &logthis('Failed to parse '.$filepath.$file.
                   1547: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1548:         }
                   1549:     }
1.259     www      1550: # Notify homeserver to grep it
                   1551: #
1.638     albertel 1552:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1553:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1554:     if ($fetchresult eq 'ok') {
1.259     www      1555: #
1.258     www      1556: # Return the URL to it
1.494     albertel 1557:         return '/uploaded/'.$path.$file;
1.263     www      1558:     } else {
1.494     albertel 1559:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1560: 		 ': '.$fetchresult);
1.263     www      1561:         return '/adm/notfound.html';
                   1562:     }    
1.493     albertel 1563: }
                   1564: 
1.637     raeburn  1565: sub extract_embedded_items {
1.648     raeburn  1566:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1567:     my @state = ();
                   1568:     my %javafiles = (
                   1569:                       codebase => '',
                   1570:                       code => '',
                   1571:                       archive => ''
                   1572:                     );
                   1573:     my %mediafiles = (
                   1574:                       src => '',
                   1575:                       movie => '',
                   1576:                      );
1.648     raeburn  1577:     my $p;
                   1578:     if ($content) {
                   1579:         $p = HTML::LCParser->new($content);
                   1580:     } else {
                   1581:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1582:     }
1.641     albertel 1583:     while (my $t=$p->get_token()) {
1.640     albertel 1584: 	if ($t->[0] eq 'S') {
                   1585: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1586: 	    push (@state, $tagname);
1.648     raeburn  1587:             if (lc($tagname) eq 'allow') {
                   1588:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1589:             }
1.640     albertel 1590: 	    if (lc($tagname) eq 'img') {
                   1591: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1592: 	    }
1.645     raeburn  1593:             if (lc($tagname) eq 'script') {
                   1594:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1595:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1596:                 } else {
                   1597:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1598:                 }
                   1599:             }
                   1600:             if (lc($tagname) eq 'link') {
                   1601:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1602:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1603:                 }
                   1604:             }
1.640     albertel 1605: 	    if (lc($tagname) eq 'object' ||
                   1606: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1607: 		foreach my $item (keys(%javafiles)) {
                   1608: 		    $javafiles{$item} = '';
                   1609: 		}
                   1610: 	    }
                   1611: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1612: 		my $name = lc($attr->{'name'});
                   1613: 		foreach my $item (keys(%javafiles)) {
                   1614: 		    if ($name eq $item) {
                   1615: 			$javafiles{$item} = $attr->{'value'};
                   1616: 			last;
                   1617: 		    }
                   1618: 		}
                   1619: 		foreach my $item (keys(%mediafiles)) {
                   1620: 		    if ($name eq $item) {
                   1621: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1622: 			last;
                   1623: 		    }
                   1624: 		}
                   1625: 	    }
                   1626: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1627: 		foreach my $item (keys(%javafiles)) {
                   1628: 		    if ($attr->{$item}) {
                   1629: 			$javafiles{$item} = $attr->{$item};
                   1630: 			last;
                   1631: 		    }
                   1632: 		}
                   1633: 		foreach my $item (keys(%mediafiles)) {
                   1634: 		    if ($attr->{$item}) {
                   1635: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1636: 			last;
                   1637: 		    }
                   1638: 		}
                   1639: 	    }
                   1640: 	} elsif ($t->[0] eq 'E') {
                   1641: 	    my ($tagname) = ($t->[1]);
                   1642: 	    if ($javafiles{'codebase'} ne '') {
                   1643: 		$javafiles{'codebase'} .= '/';
                   1644: 	    }  
                   1645: 	    if (lc($tagname) eq 'applet' ||
                   1646: 		lc($tagname) eq 'object' ||
                   1647: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1648: 		) {
                   1649: 		foreach my $item (keys(%javafiles)) {
                   1650: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1651: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1652: 			&add_filetype($allfiles,$file,$item);
                   1653: 		    }
                   1654: 		}
                   1655: 	    } 
                   1656: 	    pop @state;
                   1657: 	}
                   1658:     }
1.637     raeburn  1659:     return 'ok';
                   1660: }
                   1661: 
1.639     albertel 1662: sub add_filetype {
                   1663:     my ($allfiles,$file,$type)=@_;
                   1664:     if (exists($allfiles->{$file})) {
                   1665: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1666: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1667: 	}
                   1668:     } else {
                   1669: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1670:     }
                   1671: }
                   1672: 
1.493     albertel 1673: sub removeuploadedurl {
                   1674:     my ($url)=@_;
                   1675:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1676:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1677: }
                   1678: 
                   1679: sub removeuserfile {
                   1680:     my ($docuname,$docudom,$fname)=@_;
                   1681:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1682:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1683:     if ($result eq 'ok') {
                   1684:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1685:             my $metafile = $fname.'.meta';
                   1686:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
                   1687:         }
                   1688:     }
                   1689:     return $result;
1.257     www      1690: }
1.15      www      1691: 
1.530     albertel 1692: sub mkdiruserfile {
                   1693:     my ($docuname,$docudom,$dir)=@_;
                   1694:     my $home=&homeserver($docuname,$docudom);
                   1695:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1696: }
                   1697: 
1.531     albertel 1698: sub renameuserfile {
                   1699:     my ($docuname,$docudom,$old,$new)=@_;
                   1700:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1701:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1702:                         &escape("$old").':'.&escape("$new"),$home);
                   1703:     if ($result eq 'ok') {
                   1704:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1705:             my $oldmeta = $old.'.meta';
                   1706:             my $newmeta = $new.'.meta';
                   1707:             my $metaresult = 
                   1708:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
                   1709:         }
                   1710:     }
                   1711:     return $result;
1.531     albertel 1712: }
                   1713: 
1.14      www      1714: # ------------------------------------------------------------------------- Log
                   1715: 
                   1716: sub log {
                   1717:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1718:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1719: }
                   1720: 
                   1721: # ------------------------------------------------------------------ Course Log
1.352     www      1722: #
                   1723: # This routine flushes several buffers of non-mission-critical nature
                   1724: #
1.157     www      1725: 
                   1726: sub flushcourselogs {
1.352     www      1727:     &logthis('Flushing log buffers');
                   1728: #
                   1729: # course logs
                   1730: # This is a log of all transactions in a course, which can be used
                   1731: # for data mining purposes
                   1732: #
                   1733: # It also collects the courseid database, which lists last transaction
                   1734: # times and course titles for all courseids
                   1735: #
                   1736:     my %courseidbuffer=();
1.800     albertel 1737:     foreach my $crsid (keys %courselogs) {
1.352     www      1738:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1739: 		          &escape($courselogs{$crsid}),
                   1740: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1741: 	    delete $courselogs{$crsid};
                   1742:         } else {
                   1743:             &logthis('Failed to flush log buffer for '.$crsid);
                   1744:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1745:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1746:                         " exceeded maximum size, deleting.</font>");
                   1747:                delete $courselogs{$crsid};
                   1748:             }
1.352     www      1749:         }
                   1750:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1751:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1752: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1753:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1754:         } else {
                   1755:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1756: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1757:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1758:         }
1.191     harris41 1759:     }
1.352     www      1760: #
                   1761: # Write course id database (reverse lookup) to homeserver of courses 
                   1762: # Is used in pickcourse
                   1763: #
1.800     albertel 1764:     foreach my $crsid (keys(%courseidbuffer)) {
                   1765:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1766:     }
                   1767: #
                   1768: # File accesses
                   1769: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1770: #
1.449     matthew  1771:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1772:         if ($entry =~ /___count$/) {
                   1773:             my ($dom,$name);
1.807     albertel 1774:             ($dom,$name,undef)=
1.811     albertel 1775: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1776:             if (! defined($dom) || $dom eq '' || 
                   1777:                 ! defined($name) || $name eq '') {
1.620     albertel 1778:                 my $cid = $env{'request.course.id'};
                   1779:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1780:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1781:             }
1.450     matthew  1782:             my $value = $accesshash{$entry};
                   1783:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1784:             my %temphash=($url => $value);
1.449     matthew  1785:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1786:             if ($result eq 'ok') {
                   1787:                 delete $accesshash{$entry};
                   1788:             } elsif ($result eq 'unknown_cmd') {
                   1789:                 # Target server has old code running on it.
1.450     matthew  1790:                 my %temphash=($entry => $value);
1.449     matthew  1791:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1792:                     delete $accesshash{$entry};
                   1793:                 }
                   1794:             }
                   1795:         } else {
1.811     albertel 1796:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1797:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1798:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1799:                 delete $accesshash{$entry};
                   1800:             }
1.185     www      1801:         }
1.191     harris41 1802:     }
1.352     www      1803: #
                   1804: # Roles
                   1805: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1806: #
1.800     albertel 1807:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1808:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1809: 	    split(/\:/,$entry);
                   1810:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1811:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1812:                 $rudom,$runame) eq 'ok') {
                   1813: 	    delete $userrolehash{$entry};
                   1814:         }
                   1815:     }
1.662     raeburn  1816: #
                   1817: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1818: #
                   1819:     my %domrolebuffer = ();
                   1820:     foreach my $entry (keys %domainrolehash) {
                   1821:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1822:         if ($domrolebuffer{$rudom}) {
                   1823:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1824:                       '='.&escape($domainrolehash{$entry});
                   1825:         } else {
                   1826:             $domrolebuffer{$rudom}.=&escape($entry).
                   1827:                       '='.&escape($domainrolehash{$entry});
                   1828:         }
                   1829:         delete $domainrolehash{$entry};
                   1830:     }
                   1831:     foreach my $dom (keys(%domrolebuffer)) {
                   1832:         foreach my $tryserver (keys %libserv) {
                   1833:             if ($hostdom{$tryserver} eq $dom) {
                   1834:                 unless (&reply('domroleput:'.$dom.':'.
                   1835:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1836:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1837:                 }
                   1838:             }
                   1839:         }
                   1840:     }
1.186     www      1841:     $dumpcount++;
1.157     www      1842: }
                   1843: 
                   1844: sub courselog {
                   1845:     my $what=shift;
1.158     www      1846:     $what=time.':'.$what;
1.620     albertel 1847:     unless ($env{'request.course.id'}) { return ''; }
                   1848:     $coursedombuf{$env{'request.course.id'}}=
                   1849:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1850:     $coursenumbuf{$env{'request.course.id'}}=
                   1851:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1852:     $coursehombuf{$env{'request.course.id'}}=
                   1853:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1854:     $coursedescrbuf{$env{'request.course.id'}}=
                   1855:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1856:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1857:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1858:     $courseownerbuf{$env{'request.course.id'}}=
                   1859:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1860:     $coursetypebuf{$env{'request.course.id'}}=
                   1861:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1862:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1863: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1864:     } else {
1.620     albertel 1865: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1866:     }
1.620     albertel 1867:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1868: 	&flushcourselogs();
                   1869:     }
1.158     www      1870: }
                   1871: 
                   1872: sub courseacclog {
                   1873:     my $fnsymb=shift;
1.620     albertel 1874:     unless ($env{'request.course.id'}) { return ''; }
                   1875:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1876:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1877:         $what.=':POST';
1.583     matthew  1878:         # FIXME: Probably ought to escape things....
1.800     albertel 1879: 	foreach my $key (keys(%env)) {
                   1880:             if ($key=~/^form\.(.*)/) {
                   1881: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1882:             }
1.191     harris41 1883:         }
1.583     matthew  1884:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1885:         # FIXME: We should not be depending on a form parameter that someone
                   1886:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1887:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1888:             $what.= ':POST';
                   1889:             # FIXME: Probably ought to escape things....
                   1890:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1891:                                  'crsdiscuss') {
1.620     albertel 1892:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1893:             }
                   1894:         }
1.158     www      1895:     }
                   1896:     &courselog($what);
1.149     www      1897: }
                   1898: 
1.185     www      1899: sub countacc {
                   1900:     my $url=&declutter(shift);
1.458     matthew  1901:     return if (! defined($url) || $url eq '');
1.620     albertel 1902:     unless ($env{'request.course.id'}) { return ''; }
                   1903:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1904:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1905:     $accesshash{$key}++;
1.185     www      1906: }
1.349     www      1907: 
1.361     www      1908: sub linklog {
                   1909:     my ($from,$to)=@_;
                   1910:     $from=&declutter($from);
                   1911:     $to=&declutter($to);
                   1912:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1913:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1914: }
                   1915:   
1.349     www      1916: sub userrolelog {
                   1917:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1918:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1919:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1920:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1921:         ($trole=~/^ta/)) {
1.350     www      1922:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1923:        $userrolehash
                   1924:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1925:                     =$tend.':'.$tstart;
1.662     raeburn  1926:     }
                   1927:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1928:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1929:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1930:         ($trole=~/^sc/)) {
                   1931:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1932:        $domainrolehash
                   1933:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1934:                     = $tend.':'.$tstart;
                   1935:     }
1.351     www      1936: }
                   1937: 
                   1938: sub get_course_adv_roles {
                   1939:     my $cid=shift;
1.620     albertel 1940:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1941:     my %coursehash=&coursedescription($cid);
1.470     www      1942:     my %nothide=();
1.800     albertel 1943:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1944: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      1945:     }
1.351     www      1946:     my %returnhash=();
                   1947:     my %dumphash=
                   1948:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1949:     my $now=time;
1.800     albertel 1950:     foreach my $entry (keys %dumphash) {
                   1951: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      1952:         if (($tstart) && ($tstart<0)) { next; }
                   1953:         if (($tend) && ($tend<$now)) { next; }
                   1954:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1955:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 1956: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1957: 	if ((&privileged($username,$domain)) && 
                   1958: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1959: 	if ($role eq 'cr') { next; }
1.351     www      1960:         my $key=&plaintext($role);
                   1961:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1962:         if ($returnhash{$key}) {
                   1963: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1964:         } else {
                   1965:             $returnhash{$key}=$username.':'.$domain;
                   1966:         }
1.400     www      1967:      }
                   1968:     return %returnhash;
                   1969: }
                   1970: 
                   1971: sub get_my_roles {
                   1972:     my ($uname,$udom)=@_;
1.620     albertel 1973:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1974:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1975:     my %dumphash=
                   1976:             &dump('nohist_userroles',$udom,$uname);
                   1977:     my %returnhash=();
                   1978:     my $now=time;
1.800     albertel 1979:     foreach my $entry (keys(%dumphash)) {
                   1980: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      1981:         if (($tstart) && ($tstart<0)) { next; }
                   1982:         if (($tend) && ($tend<$now)) { next; }
                   1983:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1984:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      1985: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1986:      }
                   1987:     return %returnhash;
1.399     www      1988: }
                   1989: 
                   1990: # ----------------------------------------------------- Frontpage Announcements
                   1991: #
                   1992: #
                   1993: 
                   1994: sub postannounce {
                   1995:     my ($server,$text)=@_;
                   1996:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1997:     unless ($text=~/\w/) { $text=''; }
                   1998:     return &reply('setannounce:'.&escape($text),$server);
                   1999: }
                   2000: 
                   2001: sub getannounce {
1.448     albertel 2002: 
                   2003:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2004: 	my $announcement='';
1.800     albertel 2005: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2006: 	close($fh);
1.399     www      2007: 	if ($announcement=~/\w/) { 
                   2008: 	    return 
                   2009:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2010:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2011: 	} else {
                   2012: 	    return '';
                   2013: 	}
                   2014:     } else {
                   2015: 	return '';
                   2016:     }
1.351     www      2017: }
1.353     www      2018: 
                   2019: # ---------------------------------------------------------- Course ID routines
                   2020: # Deal with domain's nohist_courseid.db files
                   2021: #
                   2022: 
                   2023: sub courseidput {
                   2024:     my ($domain,$what,$coursehome)=@_;
                   2025:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2026: }
                   2027: 
                   2028: sub courseiddump {
1.791     raeburn  2029:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2030:     my %returnhash=();
1.355     www      2031:     unless ($domfilter) { $domfilter=''; }
1.353     www      2032:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2033:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2034: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2035: 	        foreach my $line (
1.506     raeburn  2036:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2037: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2038:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2039:                                $tryserver))) {
1.800     albertel 2040: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2041:                     if (($key) && ($value)) {
1.516     raeburn  2042: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2043:                     }
1.353     www      2044:                 }
                   2045:             }
                   2046:         }
                   2047:     }
                   2048:     return %returnhash;
                   2049: }
                   2050: 
1.658     raeburn  2051: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2052: 
                   2053: sub dcmailput {
1.685     raeburn  2054:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2055:     my $status = &Apache::lonnet::critical(
1.740     www      2056:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2057:        &escape($message),$server);
1.662     raeburn  2058:     return $status;
                   2059: }
                   2060: 
1.658     raeburn  2061: sub dcmaildump {
                   2062:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2063:     my %returnhash=();
                   2064:     if (exists($domain_primary{$dom})) {
                   2065:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2066:                                                          &escape($enddate).':';
                   2067: 	my @esc_senders=map { &escape($_)} @$senders;
                   2068: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2069: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2070:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2071:             if (($key) && ($value)) {
                   2072:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2073:             }
                   2074:         }
                   2075:     }
                   2076:     return %returnhash;
                   2077: }
1.662     raeburn  2078: # ---------------------------------------------------------- Domain roles
                   2079: 
                   2080: sub get_domain_roles {
                   2081:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2082:     if (undef($startdate) || $startdate eq '') {
                   2083:         $startdate = '.';
                   2084:     }
                   2085:     if (undef($enddate) || $enddate eq '') {
                   2086:         $enddate = '.';
                   2087:     }
                   2088:     my $rolelist = join(':',@{$roles});
                   2089:     my %personnel = ();
                   2090:     foreach my $tryserver (keys(%libserv)) {
                   2091:         if ($hostdom{$tryserver} eq $dom) {
                   2092:             %{$personnel{$tryserver}}=();
1.800     albertel 2093:             foreach my $line (
1.662     raeburn  2094:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2095:                    &escape($startdate).':'.&escape($enddate).':'.
                   2096:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2097:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2098:                 if (($key) && ($value)) {
                   2099:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2100:                 }
                   2101:             }
                   2102:         }
                   2103:     }
                   2104:     return %personnel;
                   2105: }
1.658     raeburn  2106: 
1.149     www      2107: # ----------------------------------------------------------- Check out an item
                   2108: 
1.504     albertel 2109: sub get_first_access {
                   2110:     my ($type,$argsymb)=@_;
1.790     albertel 2111:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2112:     if ($argsymb) { $symb=$argsymb; }
                   2113:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2114:     if ($type eq 'map') {
                   2115: 	$res=&symbread($map);
                   2116:     } else {
                   2117: 	$res=$symb;
                   2118:     }
                   2119:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2120:     return $times{"$courseid\0$res"};
1.504     albertel 2121: }
                   2122: 
                   2123: sub set_first_access {
                   2124:     my ($type)=@_;
1.790     albertel 2125:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2126:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2127:     if ($type eq 'map') {
                   2128: 	$res=&symbread($map);
                   2129:     } else {
                   2130: 	$res=$symb;
                   2131:     }
                   2132:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2133:     if (!$firstaccess) {
1.588     albertel 2134: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2135:     }
                   2136:     return 'already_set';
1.504     albertel 2137: }
                   2138: 
1.149     www      2139: sub checkout {
                   2140:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2141:     my $now=time;
                   2142:     my $lonhost=$perlvar{'lonHostID'};
                   2143:     my $infostr=&escape(
1.234     www      2144:                  'CHECKOUTTOKEN&'.
1.149     www      2145:                  $tuname.'&'.
                   2146:                  $tudom.'&'.
                   2147:                  $tcrsid.'&'.
                   2148:                  $symb.'&'.
                   2149: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2150:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2151:     if ($token=~/^error\:/) { 
1.672     albertel 2152:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2153:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2154:                  "</font>");
                   2155:         return ''; 
                   2156:     }
                   2157: 
1.149     www      2158:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2159:     $token=~tr/a-z/A-Z/;
                   2160: 
1.153     www      2161:     my %infohash=('resource.0.outtoken' => $token,
                   2162:                   'resource.0.checkouttime' => $now,
                   2163:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2164: 
                   2165:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2166:        return '';
1.151     www      2167:     } else {
1.672     albertel 2168:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2169:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2170:                  "</font>");
1.149     www      2171:     }    
                   2172: 
                   2173:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2174:                          &escape('Checkout '.$infostr.' - '.
                   2175:                                                  $token)) ne 'ok') {
                   2176: 	return '';
1.151     www      2177:     } else {
1.672     albertel 2178:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2179:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2180:                  "</font>");
1.149     www      2181:     }
1.151     www      2182:     return $token;
1.149     www      2183: }
                   2184: 
                   2185: # ------------------------------------------------------------ Check in an item
                   2186: 
                   2187: sub checkin {
                   2188:     my $token=shift;
1.150     www      2189:     my $now=time;
                   2190:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2191:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2192:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2193:     $dtoken=~s/\W/\_/g;
1.234     www      2194:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2195:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2196: 
1.154     www      2197:     unless (($tuname) && ($tudom)) {
                   2198:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2199:         return '';
                   2200:     }
                   2201:     
                   2202:     unless (&allowed('mgr',$tcrsid)) {
                   2203:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2204:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2205:         return '';
                   2206:     }
                   2207: 
1.153     www      2208:     my %infohash=('resource.0.intoken' => $token,
                   2209:                   'resource.0.checkintime' => $now,
                   2210:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2211: 
                   2212:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2213:        return '';
                   2214:     }    
                   2215: 
                   2216:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2217:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2218: 	return '';
                   2219:     }
                   2220: 
                   2221:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2222: }
                   2223: 
                   2224: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2225: 
                   2226: sub expirespread {
                   2227:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2228:     my $cid=$env{'request.course.id'}; 
1.110     www      2229:     if ($cid) {
                   2230:        my $now=time;
                   2231:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2232:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2233:                             $env{'course.'.$cid.'.num'}.
1.110     www      2234: 	        	    ':nohist_expirationdates:'.
                   2235:                             &escape($key).'='.$now,
1.620     albertel 2236:                             $env{'course.'.$cid.'.home'})
1.110     www      2237:     }
                   2238:     return 'ok';
1.14      www      2239: }
                   2240: 
1.109     www      2241: # ----------------------------------------------------- Devalidate Spreadsheets
                   2242: 
                   2243: sub devalidate {
1.325     www      2244:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2245:     my $cid=$env{'request.course.id'}; 
1.109     www      2246:     if ($cid) {
1.391     matthew  2247:         # delete the stored spreadsheets for
                   2248:         # - the student level sheet of this user in course's homespace
                   2249:         # - the assessment level sheet for this resource 
                   2250:         #   for this user in user's homespace
1.553     albertel 2251: 	# - current conditional state info
1.325     www      2252: 	my $key=$uname.':'.$udom.':';
1.109     www      2253:         my $status=
1.299     matthew  2254: 	    &del('nohist_calculatedsheets',
1.391     matthew  2255: 		 [$key.'studentcalc:'],
1.620     albertel 2256: 		 $env{'course.'.$cid.'.domain'},
                   2257: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2258: 		.' '.
                   2259: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2260: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2261:         unless ($status eq 'ok ok') {
                   2262:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2263:                     $uname.' at '.$udom.' for '.
1.109     www      2264: 		    $symb.': '.$status);
1.133     albertel 2265:         }
1.553     albertel 2266: 	&delenv('user.state.'.$cid);
1.109     www      2267:     }
                   2268: }
                   2269: 
1.265     albertel 2270: sub get_scalar {
                   2271:     my ($string,$end) = @_;
                   2272:     my $value;
                   2273:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2274: 	$value = $1;
                   2275:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2276: 	$value = $1;
                   2277:     }
                   2278:     return &unescape($value);
                   2279: }
                   2280: 
                   2281: sub array2str {
                   2282:   my (@array) = @_;
                   2283:   my $result=&arrayref2str(\@array);
                   2284:   $result=~s/^__ARRAY_REF__//;
                   2285:   $result=~s/__END_ARRAY_REF__$//;
                   2286:   return $result;
                   2287: }
                   2288: 
1.204     albertel 2289: sub arrayref2str {
                   2290:   my ($arrayref) = @_;
1.265     albertel 2291:   my $result='__ARRAY_REF__';
1.204     albertel 2292:   foreach my $elem (@$arrayref) {
1.265     albertel 2293:     if(ref($elem) eq 'ARRAY') {
                   2294:       $result.=&arrayref2str($elem).'&';
                   2295:     } elsif(ref($elem) eq 'HASH') {
                   2296:       $result.=&hashref2str($elem).'&';
                   2297:     } elsif(ref($elem)) {
                   2298:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2299:     } else {
                   2300:       $result.=&escape($elem).'&';
                   2301:     }
                   2302:   }
                   2303:   $result=~s/\&$//;
1.265     albertel 2304:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2305:   return $result;
                   2306: }
                   2307: 
1.168     albertel 2308: sub hash2str {
1.204     albertel 2309:   my (%hash) = @_;
                   2310:   my $result=&hashref2str(\%hash);
1.265     albertel 2311:   $result=~s/^__HASH_REF__//;
                   2312:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2313:   return $result;
                   2314: }
                   2315: 
                   2316: sub hashref2str {
                   2317:   my ($hashref)=@_;
1.265     albertel 2318:   my $result='__HASH_REF__';
1.800     albertel 2319:   foreach my $key (sort(keys(%$hashref))) {
                   2320:     if (ref($key) eq 'ARRAY') {
                   2321:       $result.=&arrayref2str($key).'=';
                   2322:     } elsif (ref($key) eq 'HASH') {
                   2323:       $result.=&hashref2str($key).'=';
                   2324:     } elsif (ref($key)) {
1.265     albertel 2325:       $result.='=';
1.800     albertel 2326:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2327:     } else {
1.800     albertel 2328: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2329:     }
                   2330: 
1.800     albertel 2331:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2332:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2333:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2334:       $result.=&hashref2str($hashref->{$key}).'&';
                   2335:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2336:        $result.='&';
1.800     albertel 2337:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2338:     } else {
1.800     albertel 2339:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2340:     }
                   2341:   }
1.168     albertel 2342:   $result=~s/\&$//;
1.265     albertel 2343:   $result .= '__END_HASH_REF__';
1.168     albertel 2344:   return $result;
                   2345: }
                   2346: 
                   2347: sub str2hash {
1.265     albertel 2348:     my ($string)=@_;
                   2349:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2350:     return %$hash;
                   2351: }
                   2352: 
                   2353: sub str2hashref {
1.168     albertel 2354:   my ($string) = @_;
1.265     albertel 2355: 
                   2356:   my %hash;
                   2357: 
                   2358:   if($string !~ /^__HASH_REF__/) {
                   2359:       if (! ($string eq '' || !defined($string))) {
                   2360: 	  $hash{'error'}='Not hash reference';
                   2361:       }
                   2362:       return (\%hash, $string);
                   2363:   }
                   2364: 
                   2365:   $string =~ s/^__HASH_REF__//;
                   2366: 
                   2367:   while($string !~ /^__END_HASH_REF__/) {
                   2368:       #key
                   2369:       my $key='';
                   2370:       if($string =~ /^__HASH_REF__/) {
                   2371:           ($key, $string)=&str2hashref($string);
                   2372:           if(defined($key->{'error'})) {
                   2373:               $hash{'error'}='Bad data';
                   2374:               return (\%hash, $string);
                   2375:           }
                   2376:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2377:           ($key, $string)=&str2arrayref($string);
                   2378:           if($key->[0] eq 'Array reference error') {
                   2379:               $hash{'error'}='Bad data';
                   2380:               return (\%hash, $string);
                   2381:           }
                   2382:       } else {
                   2383:           $string =~ s/^(.*?)=//;
1.267     albertel 2384: 	  $key=&unescape($1);
1.265     albertel 2385:       }
                   2386:       $string =~ s/^=//;
                   2387: 
                   2388:       #value
                   2389:       my $value='';
                   2390:       if($string =~ /^__HASH_REF__/) {
                   2391:           ($value, $string)=&str2hashref($string);
                   2392:           if(defined($value->{'error'})) {
                   2393:               $hash{'error'}='Bad data';
                   2394:               return (\%hash, $string);
                   2395:           }
                   2396:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2397:           ($value, $string)=&str2arrayref($string);
                   2398:           if($value->[0] eq 'Array reference error') {
                   2399:               $hash{'error'}='Bad data';
                   2400:               return (\%hash, $string);
                   2401:           }
                   2402:       } else {
                   2403: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2404:       }
                   2405:       $string =~ s/^&//;
                   2406: 
                   2407:       $hash{$key}=$value;
1.204     albertel 2408:   }
1.265     albertel 2409: 
                   2410:   $string =~ s/^__END_HASH_REF__//;
                   2411: 
                   2412:   return (\%hash, $string);
1.204     albertel 2413: }
                   2414: 
                   2415: sub str2array {
1.265     albertel 2416:     my ($string)=@_;
                   2417:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2418:     return @$array;
                   2419: }
                   2420: 
                   2421: sub str2arrayref {
1.204     albertel 2422:   my ($string) = @_;
1.265     albertel 2423:   my @array;
                   2424: 
                   2425:   if($string !~ /^__ARRAY_REF__/) {
                   2426:       if (! ($string eq '' || !defined($string))) {
                   2427: 	  $array[0]='Array reference error';
                   2428:       }
                   2429:       return (\@array, $string);
                   2430:   }
                   2431: 
                   2432:   $string =~ s/^__ARRAY_REF__//;
                   2433: 
                   2434:   while($string !~ /^__END_ARRAY_REF__/) {
                   2435:       my $value='';
                   2436:       if($string =~ /^__HASH_REF__/) {
                   2437:           ($value, $string)=&str2hashref($string);
                   2438:           if(defined($value->{'error'})) {
                   2439:               $array[0] ='Array reference error';
                   2440:               return (\@array, $string);
                   2441:           }
                   2442:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2443:           ($value, $string)=&str2arrayref($string);
                   2444:           if($value->[0] eq 'Array reference error') {
                   2445:               $array[0] ='Array reference error';
                   2446:               return (\@array, $string);
                   2447:           }
                   2448:       } else {
                   2449: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2450:       }
                   2451:       $string =~ s/^&//;
                   2452: 
                   2453:       push(@array, $value);
1.191     harris41 2454:   }
1.265     albertel 2455: 
                   2456:   $string =~ s/^__END_ARRAY_REF__//;
                   2457: 
                   2458:   return (\@array, $string);
1.168     albertel 2459: }
                   2460: 
1.167     albertel 2461: # -------------------------------------------------------------------Temp Store
                   2462: 
1.168     albertel 2463: sub tmpreset {
                   2464:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2465:   if (!$symb) {
                   2466:     $symb=&symbread();
1.620     albertel 2467:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2468:   }
                   2469:   $symb=escape($symb);
                   2470: 
1.620     albertel 2471:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2472:   $namespace=~s/\//\_/g;
                   2473:   $namespace=~s/\W//g;
                   2474: 
1.620     albertel 2475:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2476:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2477:   if ($domain eq 'public' && $stuname eq 'public') {
                   2478:       $stuname=$ENV{'REMOTE_ADDR'};
                   2479:   }
1.168     albertel 2480:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2481:   my %hash;
                   2482:   if (tie(%hash,'GDBM_File',
                   2483: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2484: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2485:     foreach my $key (keys %hash) {
1.180     albertel 2486:       if ($key=~ /:$symb/) {
1.168     albertel 2487: 	delete($hash{$key});
                   2488:       }
                   2489:     }
                   2490:   }
                   2491: }
                   2492: 
1.167     albertel 2493: sub tmpstore {
1.168     albertel 2494:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2495: 
                   2496:   if (!$symb) {
                   2497:     $symb=&symbread();
1.620     albertel 2498:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2499:   }
                   2500:   $symb=escape($symb);
                   2501: 
                   2502:   if (!$namespace) {
                   2503:     # I don't think we would ever want to store this for a course.
                   2504:     # it seems this will only be used if we don't have a course.
1.620     albertel 2505:     #$namespace=$env{'request.course.id'};
1.168     albertel 2506:     #if (!$namespace) {
1.620     albertel 2507:       $namespace=$env{'request.state'};
1.168     albertel 2508:     #}
                   2509:   }
                   2510:   $namespace=~s/\//\_/g;
                   2511:   $namespace=~s/\W//g;
1.620     albertel 2512:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2513:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2514:   if ($domain eq 'public' && $stuname eq 'public') {
                   2515:       $stuname=$ENV{'REMOTE_ADDR'};
                   2516:   }
1.168     albertel 2517:   my $now=time;
                   2518:   my %hash;
                   2519:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2520:   if (tie(%hash,'GDBM_File',
                   2521: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2522: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2523:     $hash{"version:$symb"}++;
                   2524:     my $version=$hash{"version:$symb"};
                   2525:     my $allkeys=''; 
                   2526:     foreach my $key (keys(%$storehash)) {
                   2527:       $allkeys.=$key.':';
1.591     albertel 2528:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2529:     }
                   2530:     $hash{"$version:$symb:timestamp"}=$now;
                   2531:     $allkeys.='timestamp';
                   2532:     $hash{"$version:keys:$symb"}=$allkeys;
                   2533:     if (untie(%hash)) {
                   2534:       return 'ok';
                   2535:     } else {
                   2536:       return "error:$!";
                   2537:     }
                   2538:   } else {
                   2539:     return "error:$!";
                   2540:   }
                   2541: }
1.167     albertel 2542: 
1.168     albertel 2543: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2544: 
1.168     albertel 2545: sub tmprestore {
                   2546:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2547: 
1.168     albertel 2548:   if (!$symb) {
                   2549:     $symb=&symbread();
1.620     albertel 2550:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2551:   }
                   2552:   $symb=escape($symb);
                   2553: 
1.620     albertel 2554:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2555: 
1.620     albertel 2556:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2557:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2558:   if ($domain eq 'public' && $stuname eq 'public') {
                   2559:       $stuname=$ENV{'REMOTE_ADDR'};
                   2560:   }
1.168     albertel 2561:   my %returnhash;
                   2562:   $namespace=~s/\//\_/g;
                   2563:   $namespace=~s/\W//g;
                   2564:   my %hash;
                   2565:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2566:   if (tie(%hash,'GDBM_File',
                   2567: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2568: 	  &GDBM_READER(),0640)) {
1.168     albertel 2569:     my $version=$hash{"version:$symb"};
                   2570:     $returnhash{'version'}=$version;
                   2571:     my $scope;
                   2572:     for ($scope=1;$scope<=$version;$scope++) {
                   2573:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2574:       my @keys=split(/:/,$vkeys);
                   2575:       my $key;
                   2576:       $returnhash{"$scope:keys"}=$vkeys;
                   2577:       foreach $key (@keys) {
1.591     albertel 2578: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2579: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2580:       }
                   2581:     }
1.168     albertel 2582:     if (!(untie(%hash))) {
                   2583:       return "error:$!";
                   2584:     }
                   2585:   } else {
                   2586:     return "error:$!";
                   2587:   }
                   2588:   return %returnhash;
1.167     albertel 2589: }
                   2590: 
1.9       www      2591: # ----------------------------------------------------------------------- Store
                   2592: 
                   2593: sub store {
1.124     www      2594:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2595:     my $home='';
                   2596: 
1.168     albertel 2597:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2598: 
1.213     www      2599:     $symb=&symbclean($symb);
1.122     albertel 2600:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2601: 
1.620     albertel 2602:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2603:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2604: 
                   2605:     &devalidate($symb,$stuname,$domain);
1.109     www      2606: 
                   2607:     $symb=escape($symb);
1.187     www      2608:     if (!$namespace) { 
1.620     albertel 2609:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2610:           return ''; 
                   2611:        } 
                   2612:     }
1.620     albertel 2613:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2614: 
                   2615:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2616:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2617: 
1.12      www      2618:     my $namevalue='';
1.800     albertel 2619:     foreach my $key (keys(%$storehash)) {
                   2620:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2621:     }
1.12      www      2622:     $namevalue=~s/\&$//;
1.187     www      2623:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2624:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2625: }
                   2626: 
1.47      www      2627: # -------------------------------------------------------------- Critical Store
                   2628: 
                   2629: sub cstore {
1.124     www      2630:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2631:     my $home='';
                   2632: 
1.168     albertel 2633:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2634: 
1.213     www      2635:     $symb=&symbclean($symb);
1.122     albertel 2636:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2637: 
1.620     albertel 2638:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2639:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2640: 
                   2641:     &devalidate($symb,$stuname,$domain);
1.109     www      2642: 
                   2643:     $symb=escape($symb);
1.187     www      2644:     if (!$namespace) { 
1.620     albertel 2645:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2646:           return ''; 
                   2647:        } 
                   2648:     }
1.620     albertel 2649:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2650: 
                   2651:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2652:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2653: 
1.47      www      2654:     my $namevalue='';
1.800     albertel 2655:     foreach my $key (keys(%$storehash)) {
                   2656:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2657:     }
1.47      www      2658:     $namevalue=~s/\&$//;
1.187     www      2659:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2660:     return critical
                   2661:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2662: }
                   2663: 
1.9       www      2664: # --------------------------------------------------------------------- Restore
                   2665: 
                   2666: sub restore {
1.124     www      2667:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2668:     my $home='';
                   2669: 
1.168     albertel 2670:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2671: 
1.122     albertel 2672:     if (!$symb) {
                   2673:       unless ($symb=escape(&symbread())) { return ''; }
                   2674:     } else {
1.213     www      2675:       $symb=&escape(&symbclean($symb));
1.122     albertel 2676:     }
1.188     www      2677:     if (!$namespace) { 
1.620     albertel 2678:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2679:           return ''; 
                   2680:        } 
                   2681:     }
1.620     albertel 2682:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2683:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2684:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2685:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2686: 
1.12      www      2687:     my %returnhash=();
1.800     albertel 2688:     foreach my $line (split(/\&/,$answer)) {
                   2689: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2690:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2691:     }
1.75      www      2692:     my $version;
                   2693:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2694:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2695:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2696:        }
1.75      www      2697:     }
1.13      www      2698:     return %returnhash;
1.34      www      2699: }
                   2700: 
                   2701: # ---------------------------------------------------------- Course Description
                   2702: 
                   2703: sub coursedescription {
1.731     albertel 2704:     my ($courseid,$args)=@_;
1.34      www      2705:     $courseid=~s/^\///;
1.49      www      2706:     $courseid=~s/\_/\//g;
1.34      www      2707:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2708:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2709:     my $normalid=$cdomain.'_'.$cnum;
                   2710:     # need to always cache even if we get errors otherwise we keep 
                   2711:     # trying and trying and trying to get the course description.
                   2712:     my %envhash=();
                   2713:     my %returnhash=();
1.731     albertel 2714:     
                   2715:     my $expiretime=600;
                   2716:     if ($env{'request.course.id'} eq $normalid) {
                   2717: 	$expiretime=120;
                   2718:     }
                   2719: 
                   2720:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2721:     if (!$args->{'freshen_cache'}
                   2722: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2723: 	foreach my $key (keys(%env)) {
                   2724: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2725: 	    my ($setting) = $1;
                   2726: 	    $returnhash{$setting} = $env{$key};
                   2727: 	}
                   2728: 	return %returnhash;
                   2729:     }
                   2730: 
                   2731:     # get the data agin
                   2732:     if (!$args->{'one_time'}) {
                   2733: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2734:     }
1.811     albertel 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.811     albertel 2891:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
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.811     albertel 2922:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\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)) {
1.812     raeburn  3047:       next if ($key =~ /^error: 2 /);
1.800     albertel 3048:       push(@keyarray,&unescape($key));
1.407     www      3049:    }
                   3050:    return @keyarray;
1.318     matthew  3051: }
                   3052: 
1.319     matthew  3053: # --------------------------------------------------------------- currentdump
                   3054: sub currentdump {
1.328     matthew  3055:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3056:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3057:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3058:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3059:    my $uhome = &homeserver($sname,$sdom);
                   3060:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3061:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3062:    #
1.318     matthew  3063:    my %returnhash=();
1.319     matthew  3064:    #
                   3065:    if ($rep eq "unknown_cmd") { 
                   3066:        # an old lond will not know currentdump
                   3067:        # Do a dump and make it look like a currentdump
1.326     matthew  3068:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3069:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3070:        my %hash = @tmp;
                   3071:        @tmp=();
1.424     matthew  3072:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3073:    } else {
                   3074:        my @pairs=split(/\&/,$rep);
1.800     albertel 3075:        foreach my $pair (@pairs) {
                   3076:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3077:            my ($symb,$param) = split(/:/,$key);
                   3078:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3079:                                                         &thaw_unescape($value);
1.319     matthew  3080:        }
1.191     harris41 3081:    }
1.12      www      3082:    return %returnhash;
1.424     matthew  3083: }
                   3084: 
                   3085: sub convert_dump_to_currentdump{
                   3086:     my %hash = %{shift()};
                   3087:     my %returnhash;
                   3088:     # Code ripped from lond, essentially.  The only difference
                   3089:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3090:     # we might run in to problems with parameter names =~ /^v\./
                   3091:     while (my ($key,$value) = each(%hash)) {
                   3092:         my ($v,$symb,$param) = split(/:/,$key);
                   3093:         next if ($v eq 'version' || $symb eq 'keys');
                   3094:         next if (exists($returnhash{$symb}) &&
                   3095:                  exists($returnhash{$symb}->{$param}) &&
                   3096:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3097:         $returnhash{$symb}->{$param}=$value;
                   3098:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3099:     }
                   3100:     #
                   3101:     # Remove all of the keys in the hashes which keep track of
                   3102:     # the version of the parameter.
                   3103:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3104:         # use a foreach because we are going to delete from the hash.
                   3105:         foreach my $key (keys(%$param_hash)) {
                   3106:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3107:         }
                   3108:     }
                   3109:     return \%returnhash;
1.12      www      3110: }
                   3111: 
1.627     albertel 3112: # ------------------------------------------------------ critical inc interface
                   3113: 
                   3114: sub cinc {
                   3115:     return &inc(@_,'critical');
                   3116: }
                   3117: 
1.449     matthew  3118: # --------------------------------------------------------------- inc interface
                   3119: 
                   3120: sub inc {
1.627     albertel 3121:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3122:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3123:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3124:     my $uhome=&homeserver($uname,$udomain);
                   3125:     my $items='';
                   3126:     if (! ref($store)) {
                   3127:         # got a single value, so use that instead
                   3128:         $items = &escape($store).'=&';
                   3129:     } elsif (ref($store) eq 'SCALAR') {
                   3130:         $items = &escape($$store).'=&';        
                   3131:     } elsif (ref($store) eq 'ARRAY') {
                   3132:         $items = join('=&',map {&escape($_);} @{$store});
                   3133:     } elsif (ref($store) eq 'HASH') {
                   3134:         while (my($key,$value) = each(%{$store})) {
                   3135:             $items.= &escape($key).'='.&escape($value).'&';
                   3136:         }
                   3137:     }
                   3138:     $items=~s/\&$//;
1.627     albertel 3139:     if ($critical) {
                   3140: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3141:     } else {
                   3142: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3143:     }
1.449     matthew  3144: }
                   3145: 
1.12      www      3146: # --------------------------------------------------------------- put interface
                   3147: 
                   3148: sub put {
1.134     albertel 3149:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3150:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3151:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3152:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3153:    my $items='';
1.800     albertel 3154:    foreach my $item (keys(%$storehash)) {
                   3155:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3156:    }
1.12      www      3157:    $items=~s/\&$//;
1.134     albertel 3158:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3159: }
                   3160: 
1.631     albertel 3161: # ------------------------------------------------------------ newput interface
                   3162: 
                   3163: sub newput {
                   3164:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3165:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3166:    if (!$uname) { $uname=$env{'user.name'}; }
                   3167:    my $uhome=&homeserver($uname,$udomain);
                   3168:    my $items='';
                   3169:    foreach my $key (keys(%$storehash)) {
                   3170:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3171:    }
                   3172:    $items=~s/\&$//;
                   3173:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3174: }
                   3175: 
                   3176: # ---------------------------------------------------------  putstore interface
                   3177: 
1.524     raeburn  3178: sub putstore {
1.715     albertel 3179:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3180:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3181:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3182:    my $uhome=&homeserver($uname,$udomain);
                   3183:    my $items='';
1.715     albertel 3184:    foreach my $key (keys(%$storehash)) {
                   3185:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3186:    }
1.715     albertel 3187:    $items=~s/\&$//;
1.716     albertel 3188:    my $esc_symb=&escape($symb);
                   3189:    my $esc_v=&escape($version);
1.715     albertel 3190:    my $reply =
1.716     albertel 3191:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3192: 	      $uhome);
                   3193:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3194:        # gfall back to way things use to be done
1.715     albertel 3195:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3196: 			    $uname);
1.524     raeburn  3197:    }
1.715     albertel 3198:    return $reply;
                   3199: }
                   3200: 
                   3201: sub old_putstore {
1.716     albertel 3202:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3203:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3204:     if (!$uname) { $uname=$env{'user.name'}; }
                   3205:     my $uhome=&homeserver($uname,$udomain);
                   3206:     my %newstorehash;
1.800     albertel 3207:     foreach my $item (keys(%$storehash)) {
                   3208: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3209: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3210:     }
                   3211:     my $items='';
                   3212:     my %allitems = ();
1.800     albertel 3213:     foreach my $item (keys(%newstorehash)) {
                   3214: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3215: 	    my $key = $1.':keys:'.$2;
                   3216: 	    $allitems{$key} .= $3.':';
                   3217: 	}
1.800     albertel 3218: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3219:     }
1.800     albertel 3220:     foreach my $item (keys(%allitems)) {
                   3221: 	$allitems{$item} =~ s/\:$//;
                   3222: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3223:     }
                   3224:     $items=~s/\&$//;
                   3225:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3226: }
                   3227: 
1.47      www      3228: # ------------------------------------------------------ critical put interface
                   3229: 
                   3230: sub cput {
1.134     albertel 3231:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3232:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3233:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3234:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3235:    my $items='';
1.800     albertel 3236:    foreach my $item (keys(%$storehash)) {
                   3237:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3238:    }
1.47      www      3239:    $items=~s/\&$//;
1.134     albertel 3240:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3241: }
                   3242: 
                   3243: # -------------------------------------------------------------- eget interface
                   3244: 
                   3245: sub eget {
1.133     albertel 3246:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3247:    my $items='';
1.800     albertel 3248:    foreach my $item (@$storearr) {
                   3249:        $items.=&escape($item).'&';
1.191     harris41 3250:    }
1.12      www      3251:    $items=~s/\&$//;
1.620     albertel 3252:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3253:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3254:    my $uhome=&homeserver($uname,$udomain);
                   3255:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3256:    my @pairs=split(/\&/,$rep);
                   3257:    my %returnhash=();
1.42      www      3258:    my $i=0;
1.800     albertel 3259:    foreach my $item (@$storearr) {
                   3260:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3261:       $i++;
1.191     harris41 3262:    }
1.12      www      3263:    return %returnhash;
                   3264: }
                   3265: 
1.667     albertel 3266: # ------------------------------------------------------------ tmpput interface
                   3267: sub tmpput {
1.802     raeburn  3268:     my ($storehash,$server,$context)=@_;
1.667     albertel 3269:     my $items='';
1.800     albertel 3270:     foreach my $item (keys(%$storehash)) {
                   3271: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3272:     }
                   3273:     $items=~s/\&$//;
1.802     raeburn  3274:     if (defined($context)) {
                   3275:         $items .= ':'.&escape($context);
                   3276:     }
1.667     albertel 3277:     return &reply("tmpput:$items",$server);
                   3278: }
                   3279: 
                   3280: # ------------------------------------------------------------ tmpget interface
                   3281: sub tmpget {
1.688     albertel 3282:     my ($token,$server)=@_;
                   3283:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3284:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3285:     my %returnhash;
                   3286:     foreach my $item (split(/\&/,$rep)) {
                   3287: 	my ($key,$value)=split(/=/,$item);
                   3288: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3289:     }
                   3290:     return %returnhash;
                   3291: }
                   3292: 
1.688     albertel 3293: # ------------------------------------------------------------ tmpget interface
                   3294: sub tmpdel {
                   3295:     my ($token,$server)=@_;
                   3296:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3297:     return &reply("tmpdel:$token",$server);
                   3298: }
                   3299: 
1.765     albertel 3300: # -------------------------------------------------- portfolio access checking
                   3301: 
                   3302: sub portfolio_access {
1.766     albertel 3303:     my ($requrl) = @_;
1.765     albertel 3304:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3305:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3306:     if ($result eq 'ok') {
1.766     albertel 3307:        return 'F';
1.765     albertel 3308:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3309:        return 'A';
1.765     albertel 3310:     }
1.766     albertel 3311:     return '';
1.765     albertel 3312: }
                   3313: 
                   3314: sub get_portfolio_access {
1.767     albertel 3315:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3316: 
                   3317:     if (!ref($access_hash)) {
                   3318: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3319: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3320: 						   $file_name);
                   3321: 	$access_hash = $access_controls{$file_name};
                   3322:     }
                   3323: 
1.765     albertel 3324:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3325:     my $now = time;
                   3326:     if (ref($access_hash) eq 'HASH') {
                   3327:         foreach my $key (keys(%{$access_hash})) {
                   3328:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3329:             if ($start > $now) {
                   3330:                 next;
                   3331:             }
                   3332:             if ($end && $end<$now) {
                   3333:                 next;
                   3334:             }
                   3335:             if ($scope eq 'public') {
                   3336:                 $public = $key;
                   3337:                 last;
                   3338:             } elsif ($scope eq 'guest') {
                   3339:                 $guest = $key;
                   3340:             } elsif ($scope eq 'domains') {
                   3341:                 push(@domains,$key);
                   3342:             } elsif ($scope eq 'users') {
                   3343:                 push(@users,$key);
                   3344:             } elsif ($scope eq 'course') {
                   3345:                 push(@courses,$key);
                   3346:             } elsif ($scope eq 'group') {
                   3347:                 push(@groups,$key);
                   3348:             }
                   3349:         }
                   3350:         if ($public) {
                   3351:             return 'ok';
                   3352:         }
                   3353:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3354:             if ($guest) {
                   3355:                 return $guest;
                   3356:             }
                   3357:         } else {
                   3358:             if (@domains > 0) {
                   3359:                 foreach my $domkey (@domains) {
                   3360:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3361:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3362:                             return 'ok';
                   3363:                         }
                   3364:                     }
                   3365:                 }
                   3366:             }
                   3367:             if (@users > 0) {
                   3368:                 foreach my $userkey (@users) {
                   3369:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3370:                         return 'ok';
                   3371:                     }
                   3372:                 }
                   3373:             }
                   3374:             my %roleshash;
                   3375:             my @courses_and_groups = @courses;
                   3376:             push(@courses_and_groups,@groups); 
                   3377:             if (@courses_and_groups > 0) {
                   3378:                 my (%allgroups,%allroles); 
                   3379:                 my ($start,$end,$role,$sec,$group);
                   3380:                 foreach my $envkey (%env) {
1.811     albertel 3381:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3382:                         my $cid = $2.'_'.$3; 
                   3383:                         if ($1 eq 'gr') {
                   3384:                             $group = $4;
                   3385:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3386:                         } else {
                   3387:                             if ($4 eq '') {
                   3388:                                 $sec = 'none';
                   3389:                             } else {
                   3390:                                 $sec = $4;
                   3391:                             }
                   3392:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3393:                         }
1.811     albertel 3394:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3395:                         my $cid = $2.'_'.$3;
                   3396:                         if ($4 eq '') {
                   3397:                             $sec = 'none';
                   3398:                         } else {
                   3399:                             $sec = $4;
                   3400:                         }
                   3401:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3402:                     }
                   3403:                 }
                   3404:                 if (keys(%allroles) == 0) {
                   3405:                     return;
                   3406:                 }
                   3407:                 foreach my $key (@courses_and_groups) {
                   3408:                     my %content = %{$$access_hash{$key}};
                   3409:                     my $cnum = $content{'number'};
                   3410:                     my $cdom = $content{'domain'};
                   3411:                     my $cid = $cdom.'_'.$cnum;
                   3412:                     if (!exists($allroles{$cid})) {
                   3413:                         next;
                   3414:                     }    
                   3415:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3416:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3417:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3418:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3419:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3420:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3421:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3422:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3423:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3424:                                         if (grep/^all$/,@sections) {
                   3425:                                             return 'ok';
                   3426:                                         } else {
                   3427:                                             if (grep/^$sec$/,@sections) {
                   3428:                                                 return 'ok';
                   3429:                                             }
                   3430:                                         }
                   3431:                                     }
                   3432:                                 }
                   3433:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3434:                                     if (grep/^none$/,@groups) {
                   3435:                                         return 'ok';
                   3436:                                     }
                   3437:                                 } else {
                   3438:                                     if (grep/^all$/,@groups) {
                   3439:                                         return 'ok';
                   3440:                                     } 
                   3441:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3442:                                         if (grep/^$group$/,@groups) {
                   3443:                                             return 'ok';
                   3444:                                         }
                   3445:                                     }
                   3446:                                 } 
                   3447:                             }
                   3448:                         }
                   3449:                     }
                   3450:                 }
                   3451:             }
                   3452:             if ($guest) {
                   3453:                 return $guest;
                   3454:             }
                   3455:         }
                   3456:     }
                   3457:     return;
                   3458: }
                   3459: 
                   3460: sub course_group_datechecker {
                   3461:     my ($dates,$now,$status) = @_;
                   3462:     my ($start,$end) = split(/\./,$dates);
                   3463:     if (!$start && !$end) {
                   3464:         return 'ok';
                   3465:     }
                   3466:     if (grep/^active$/,@{$status}) {
                   3467:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3468:             return 'ok';
                   3469:         }
                   3470:     }
                   3471:     if (grep/^previous$/,@{$status}) {
                   3472:         if ($end > $now ) {
                   3473:             return 'ok';
                   3474:         }
                   3475:     }
                   3476:     if (grep/^future$/,@{$status}) {
                   3477:         if ($start > $now) {
                   3478:             return 'ok';
                   3479:         }
                   3480:     }
                   3481:     return; 
                   3482: }
                   3483: 
                   3484: sub parse_portfolio_url {
                   3485:     my ($url) = @_;
                   3486: 
                   3487:     my ($type,$udom,$unum,$group,$file_name);
                   3488:     
1.807     albertel 3489:     if ($url =~  m-^/*uploaded/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3490: 	$type = 1;
                   3491:         $udom = $1;
                   3492:         $unum = $2;
                   3493:         $file_name = $3;
1.811     albertel 3494:     } elsif ($url =~ m-^/*uploaded/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3495: 	$type = 2;
                   3496:         $udom = $1;
                   3497:         $unum = $2;
                   3498:         $group = $3;
                   3499:         $file_name = $3.'/'.$4;
                   3500:     }
                   3501:     if (wantarray) {
                   3502: 	return ($type,$udom,$unum,$file_name,$group);
                   3503:     }
                   3504:     return $type;
                   3505: }
                   3506: 
                   3507: sub is_portfolio_url {
                   3508:     my ($url) = @_;
                   3509:     return scalar(&parse_portfolio_url($url));
                   3510: }
                   3511: 
1.798     raeburn  3512: sub is_portfolio_file {
                   3513:     my ($file) = @_;
1.811     albertel 3514:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w\/portfolio/)) {
1.798     raeburn  3515:         return 1;
                   3516:     }
                   3517:     return;
                   3518: }
                   3519: 
                   3520: 
1.341     www      3521: # ---------------------------------------------- Custom access rule evaluation
                   3522: 
                   3523: sub customaccess {
                   3524:     my ($priv,$uri)=@_;
1.807     albertel 3525:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.343     www      3526:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3527:     $udom = &LONCAPA::clean_domain($udom);
                   3528:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3529:     my $access=0;
1.800     albertel 3530:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3531: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3532:         if ($role) {
                   3533: 	   if ($role ne $urole) { next; }
                   3534:         }
1.800     albertel 3535:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3536:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3537:             if ($tdom) {
                   3538: 		if ($tdom ne $udom) { next; }
                   3539:             }
                   3540:             if ($tcrs) {
                   3541: 		if ($tcrs ne $ucrs) { next; }
                   3542:             }
                   3543:             if ($tsec) {
                   3544: 		if ($tsec ne $usec) { next; }
                   3545:             }
                   3546:             $access=($effect eq 'allow');
                   3547:             last;
1.342     www      3548:         }
1.402     bowersj2 3549: 	if ($realm eq '' && $role eq '') {
                   3550:             $access=($effect eq 'allow');
                   3551: 	}
1.341     www      3552:     }
                   3553:     return $access;
                   3554: }
                   3555: 
1.103     harris41 3556: # ------------------------------------------------- Check for a user privilege
1.12      www      3557: 
                   3558: sub allowed {
1.810     raeburn  3559:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3560:     my $ver_orguri=$uri;
1.439     www      3561:     $uri=&deversion($uri);
1.152     www      3562:     my $orguri=$uri;
1.52      www      3563:     $uri=&declutter($uri);
1.809     raeburn  3564: 
1.810     raeburn  3565:     if ($priv eq 'evb') {
                   3566: # Evade communication block restrictions for specified role in a course
                   3567:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3568:             return $1;
                   3569:         } else {
                   3570:             return;
                   3571:         }
                   3572:     }
                   3573: 
1.620     albertel 3574:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3575: # Free bre access to adm and meta resources
1.775     albertel 3576:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3577: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3578: 	&& ($priv eq 'bre')) {
1.14      www      3579: 	return 'F';
1.159     www      3580:     }
                   3581: 
1.545     banghart 3582: # Free bre access to user's own portfolio contents
1.714     raeburn  3583:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3584:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3585: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3586:         return 'F';
                   3587:     }
                   3588: 
1.762     raeburn  3589: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3590:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3591:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3592:         if (exists($env{'request.course.id'})) {
                   3593:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3594:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3595:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3596:                 my $courseprivid=$env{'request.course.id'};
                   3597:                 $courseprivid=~s/\_/\//;
                   3598:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3599:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3600:                     return $1; 
1.762     raeburn  3601:                 } else {
                   3602:                     if ($env{'request.course.sec'}) {
                   3603:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3604:                     }
                   3605:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3606:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3607:                         return $2;
                   3608:                     }
1.714     raeburn  3609:                 }
                   3610:             }
                   3611:         }
                   3612:     }
                   3613: 
1.159     www      3614: # Free bre to public access
                   3615: 
                   3616:     if ($priv eq 'bre') {
1.238     www      3617:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3618: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3619:            return 'F'; 
                   3620:         }
1.238     www      3621:         if ($copyright eq 'priv') {
                   3622:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3623: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3624: 		return '';
                   3625:             }
                   3626:         }
                   3627:         if ($copyright eq 'domain') {
                   3628:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3629: 	    unless (($env{'user.domain'} eq $1) ||
                   3630:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3631: 		return '';
                   3632:             }
1.262     matthew  3633:         }
1.620     albertel 3634:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3635:             # Library role, so allow browsing of resources in this domain.
                   3636:             return 'F';
1.238     www      3637:         }
1.341     www      3638:         if ($copyright eq 'custom') {
                   3639: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3640:         }
1.14      www      3641:     }
1.264     matthew  3642:     # Domain coordinator is trying to create a course
1.620     albertel 3643:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3644:         # uri is the requested domain in this case.
                   3645:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3646:         # a role of dc for the domain in question.
1.620     albertel 3647:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3648:     }
1.29      www      3649: 
1.52      www      3650:     my $thisallowed='';
                   3651:     my $statecond=0;
                   3652:     my $courseprivid='';
                   3653: 
                   3654: # Course
                   3655: 
1.620     albertel 3656:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3657:        $thisallowed.=$1;
                   3658:     }
1.29      www      3659: 
1.52      www      3660: # Domain
                   3661: 
1.620     albertel 3662:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3663:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3664:        $thisallowed.=$1;
                   3665:     }
1.52      www      3666: 
                   3667: # Course: uri itself is a course
1.66      www      3668:     my $courseuri=$uri;
                   3669:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3670:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3671: 
1.620     albertel 3672:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3673:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3674:        $thisallowed.=$1;
                   3675:     }
1.29      www      3676: 
1.665     albertel 3677: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3678: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3679:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3680: 	$thisallowed='';
1.671     raeburn  3681:         my ($match)=&is_on_map($uri);
                   3682:         if ($match) {
                   3683:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3684:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3685:                 $thisallowed.=$1;
                   3686:             }
                   3687:         } else {
1.705     albertel 3688:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3689:             if ($refuri) {
                   3690:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3691:                     $thisallowed='F';
1.671     raeburn  3692:                 } else {
                   3693:                     $refuri=&declutter($refuri);
                   3694:                     my ($match) = &is_on_map($refuri);
                   3695:                     if ($match) {
                   3696:                         $thisallowed='F';
                   3697:                     }
1.669     raeburn  3698:                 }
1.671     raeburn  3699:             }
                   3700:         }
1.314     www      3701:     }
1.492     albertel 3702: 
1.766     albertel 3703:     if ($priv eq 'bre'
                   3704: 	&& $thisallowed ne 'F' 
                   3705: 	&& $thisallowed ne '2'
                   3706: 	&& &is_portfolio_url($uri)) {
                   3707: 	$thisallowed = &portfolio_access($uri);
                   3708:     }
                   3709:     
1.52      www      3710: # Full access at system, domain or course-wide level? Exit.
1.29      www      3711: 
                   3712:     if ($thisallowed=~/F/) {
                   3713: 	return 'F';
                   3714:     }
                   3715: 
1.52      www      3716: # If this is generating or modifying users, exit with special codes
1.29      www      3717: 
1.643     www      3718:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3719: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3720: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3721: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3722: 	    unless ($auname) { return $thisallowed; }
                   3723: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3724: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3725: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3726: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3727: 	}
1.52      www      3728: 	return $thisallowed;
                   3729:     }
                   3730: #
1.103     harris41 3731: # Gathered so far: system, domain and course wide privileges
1.52      www      3732: #
                   3733: # Course: See if uri or referer is an individual resource that is part of 
                   3734: # the course
                   3735: 
1.620     albertel 3736:     if ($env{'request.course.id'}) {
1.232     www      3737: 
1.620     albertel 3738:        $courseprivid=$env{'request.course.id'};
                   3739:        if ($env{'request.course.sec'}) {
                   3740:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3741:        }
                   3742:        $courseprivid=~s/\_/\//;
                   3743:        my $checkreferer=1;
1.232     www      3744:        my ($match,$cond)=&is_on_map($uri);
                   3745:        if ($match) {
                   3746:            $statecond=$cond;
1.620     albertel 3747:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3748:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3749:                $thisallowed.=$1;
                   3750:                $checkreferer=0;
                   3751:            }
1.29      www      3752:        }
1.83      www      3753:        
1.148     www      3754:        if ($checkreferer) {
1.620     albertel 3755: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3756:             unless ($refuri) {
1.800     albertel 3757:                 foreach my $key (keys(%env)) {
                   3758: 		    if ($key=~/^httpref\..*\*/) {
                   3759: 			my $pattern=$key;
1.156     www      3760:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3761:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3762:                         $pattern=~s/\//\\\//g;
1.152     www      3763:                         if ($orguri=~/$pattern/) {
1.800     albertel 3764: 			    $refuri=$env{$key};
1.148     www      3765:                         }
                   3766:                     }
1.191     harris41 3767:                 }
1.148     www      3768:             }
1.232     www      3769: 
1.148     www      3770:          if ($refuri) { 
1.152     www      3771: 	  $refuri=&declutter($refuri);
1.232     www      3772:           my ($match,$cond)=&is_on_map($refuri);
                   3773:             if ($match) {
                   3774:               my $refstatecond=$cond;
1.620     albertel 3775:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3776:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3777:                   $thisallowed.=$1;
1.53      www      3778:                   $uri=$refuri;
                   3779:                   $statecond=$refstatecond;
1.52      www      3780:               }
                   3781:           }
1.148     www      3782:         }
1.29      www      3783:        }
1.52      www      3784:    }
1.29      www      3785: 
1.52      www      3786: #
1.103     harris41 3787: # Gathered now: all privileges that could apply, and condition number
1.52      www      3788: # 
                   3789: #
                   3790: # Full or no access?
                   3791: #
1.29      www      3792: 
1.52      www      3793:     if ($thisallowed=~/F/) {
                   3794: 	return 'F';
                   3795:     }
1.29      www      3796: 
1.52      www      3797:     unless ($thisallowed) {
                   3798:         return '';
                   3799:     }
1.29      www      3800: 
1.52      www      3801: # Restrictions exist, deal with them
                   3802: #
                   3803: #   C:according to course preferences
                   3804: #   R:according to resource settings
                   3805: #   L:unless locked
                   3806: #   X:according to user session state
                   3807: #
                   3808: 
                   3809: # Possibly locked functionality, check all courses
1.54      www      3810: # Locks might take effect only after 10 minutes cache expiration for other
                   3811: # courses, and 2 minutes for current course
1.52      www      3812: 
                   3813:     my $envkey;
                   3814:     if ($thisallowed=~/L/) {
1.620     albertel 3815:         foreach $envkey (keys %env) {
1.54      www      3816:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3817:                my $courseid=$2;
                   3818:                my $roleid=$1.'.'.$2;
1.92      www      3819:                $courseid=~s/^\///;
1.54      www      3820:                my $expiretime=600;
1.620     albertel 3821:                if ($env{'request.role'} eq $roleid) {
1.54      www      3822: 		  $expiretime=120;
                   3823:                }
                   3824: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3825:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3826:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3827: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3828:                }
1.620     albertel 3829:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3830:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3831: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3832:                        &log($env{'user.domain'},$env{'user.name'},
                   3833:                             $env{'user.home'},
1.57      www      3834:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3835:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3836:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3837: 		       return '';
                   3838:                    }
                   3839:                }
1.620     albertel 3840:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3841:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3842: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3843:                        &log($env{'user.domain'},$env{'user.name'},
                   3844:                             $env{'user.home'},
1.57      www      3845:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3846:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3847:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3848: 		       return '';
                   3849:                    }
                   3850:                }
                   3851: 	   }
1.29      www      3852:        }
1.52      www      3853:     }
                   3854:    
                   3855: #
                   3856: # Rest of the restrictions depend on selected course
                   3857: #
                   3858: 
1.620     albertel 3859:     unless ($env{'request.course.id'}) {
1.766     albertel 3860: 	if ($thisallowed eq 'A') {
                   3861: 	    return 'A';
                   3862: 	} else {
                   3863: 	    return '1';
                   3864: 	}
1.52      www      3865:     }
1.29      www      3866: 
1.52      www      3867: #
                   3868: # Now user is definitely in a course
                   3869: #
1.53      www      3870: 
                   3871: 
                   3872: # Course preferences
                   3873: 
                   3874:    if ($thisallowed=~/C/) {
1.620     albertel 3875:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3876:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3877:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3878: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3879: 	   if ($priv ne 'pch') { 
                   3880: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3881: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3882: 			$env{'request.course.id'});
                   3883: 	   }
1.237     www      3884:            return '';
                   3885:        }
                   3886: 
1.620     albertel 3887:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3888: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3889: 	   if ($priv ne 'pch') { 
                   3890: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3891: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3892: 			$env{'request.course.id'});
                   3893: 	   }
1.54      www      3894:            return '';
                   3895:        }
1.53      www      3896:    }
                   3897: 
                   3898: # Resource preferences
                   3899: 
                   3900:    if ($thisallowed=~/R/) {
1.620     albertel 3901:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3902:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3903: 	   if ($priv ne 'pch') { 
                   3904: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3905: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3906: 	   }
                   3907: 	   return '';
1.54      www      3908:        }
1.53      www      3909:    }
1.30      www      3910: 
1.246     www      3911: # Restricted by state or randomout?
1.30      www      3912: 
1.52      www      3913:    if ($thisallowed=~/X/) {
1.620     albertel 3914:       if ($env{'acc.randomout'}) {
1.579     albertel 3915: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3916:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3917:             return ''; 
                   3918:          }
1.247     www      3919:       }
                   3920:       if (&condval($statecond)) {
1.52      www      3921: 	 return '2';
                   3922:       } else {
                   3923:          return '';
                   3924:       }
                   3925:    }
1.30      www      3926: 
1.766     albertel 3927:     if ($thisallowed eq 'A') {
                   3928: 	return 'A';
                   3929:     }
1.52      www      3930:    return 'F';
1.232     www      3931: }
                   3932: 
1.710     albertel 3933: sub split_uri_for_cond {
                   3934:     my $uri=&deversion(&declutter(shift));
                   3935:     my @uriparts=split(/\//,$uri);
                   3936:     my $filename=pop(@uriparts);
                   3937:     my $pathname=join('/',@uriparts);
                   3938:     return ($pathname,$filename);
                   3939: }
1.232     www      3940: # --------------------------------------------------- Is a resource on the map?
                   3941: 
                   3942: sub is_on_map {
1.710     albertel 3943:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3944:     #Trying to find the conditional for the file
1.620     albertel 3945:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3946: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3947:     if ($match) {
1.289     bowersj2 3948: 	return (1,$1);
                   3949:     } else {
1.434     www      3950: 	return (0,0);
1.289     bowersj2 3951:     }
1.12      www      3952: }
                   3953: 
1.427     www      3954: # --------------------------------------------------------- Get symb from alias
                   3955: 
                   3956: sub get_symb_from_alias {
                   3957:     my $symb=shift;
                   3958:     my ($map,$resid,$url)=&decode_symb($symb);
                   3959: # Already is a symb
                   3960:     if ($url) { return $symb; }
                   3961: # Must be an alias
                   3962:     my $aliassymb='';
                   3963:     my %bighash;
1.620     albertel 3964:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3965:                             &GDBM_READER(),0640)) {
                   3966:         my $rid=$bighash{'mapalias_'.$symb};
                   3967: 	if ($rid) {
                   3968: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3969: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3970: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3971: 	}
                   3972:         untie %bighash;
                   3973:     }
                   3974:     return $aliassymb;
                   3975: }
                   3976: 
1.12      www      3977: # ----------------------------------------------------------------- Define Role
                   3978: 
                   3979: sub definerole {
                   3980:   if (allowed('mcr','/')) {
                   3981:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 3982:     foreach my $role (split(':',$sysrole)) {
                   3983: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3984:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3985:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3986: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3987:                return "refused:s:$crole&$cqual"; 
                   3988:             }
                   3989:         }
1.191     harris41 3990:     }
1.800     albertel 3991:     foreach my $role (split(':',$domrole)) {
                   3992: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3993:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3994:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3995: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3996:                return "refused:d:$crole&$cqual"; 
                   3997:             }
                   3998:         }
1.191     harris41 3999:     }
1.800     albertel 4000:     foreach my $role (split(':',$courole)) {
                   4001: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4002:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4003:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4004: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4005:                return "refused:c:$crole&$cqual"; 
                   4006:             }
                   4007:         }
1.191     harris41 4008:     }
1.620     albertel 4009:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4010:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4011: 	        "rolesdef_$rolename=".
                   4012:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4013:     return reply($command,$env{'user.home'});
1.12      www      4014:   } else {
                   4015:     return 'refused';
                   4016:   }
1.105     harris41 4017: }
                   4018: 
                   4019: # ---------------- Make a metadata query against the network of library servers
                   4020: 
                   4021: sub metadata_query {
1.244     matthew  4022:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4023:     my %rhash;
1.244     matthew  4024:     my @server_list = (defined($server_array) ? @$server_array
                   4025:                                               : keys(%libserv) );
                   4026:     for my $server (@server_list) {
1.118     harris41 4027: 	unless ($custom or $customshow) {
                   4028: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4029: 	    $rhash{$server}=$reply;
                   4030: 	}
                   4031: 	else {
                   4032: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4033: 			     &escape($custom).':'.&escape($customshow),
                   4034: 			     $server);
                   4035: 	    $rhash{$server}=$reply;
                   4036: 	}
1.112     harris41 4037:     }
1.118     harris41 4038:     return \%rhash;
1.240     www      4039: }
                   4040: 
                   4041: # ----------------------------------------- Send log queries and wait for reply
                   4042: 
                   4043: sub log_query {
                   4044:     my ($uname,$udom,$query,%filters)=@_;
                   4045:     my $uhome=&homeserver($uname,$udom);
                   4046:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4047:     my $uhost=$hostname{$uhome};
1.800     albertel 4048:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4049:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4050:                        $uhome);
1.479     albertel 4051:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4052:     return get_query_reply($queryid);
                   4053: }
                   4054: 
1.508     raeburn  4055: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4056: 
                   4057: sub fetch_enrollment_query {
1.511     raeburn  4058:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4059:     my $homeserver;
1.547     raeburn  4060:     my $maxtries = 1;
1.508     raeburn  4061:     if ($context eq 'automated') {
                   4062:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4063:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4064:     } else {
                   4065:         $homeserver = &homeserver($cnum,$dom);
                   4066:     }
1.506     raeburn  4067:     my $host=$hostname{$homeserver};
                   4068:     my $cmd = '';
1.800     albertel 4069:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4070:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4071:     }
                   4072:     $cmd =~ s/%%$//;
                   4073:     $cmd = &escape($cmd);
                   4074:     my $query = 'fetchenrollment';
1.620     albertel 4075:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4076:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4077:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4078:         return 'error: '.$queryid;
                   4079:     }
1.506     raeburn  4080:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4081:     my $tries = 1;
                   4082:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4083:         $reply = &get_query_reply($queryid);
                   4084:         $tries ++;
                   4085:     }
1.526     raeburn  4086:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4087:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4088:     } else {
1.515     raeburn  4089:         my @responses = split/:/,$reply;
                   4090:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4091:             foreach my $line (@responses) {
                   4092:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4093:                 $$replyref{$key} = $value;
                   4094:             }
                   4095:         } else {
1.506     raeburn  4096:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4097:             foreach my $line (@responses) {
                   4098:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4099:                 $$replyref{$key} = $value;
                   4100:                 if ($value > 0) {
1.800     albertel 4101:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4102:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4103:                         my $destname = $pathname.'/'.$filename;
                   4104:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4105:                         if ($xml_classlist =~ /^error/) {
                   4106:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4107:                         } else {
1.506     raeburn  4108:                             if ( open(FILE,">$destname") ) {
                   4109:                                 print FILE &unescape($xml_classlist);
                   4110:                                 close(FILE);
1.526     raeburn  4111:                             } else {
                   4112:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4113:                             }
                   4114:                         }
                   4115:                     }
                   4116:                 }
                   4117:             }
                   4118:         }
                   4119:         return 'ok';
                   4120:     }
                   4121:     return 'error';
                   4122: }
                   4123: 
1.242     www      4124: sub get_query_reply {
                   4125:     my $queryid=shift;
1.240     www      4126:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4127:     my $reply='';
                   4128:     for (1..100) {
                   4129: 	sleep 2;
                   4130:         if (-e $replyfile.'.end') {
1.448     albertel 4131: 	    if (open(my $fh,$replyfile)) {
1.240     www      4132:                $reply.=<$fh>;
1.448     albertel 4133:                close($fh);
1.240     www      4134: 	   } else { return 'error: reply_file_error'; }
1.242     www      4135:            return &unescape($reply);
                   4136: 	}
1.240     www      4137:     }
1.242     www      4138:     return 'timeout:'.$queryid;
1.240     www      4139: }
                   4140: 
                   4141: sub courselog_query {
1.241     www      4142: #
                   4143: # possible filters:
                   4144: # url: url or symb
                   4145: # username
                   4146: # domain
                   4147: # action: view, submit, grade
                   4148: # start: timestamp
                   4149: # end: timestamp
                   4150: #
1.240     www      4151:     my (%filters)=@_;
1.620     albertel 4152:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4153:     if ($filters{'url'}) {
                   4154: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4155:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4156:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4157:     }
1.620     albertel 4158:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4159:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4160:     return &log_query($cname,$cdom,'courselog',%filters);
                   4161: }
                   4162: 
                   4163: sub userlog_query {
                   4164:     my ($uname,$udom,%filters)=@_;
                   4165:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4166: }
                   4167: 
1.506     raeburn  4168: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4169: 
                   4170: sub auto_run {
1.508     raeburn  4171:     my ($cnum,$cdom) = @_;
                   4172:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4173:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4174:     return $response;
                   4175: }
1.776     albertel 4176: 
1.506     raeburn  4177: sub auto_get_sections {
1.508     raeburn  4178:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4179:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4180:     my @secs = ();
1.511     raeburn  4181:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4182:     unless ($response eq 'refused') {
                   4183:         @secs = split/:/,$response;
                   4184:     }
                   4185:     return @secs;
                   4186: }
1.776     albertel 4187: 
1.506     raeburn  4188: sub auto_new_course {
1.508     raeburn  4189:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4190:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4191:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4192:     return $response;
                   4193: }
1.776     albertel 4194: 
1.506     raeburn  4195: sub auto_validate_courseID {
1.508     raeburn  4196:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4197:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4198:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4199:     return $response;
                   4200: }
1.776     albertel 4201: 
1.506     raeburn  4202: sub auto_create_password {
1.508     raeburn  4203:     my ($cnum,$cdom,$authparam) = @_;
                   4204:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4205:     my $create_passwd = 0;
                   4206:     my $authchk = '';
1.511     raeburn  4207:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4208:     if ($response eq 'refused') {
                   4209:         $authchk = 'refused';
                   4210:     } else {
                   4211:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4212:     }
                   4213:     return ($authparam,$create_passwd,$authchk);
                   4214: }
                   4215: 
1.706     raeburn  4216: sub auto_photo_permission {
                   4217:     my ($cnum,$cdom,$students) = @_;
                   4218:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4219:     my ($outcome,$perm_reqd,$conditions) = 
                   4220: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4221:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4222: 	return (undef,undef);
                   4223:     }
1.706     raeburn  4224:     return ($outcome,$perm_reqd,$conditions);
                   4225: }
                   4226: 
                   4227: sub auto_checkphotos {
                   4228:     my ($uname,$udom,$pid) = @_;
                   4229:     my $homeserver = &homeserver($uname,$udom);
                   4230:     my ($result,$resulttype);
                   4231:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4232: 				   &escape($uname).':'.&escape($pid),
                   4233: 				   $homeserver));
1.709     albertel 4234:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4235: 	return (undef,undef);
                   4236:     }
1.706     raeburn  4237:     if ($outcome) {
                   4238:         ($result,$resulttype) = split(/:/,$outcome);
                   4239:     } 
                   4240:     return ($result,$resulttype);
                   4241: }
                   4242: 
                   4243: sub auto_photochoice {
                   4244:     my ($cnum,$cdom) = @_;
                   4245:     my $homeserver = &homeserver($cnum,$cdom);
                   4246:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4247: 						       &escape($cdom),
                   4248: 						       $homeserver)));
1.709     albertel 4249:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4250: 	return (undef,undef);
                   4251:     }
1.706     raeburn  4252:     return ($update,$comment);
                   4253: }
                   4254: 
                   4255: sub auto_photoupdate {
                   4256:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4257:     my $homeserver = &homeserver($cnum,$dom);
                   4258:     my $host=$hostname{$homeserver};
                   4259:     my $cmd = '';
                   4260:     my $maxtries = 1;
1.800     albertel 4261:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4262:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4263:     }
                   4264:     $cmd =~ s/%%$//;
                   4265:     $cmd = &escape($cmd);
                   4266:     my $query = 'institutionalphotos';
                   4267:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4268:     unless ($queryid=~/^\Q$host\E\_/) {
                   4269:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4270:         return 'error: '.$queryid;
                   4271:     }
                   4272:     my $reply = &get_query_reply($queryid);
                   4273:     my $tries = 1;
                   4274:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4275:         $reply = &get_query_reply($queryid);
                   4276:         $tries ++;
                   4277:     }
                   4278:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4279:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4280:     } else {
                   4281:         my @responses = split(/:/,$reply);
                   4282:         my $outcome = shift(@responses); 
                   4283:         foreach my $item (@responses) {
                   4284:             my ($key,$value) = split(/=/,$item);
                   4285:             $$photo{$key} = $value;
                   4286:         }
                   4287:         return $outcome;
                   4288:     }
                   4289:     return 'error';
                   4290: }
                   4291: 
1.521     raeburn  4292: sub auto_instcode_format {
1.793     albertel 4293:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4294: 	$cat_order) = @_;
1.521     raeburn  4295:     my $courses = '';
1.772     raeburn  4296:     my @homeservers;
1.521     raeburn  4297:     if ($caller eq 'global') {
1.793     albertel 4298:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4299:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4300:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4301:                     push(@homeservers,$tryserver);
                   4302:                 }
1.584     raeburn  4303:             }
                   4304:         }
1.521     raeburn  4305:     } else {
1.772     raeburn  4306:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4307:     }
1.793     albertel 4308:     foreach my $code (keys(%{$instcodes})) {
                   4309:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4310:     }
                   4311:     chop($courses);
1.772     raeburn  4312:     my $ok_response = 0;
                   4313:     my $response;
                   4314:     while (@homeservers > 0 && $ok_response == 0) {
                   4315:         my $server = shift(@homeservers); 
                   4316:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4317:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4318:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4319: 		split/:/,$response;
1.772     raeburn  4320:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4321:             push(@{$codetitles},&str2array($codetitles_str));
                   4322:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4323:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4324:             $ok_response = 1;
                   4325:         }
                   4326:     }
                   4327:     if ($ok_response) {
1.521     raeburn  4328:         return 'ok';
1.772     raeburn  4329:     } else {
                   4330:         return $response;
1.521     raeburn  4331:     }
                   4332: }
                   4333: 
1.792     raeburn  4334: sub auto_instcode_defaults {
                   4335:     my ($domain,$returnhash,$code_order) = @_;
                   4336:     my @homeservers;
1.793     albertel 4337:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4338:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4339:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4340:                 push(@homeservers,$tryserver);
                   4341:             }
                   4342:         }
                   4343:     }
                   4344:     my $ok_response = 0;
                   4345:     my $response;
                   4346:     while (@homeservers > 0 && $ok_response == 0) {
                   4347:         my $server = shift(@homeservers);
                   4348:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4349:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4350:             foreach my $pair (split(/\&/,$response)) {
                   4351:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4352:                 if ($name eq 'code_order') {
1.796     raeburn  4353:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4354:                 } else {
1.796     raeburn  4355:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4356:                 }
                   4357:             }
1.804     raeburn  4358:             $ok_response = 1;
1.792     raeburn  4359:         }
                   4360:     }
                   4361:     if ($ok_response) {
                   4362:         return 'ok';
                   4363:     } else {
                   4364:         return $response;
                   4365:     }
                   4366: } 
                   4367: 
1.777     albertel 4368: sub auto_validate_class_sec {
1.773     raeburn  4369:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4370:     my $homeserver = &homeserver($cnum,$cdom);
                   4371:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4372:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4373:     return $response;
                   4374: }
                   4375: 
1.679     raeburn  4376: # ------------------------------------------------------- Course Group routines
                   4377: 
                   4378: sub get_coursegroups {
1.809     raeburn  4379:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4380:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4381: }
                   4382: 
1.679     raeburn  4383: sub modify_coursegroup {
                   4384:     my ($cdom,$cnum,$groupsettings) = @_;
                   4385:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4386: }
                   4387: 
1.809     raeburn  4388: sub toggle_coursegroup_status {
                   4389:     my ($cdom,$cnum,$group,$action) = @_;
                   4390:     my ($from_namespace,$to_namespace);
                   4391:     if ($action eq 'delete') {
                   4392:         $from_namespace = 'coursegroups';
                   4393:         $to_namespace = 'deleted_groups';
                   4394:     } else {
                   4395:         $from_namespace = 'deleted_groups';
                   4396:         $to_namespace = 'coursegroups';
                   4397:     }
                   4398:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4399:     if (my $tmp = &error(%curr_group)) {
                   4400:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4401:         return ('read error',$tmp);
                   4402:     } else {
                   4403:         my %savedsettings = %curr_group; 
1.809     raeburn  4404:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4405:         my $deloutcome;
                   4406:         if ($result eq 'ok') {
1.809     raeburn  4407:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4408:         } else {
                   4409:             return ('write error',$result);
                   4410:         }
                   4411:         if ($deloutcome eq 'ok') {
                   4412:             return 'ok';
                   4413:         } else {
                   4414:             return ('delete error',$deloutcome);
                   4415:         }
                   4416:     }
                   4417: }
                   4418: 
1.679     raeburn  4419: sub modify_group_roles {
                   4420:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4421:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4422:     my $role = 'gr/'.&escape($userprivs);
                   4423:     my ($uname,$udom) = split(/:/,$user);
                   4424:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4425:     if ($result eq 'ok') {
                   4426:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4427:     }
1.679     raeburn  4428:     return $result;
                   4429: }
                   4430: 
                   4431: sub modify_coursegroup_membership {
                   4432:     my ($cdom,$cnum,$membership) = @_;
                   4433:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4434:     return $result;
                   4435: }
                   4436: 
1.682     raeburn  4437: sub get_active_groups {
                   4438:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4439:     my $now = time;
                   4440:     my %groups = ();
                   4441:     foreach my $key (keys(%env)) {
1.811     albertel 4442:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4443:             my ($start,$end) = split(/\./,$env{$key});
                   4444:             if (($end!=0) && ($end<$now)) { next; }
                   4445:             if (($start!=0) && ($start>$now)) { next; }
                   4446:             if ($1 eq $cdom && $2 eq $cnum) {
                   4447:                 $groups{$3} = $env{$key} ;
                   4448:             }
                   4449:         }
                   4450:     }
                   4451:     return %groups;
                   4452: }
                   4453: 
1.683     raeburn  4454: sub get_group_membership {
                   4455:     my ($cdom,$cnum,$group) = @_;
                   4456:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4457: }
                   4458: 
                   4459: sub get_users_groups {
                   4460:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4461:     my @usersgroups;
1.683     raeburn  4462:     my $cachetime=1800;
                   4463: 
                   4464:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4465:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4466:     if (defined($cached)) {
1.734     albertel 4467:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4468:     } else {  
                   4469:         $grouplist = '';
                   4470:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4471:         my ($tmp) = keys(%roleshash);
                   4472:         if ($tmp=~/^error:/) {
                   4473:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4474:         } else {
                   4475:             my $access_end = $env{'course.'.$courseid.
                   4476:                                   '.default_enrollment_end_date'};
                   4477:             my $now = time;
1.734     albertel 4478:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4479:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4480:                     my $group = $1;
                   4481:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4482:                         my $start = $2;
                   4483:                         my $end = $1;
                   4484:                         if ($start == -1) { next; } # deleted from group
                   4485:                         if (($start!=0) && ($start>$now)) { next; }
                   4486:                         if (($end!=0) && ($end<$now)) {
                   4487:                             if ($access_end && $access_end < $now) {
                   4488:                                 if ($access_end - $end < 86400) {
                   4489:                                     push(@usersgroups,$group);
                   4490:                                 }
                   4491:                             }
                   4492:                             next;
                   4493:                         }
                   4494:                         push(@usersgroups,$group);
                   4495:                     }
1.683     raeburn  4496:                 }
                   4497:             }
1.733     raeburn  4498:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4499:             $grouplist = join(':',@usersgroups);
                   4500:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4501:         }
                   4502:     }
1.733     raeburn  4503:     return @usersgroups;
1.683     raeburn  4504: }
                   4505: 
                   4506: sub devalidate_getgroups_cache {
                   4507:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4508:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4509: 
1.683     raeburn  4510:     my $hashid="$udom:$uname:$courseid";
                   4511:     &devalidate_cache_new('getgroups',$hashid);
                   4512: }
                   4513: 
1.12      www      4514: # ------------------------------------------------------------------ Plain Text
                   4515: 
                   4516: sub plaintext {
1.742     raeburn  4517:     my ($short,$type,$cid) = @_;
1.758     albertel 4518:     if ($short =~ /^cr/) {
                   4519: 	return (split('/',$short))[-1];
                   4520:     }
1.742     raeburn  4521:     if (!defined($cid)) {
                   4522:         $cid = $env{'request.course.id'};
                   4523:     }
                   4524:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4525:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4526:                                           '.plaintext'});
                   4527:     }
                   4528:     my %rolenames = (
                   4529:                       Course => 'std',
                   4530:                       Group => 'alt1',
                   4531:                     );
                   4532:     if (defined($type) && 
                   4533:          defined($rolenames{$type}) && 
                   4534:          defined($prp{$short}{$rolenames{$type}})) {
                   4535:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4536:     } else {
                   4537:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4538:     }
1.12      www      4539: }
                   4540: 
                   4541: # ----------------------------------------------------------------- Assign Role
                   4542: 
                   4543: sub assignrole {
1.357     www      4544:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4545:     my $mrole;
                   4546:     if ($role =~ /^cr\//) {
1.393     www      4547:         my $cwosec=$url;
1.811     albertel 4548:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4549: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4550:            &logthis('Refused custom assignrole: '.
                   4551:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4552: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4553:            return 'refused'; 
                   4554:         }
1.21      www      4555:         $mrole='cr';
1.678     raeburn  4556:     } elsif ($role =~ /^gr\//) {
                   4557:         my $cwogrp=$url;
1.811     albertel 4558:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4559:         unless (&allowed('mdg',$cwogrp)) {
                   4560:             &logthis('Refused group assignrole: '.
                   4561:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4562:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4563:             return 'refused';
                   4564:         }
                   4565:         $mrole='gr';
1.21      www      4566:     } else {
1.82      www      4567:         my $cwosec=$url;
1.811     albertel 4568:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4569:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4570:            &logthis('Refused assignrole: '.
                   4571:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4572: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4573:            return 'refused'; 
                   4574:         }
1.21      www      4575:         $mrole=$role;
                   4576:     }
1.620     albertel 4577:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4578:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4579:     if ($end) { $command.='_'.$end; }
1.21      www      4580:     if ($start) {
                   4581: 	if ($end) { 
1.81      www      4582:            $command.='_'.$start; 
1.21      www      4583:         } else {
1.81      www      4584:            $command.='_0_'.$start;
1.21      www      4585:         }
                   4586:     }
1.739     raeburn  4587:     my $origstart = $start;
                   4588:     my $origend = $end;
1.357     www      4589: # actually delete
                   4590:     if ($deleteflag) {
1.373     www      4591: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4592: # modify command to delete the role
1.620     albertel 4593:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4594:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4595: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4596: # set start and finish to negative values for userrolelog
                   4597:            $start=-1;
                   4598:            $end=-1;
                   4599:         }
                   4600:     }
                   4601: # send command
1.349     www      4602:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4603: # log new user role if status is ok
1.349     www      4604:     if ($answer eq 'ok') {
1.663     raeburn  4605: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4606: # for course roles, perform group memberships changes triggered by role change.
                   4607:         unless ($role =~ /^gr/) {
                   4608:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4609:                                              $origstart);
                   4610:         }
1.349     www      4611:     }
                   4612:     return $answer;
1.169     harris41 4613: }
                   4614: 
                   4615: # -------------------------------------------------- Modify user authentication
1.197     www      4616: # Overrides without validation
                   4617: 
1.169     harris41 4618: sub modifyuserauth {
                   4619:     my ($udom,$uname,$umode,$upass)=@_;
                   4620:     my $uhome=&homeserver($uname,$udom);
1.197     www      4621:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4622:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4623:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4624:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4625:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4626: 		     &escape($upass),$uhome);
1.620     albertel 4627:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4628:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4629:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4630:     &log($udom,,$uname,$uhome,
1.620     albertel 4631:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4632:                                      $env{'user.name'}.', '.$umode.
1.197     www      4633:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4634:     unless ($reply eq 'ok') {
1.197     www      4635:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4636: 	return 'error: '.$reply;
                   4637:     }   
1.170     harris41 4638:     return 'ok';
1.80      www      4639: }
                   4640: 
1.81      www      4641: # --------------------------------------------------------------- Modify a user
1.80      www      4642: 
1.81      www      4643: sub modifyuser {
1.206     matthew  4644:     my ($udom,    $uname, $uid,
                   4645:         $umode,   $upass, $first,
                   4646:         $middle,  $last,  $gene,
1.387     www      4647:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4648:     $udom= &LONCAPA::clean_domain($udom);
                   4649:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4650:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4651:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4652: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4653:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4654:                                      ' desiredhome not specified'). 
1.620     albertel 4655:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4656:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4657:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4658: # ----------------------------------------------------------------- Create User
1.406     albertel 4659:     if (($uhome eq 'no_host') && 
                   4660: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4661:         my $unhome='';
1.209     matthew  4662:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4663:             $unhome = $desiredhome;
1.620     albertel 4664: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4665: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4666:         } else { # load balancing routine for determining $unhome
1.80      www      4667:             my $tryserver;
1.81      www      4668:             my $loadm=10000000;
1.80      www      4669:             foreach $tryserver (keys %libserv) {
                   4670: 	       if ($hostdom{$tryserver} eq $udom) {
                   4671:                   my $answer=reply('load',$tryserver);
                   4672:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4673: 		      $loadm=$answer;
                   4674:                       $unhome=$tryserver;
                   4675:                   }
                   4676: 	       }
                   4677: 	    }
                   4678:         }
                   4679:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4680: 	    return 'error: unable to find a home server for '.$uname.
                   4681:                    ' in domain '.$udom;
1.80      www      4682:         }
                   4683:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4684:                          &escape($upass),$unhome);
                   4685: 	unless ($reply eq 'ok') {
                   4686:             return 'error: '.$reply;
                   4687:         }   
1.230     stredwic 4688:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4689:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4690: 	    return 'error: unable verify users home machine.';
1.80      www      4691:         }
1.209     matthew  4692:     }   # End of creation of new user
1.80      www      4693: # ---------------------------------------------------------------------- Add ID
                   4694:     if ($uid) {
                   4695:        $uid=~tr/A-Z/a-z/;
                   4696:        my %uidhash=&idrget($udom,$uname);
1.196     www      4697:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4698:          && (!$forceid)) {
1.80      www      4699: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4700: 	      return 'error: user id "'.$uid.'" does not match '.
                   4701:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4702:           }
                   4703:        } else {
                   4704: 	  &idput($udom,($uname => $uid));
                   4705:        }
                   4706:     }
                   4707: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4708:     my @tmp=&get('environment',
1.134     albertel 4709: 		   ['firstname','middlename','lastname','generation'],
                   4710: 		   $udom,$uname);
1.313     matthew  4711:     my %names;
                   4712:     if ($tmp[0] =~ m/^error:.*/) { 
                   4713:         %names=(); 
                   4714:     } else {
                   4715:         %names = @tmp;
                   4716:     }
1.388     www      4717: #
                   4718: # Make sure to not trash student environment if instructor does not bother
                   4719: # to supply name and email information
                   4720: #
                   4721:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4722:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4723:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4724:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4725:     if ($email) {
                   4726:        $email=~s/[^\w\@\.\-\,]//gs;
                   4727:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4728: 			   $names{'critnotification'} = $email;
                   4729: 			   $names{'permanentemail'} = $email; }
                   4730:     }
1.134     albertel 4731:     my $reply = &put('environment', \%names, $udom,$uname);
                   4732:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4733:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4734:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4735:              $umode.', '.$first.', '.$middle.', '.
                   4736: 	     $last.', '.$gene.' by '.
1.620     albertel 4737:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4738:     return 'ok';
1.80      www      4739: }
                   4740: 
1.81      www      4741: # -------------------------------------------------------------- Modify student
1.80      www      4742: 
1.81      www      4743: sub modifystudent {
                   4744:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4745:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4746:     if (!$cid) {
1.620     albertel 4747: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4748: 	    return 'not_in_class';
                   4749: 	}
1.80      www      4750:     }
                   4751: # --------------------------------------------------------------- Make the user
1.81      www      4752:     my $reply=&modifyuser
1.209     matthew  4753: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4754:          $desiredhome,$email);
1.80      www      4755:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4756:     # This will cause &modify_student_enrollment to get the uid from the
                   4757:     # students environment
                   4758:     $uid = undef if (!$forceid);
1.455     albertel 4759:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4760: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4761:     return $reply;
                   4762: }
                   4763: 
                   4764: sub modify_student_enrollment {
1.515     raeburn  4765:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4766:     my ($cdom,$cnum,$chome);
                   4767:     if (!$cid) {
1.620     albertel 4768: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4769: 	    return 'not_in_class';
                   4770: 	}
1.620     albertel 4771: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4772: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4773:     } else {
                   4774: 	($cdom,$cnum)=split(/_/,$cid);
                   4775:     }
1.620     albertel 4776:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4777:     if (!$chome) {
1.457     raeburn  4778: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4779:     }
1.455     albertel 4780:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4781:     # Make sure the user exists
1.81      www      4782:     my $uhome=&homeserver($uname,$udom);
                   4783:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4784: 	return 'error: no such user';
                   4785:     }
1.297     matthew  4786:     # Get student data if we were not given enough information
                   4787:     if (!defined($first)  || $first  eq '' || 
                   4788:         !defined($last)   || $last   eq '' || 
                   4789:         !defined($uid)    || $uid    eq '' || 
                   4790:         !defined($middle) || $middle eq '' || 
                   4791:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4792:         # They did not supply us with enough data to enroll the student, so
                   4793:         # we need to pick up more information.
1.297     matthew  4794:         my %tmp = &get('environment',
1.294     matthew  4795:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4796:                        ,$udom,$uname);
                   4797: 
1.800     albertel 4798:         #foreach my $key (keys(%tmp)) {
                   4799:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4800:         #}
1.294     matthew  4801:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4802:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4803:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4804:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4805:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4806:     }
1.556     albertel 4807:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4808:     my $reply=cput('classlist',
                   4809: 		   {"$uname:$udom" => 
1.515     raeburn  4810: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4811: 		   $cdom,$cnum);
1.81      www      4812:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4813: 	return 'error: '.$reply;
1.652     albertel 4814:     } else {
                   4815: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4816:     }
1.297     matthew  4817:     # Add student role to user
1.83      www      4818:     my $uurl='/'.$cid;
1.81      www      4819:     $uurl=~s/\_/\//g;
                   4820:     if ($usec) {
                   4821: 	$uurl.='/'.$usec;
                   4822:     }
                   4823:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4824: }
                   4825: 
1.556     albertel 4826: sub format_name {
                   4827:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4828:     my $name;
                   4829:     if ($first ne 'lastname') {
                   4830: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4831:     } else {
                   4832: 	if ($lastname=~/\S/) {
                   4833: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4834: 	    $name=~s/\s+,/,/;
                   4835: 	} else {
                   4836: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4837: 	}
                   4838:     }
                   4839:     $name=~s/^\s+//;
                   4840:     $name=~s/\s+$//;
                   4841:     $name=~s/\s+/ /g;
                   4842:     return $name;
                   4843: }
                   4844: 
1.84      www      4845: # ------------------------------------------------- Write to course preferences
                   4846: 
                   4847: sub writecoursepref {
                   4848:     my ($courseid,%prefs)=@_;
                   4849:     $courseid=~s/^\///;
                   4850:     $courseid=~s/\_/\//g;
                   4851:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4852:     my $chome=homeserver($cnum,$cdomain);
                   4853:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4854: 	return 'error: no such course';
                   4855:     }
                   4856:     my $cstring='';
1.800     albertel 4857:     foreach my $pref (keys(%prefs)) {
                   4858: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4859:     }
1.84      www      4860:     $cstring=~s/\&$//;
                   4861:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4862: }
                   4863: 
                   4864: # ---------------------------------------------------------- Make/modify course
                   4865: 
                   4866: sub createcourse {
1.741     raeburn  4867:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4868:         $course_owner,$crstype)=@_;
1.84      www      4869:     $url=&declutter($url);
                   4870:     my $cid='';
1.264     matthew  4871:     unless (&allowed('ccc',$udom)) {
1.84      www      4872:         return 'refused';
                   4873:     }
                   4874: # ------------------------------------------------------------------- Create ID
1.674     www      4875:    my $uname=int(1+rand(9)).
                   4876:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4877:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4878:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4879: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4880:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4881:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4882:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4883:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4884:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4885:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4886:            return 'error: unable to generate unique course-ID';
                   4887:        } 
                   4888:    }
1.264     matthew  4889: # ------------------------------------------------ Check supplied server name
1.620     albertel 4890:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4891:     if (! exists($libserv{$course_server})) {
                   4892:         return 'error:bad server name '.$course_server;
                   4893:     }
1.84      www      4894: # ------------------------------------------------------------- Make the course
                   4895:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4896:                       $course_server);
1.84      www      4897:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4898:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4899:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4900: 	return 'error: no such course';
                   4901:     }
1.271     www      4902: # ----------------------------------------------------------------- Course made
1.516     raeburn  4903: # log existence
                   4904:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4905:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4906:                   &escape($crstype),$uhome);
1.358     www      4907:     &flushcourselogs();
                   4908: # set toplevel url
1.271     www      4909:     my $topurl=$url;
                   4910:     unless ($nonstandard) {
                   4911: # ------------------------------------------ For standard courses, make top url
                   4912:         my $mapurl=&clutter($url);
1.278     www      4913:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4914:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4915: <map>
                   4916: <resource id="1" type="start"></resource>
                   4917: <resource id="2" src="$mapurl"></resource>
                   4918: <resource id="3" type="finish"></resource>
                   4919: <link index="1" from="1" to="2"></link>
                   4920: <link index="2" from="2" to="3"></link>
                   4921: </map>
                   4922: ENDINITMAP
                   4923:         $topurl=&declutter(
1.638     albertel 4924:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4925:                           );
                   4926:     }
                   4927: # ----------------------------------------------------------- Write preferences
1.84      www      4928:     &writecoursepref($udom.'_'.$uname,
                   4929:                      ('description' => $description,
1.271     www      4930:                       'url'         => $topurl));
1.84      www      4931:     return '/'.$udom.'/'.$uname;
                   4932: }
                   4933: 
1.813   ! albertel 4934: sub is_course {
        !          4935:     my ($cdom,$cnum) = @_;
        !          4936:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
        !          4937: 				undef,'.');
        !          4938:     if (exists($courses{$cdom.'_'.$cnum})) {
        !          4939:         return 1;
        !          4940:     }
        !          4941:     return 0;
        !          4942: }
        !          4943: 
1.21      www      4944: # ---------------------------------------------------------- Assign Custom Role
                   4945: 
                   4946: sub assigncustomrole {
1.357     www      4947:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4948:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4949:                        $end,$start,$deleteflag);
1.21      www      4950: }
                   4951: 
                   4952: # ----------------------------------------------------------------- Revoke Role
                   4953: 
                   4954: sub revokerole {
1.357     www      4955:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4956:     my $now=time;
1.357     www      4957:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4958: }
                   4959: 
                   4960: # ---------------------------------------------------------- Revoke Custom Role
                   4961: 
                   4962: sub revokecustomrole {
1.357     www      4963:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4964:     my $now=time;
1.357     www      4965:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4966:            $deleteflag);
1.17      www      4967: }
                   4968: 
1.533     banghart 4969: # ------------------------------------------------------------ Disk usage
1.535     albertel 4970: sub diskusage {
1.533     banghart 4971:     my ($udom,$uname,$directoryRoot)=@_;
                   4972:     $directoryRoot =~ s/\/$//;
1.535     albertel 4973:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4974:     return $listing;
1.512     banghart 4975: }
                   4976: 
1.566     banghart 4977: sub is_locked {
                   4978:     my ($file_name, $domain, $user) = @_;
                   4979:     my @check;
                   4980:     my $is_locked;
                   4981:     push @check, $file_name;
1.613     albertel 4982:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4983: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4984:     my ($tmp)=keys(%locked);
                   4985:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4986:     
1.566     banghart 4987:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4988:         $is_locked = 'false';
                   4989:         foreach my $entry (@{$locked{$file_name}}) {
                   4990:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4991:                $is_locked = 'true';
                   4992:                last;
1.745     raeburn  4993:            }
                   4994:        }
1.566     banghart 4995:     } else {
                   4996:         $is_locked = 'false';
                   4997:     }
                   4998: }
                   4999: 
1.759     albertel 5000: sub declutter_portfile {
                   5001:     my ($file) = @_;
                   5002:     &logthis("got $file");
                   5003:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5004:     &logthis("ret $file");
                   5005:     return $file;
                   5006: }
                   5007: 
1.559     banghart 5008: # ------------------------------------------------------------- Mark as Read Only
                   5009: 
                   5010: sub mark_as_readonly {
                   5011:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5012:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5013:     my ($tmp)=keys(%current_permissions);
                   5014:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5015:     foreach my $file (@{$files}) {
1.759     albertel 5016: 	$file = &declutter_portfile($file);
1.561     banghart 5017:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5018:     }
1.613     albertel 5019:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5020:     return;
                   5021: }
                   5022: 
1.572     banghart 5023: # ------------------------------------------------------------Save Selected Files
                   5024: 
                   5025: sub save_selected_files {
                   5026:     my ($user, $path, @files) = @_;
                   5027:     my $filename = $user."savedfiles";
1.573     banghart 5028:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5029:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5030:     foreach my $file (@files) {
1.620     albertel 5031:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5032:     }
                   5033:     foreach my $file (@other_files) {
1.574     banghart 5034:         print (OUT $file."\n");
1.572     banghart 5035:     }
1.574     banghart 5036:     close (OUT);
1.572     banghart 5037:     return 'ok';
                   5038: }
                   5039: 
1.574     banghart 5040: sub clear_selected_files {
                   5041:     my ($user) = @_;
                   5042:     my $filename = $user."savedfiles";
                   5043:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5044:     print (OUT undef);
                   5045:     close (OUT);
                   5046:     return ("ok");    
                   5047: }
                   5048: 
1.572     banghart 5049: sub files_in_path {
                   5050:     my ($user, $path) = @_;
                   5051:     my $filename = $user."savedfiles";
                   5052:     my %return_files;
1.574     banghart 5053:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5054:     while (my $line_in = <IN>) {
1.574     banghart 5055:         chomp ($line_in);
                   5056:         my @paths_and_file = split (m!/!, $line_in);
                   5057:         my $file_part = pop (@paths_and_file);
                   5058:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5059:         $path_part.='/';
                   5060:         my $path_and_file = $path_part.$file_part;
                   5061:         if ($path_part eq $path) {
                   5062:             $return_files{$file_part}= 'selected';
                   5063:         }
                   5064:     }
1.574     banghart 5065:     close (IN);
                   5066:     return (\%return_files);
1.572     banghart 5067: }
                   5068: 
                   5069: # called in portfolio select mode, to show files selected NOT in current directory
                   5070: sub files_not_in_path {
                   5071:     my ($user, $path) = @_;
                   5072:     my $filename = $user."savedfiles";
                   5073:     my @return_files;
                   5074:     my $path_part;
1.800     albertel 5075:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5076:     while (my $line = <IN>) {
1.572     banghart 5077:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5078:         my @paths_and_file = split(m|/|, $line);
                   5079:         my $file_part = pop(@paths_and_file);
                   5080:         chomp($file_part);
                   5081:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5082:         $path_part .= '/';
                   5083:         my $path_and_file = $path_part.$file_part;
                   5084:         if ($path_part ne $path) {
1.800     albertel 5085:             push(@return_files, ($path_and_file));
1.572     banghart 5086:         }
                   5087:     }
1.800     albertel 5088:     close(OUT);
1.574     banghart 5089:     return (@return_files);
1.572     banghart 5090: }
                   5091: 
1.745     raeburn  5092: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5093: 
1.745     raeburn  5094: sub get_portfile_permissions {
                   5095:     my ($domain,$user) = @_;
1.613     albertel 5096:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5097:     my ($tmp)=keys(%current_permissions);
                   5098:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5099:     return \%current_permissions;
                   5100: }
                   5101: 
                   5102: #---------------------------------------------Get portfolio file access controls
                   5103: 
1.749     raeburn  5104: sub get_access_controls {
1.745     raeburn  5105:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5106:     my %access;
                   5107:     my $real_file = $file;
                   5108:     $file =~ s/\.meta$//;
1.745     raeburn  5109:     if (defined($file)) {
1.749     raeburn  5110:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5111:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5112:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5113:             }
                   5114:         }
1.745     raeburn  5115:     } else {
1.749     raeburn  5116:         foreach my $key (keys(%{$current_permissions})) {
                   5117:             if ($key =~ /\0accesscontrol$/) {
                   5118:                 if (defined($group)) {
                   5119:                     if ($key !~ m-^\Q$group\E/-) {
                   5120:                         next;
                   5121:                     }
                   5122:                 }
                   5123:                 my ($fullpath) = split(/\0/,$key);
                   5124:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5125:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5126:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5127:                     }
                   5128:                 }
                   5129:             }
                   5130:         }
                   5131:     }
                   5132:     return %access;
                   5133: }
                   5134: 
                   5135: sub modify_access_controls {
                   5136:     my ($file_name,$changes,$domain,$user)=@_;
                   5137:     my ($outcome,$deloutcome);
                   5138:     my %store_permissions;
                   5139:     my %new_values;
                   5140:     my %new_control;
                   5141:     my %translation;
                   5142:     my @deletions = ();
                   5143:     my $now = time;
                   5144:     if (exists($$changes{'activate'})) {
                   5145:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5146:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5147:             my $numnew = scalar(@newitems);
                   5148:             for (my $i=0; $i<$numnew; $i++) {
                   5149:                 my $newkey = $newitems[$i];
                   5150:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5151:                 if ($newkey =~ /^\d+:/) { 
                   5152:                     $newkey =~ s/^(\d+)/$newid/;
                   5153:                     $translation{$1} = $newid;
                   5154:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5155:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5156:                     $translation{$1} = $newid;
                   5157:                 }
1.749     raeburn  5158:                 $new_values{$file_name."\0".$newkey} = 
                   5159:                                           $$changes{'activate'}{$newitems[$i]};
                   5160:                 $new_control{$newkey} = $now;
                   5161:             }
                   5162:         }
                   5163:     }
                   5164:     my %todelete;
                   5165:     my %changed_items;
                   5166:     foreach my $action ('delete','update') {
                   5167:         if (exists($$changes{$action})) {
                   5168:             if (ref($$changes{$action}) eq 'HASH') {
                   5169:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5170:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5171:                     if ($action eq 'delete') { 
                   5172:                         $todelete{$itemnum} = 1;
                   5173:                     } else {
                   5174:                         $changed_items{$itemnum} = $key;
                   5175:                     }
                   5176:                 }
1.745     raeburn  5177:             }
                   5178:         }
1.749     raeburn  5179:     }
                   5180:     # get lock on access controls for file.
                   5181:     my $lockhash = {
                   5182:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5183:                                                        ':'.$env{'user.domain'},
                   5184:                    }; 
                   5185:     my $tries = 0;
                   5186:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5187:    
                   5188:     while (($gotlock ne 'ok') && $tries <3) {
                   5189:         $tries ++;
                   5190:         sleep 1;
                   5191:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5192:     }
                   5193:     if ($gotlock eq 'ok') {
                   5194:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5195:         my ($tmp)=keys(%curr_permissions);
                   5196:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5197:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5198:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5199:             if (ref($curr_controls) eq 'HASH') {
                   5200:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5201:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5202:                     if (defined($todelete{$itemnum})) {
                   5203:                         push(@deletions,$file_name."\0".$control_item);
                   5204:                     } else {
                   5205:                         if (defined($changed_items{$itemnum})) {
                   5206:                             $new_control{$changed_items{$itemnum}} = $now;
                   5207:                             push(@deletions,$file_name."\0".$control_item);
                   5208:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5209:                         } else {
                   5210:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5211:                         }
                   5212:                     }
1.745     raeburn  5213:                 }
                   5214:             }
                   5215:         }
1.749     raeburn  5216:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5217:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5218:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5219:         #  remove lock
                   5220:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5221:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5222:     } else {
                   5223:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5224:     }
1.749     raeburn  5225:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5226: }
                   5227: 
                   5228: #------------------------------------------------------Get Marked as Read Only
                   5229: 
                   5230: sub get_marked_as_readonly {
                   5231:     my ($domain,$user,$what,$group) = @_;
                   5232:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5233:     my @readonly_files;
1.629     banghart 5234:     my $cmp1=$what;
                   5235:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5236:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5237:         if (defined($group)) {
                   5238:             if ($file_name !~ m-^\Q$group\E/-) {
                   5239:                 next;
                   5240:             }
                   5241:         }
1.561     banghart 5242:         if (ref($value) eq "ARRAY"){
                   5243:             foreach my $stored_what (@{$value}) {
1.629     banghart 5244:                 my $cmp2=$stored_what;
1.759     albertel 5245:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5246:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5247:                 }
1.629     banghart 5248:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5249:                     push(@readonly_files, $file_name);
1.745     raeburn  5250:                     last;
1.563     banghart 5251:                 } elsif (!defined($what)) {
                   5252:                     push(@readonly_files, $file_name);
1.745     raeburn  5253:                     last;
1.561     banghart 5254:                 }
                   5255:             }
1.745     raeburn  5256:         }
1.561     banghart 5257:     }
                   5258:     return @readonly_files;
                   5259: }
1.577     banghart 5260: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5261: 
1.577     banghart 5262: sub get_marked_as_readonly_hash {
1.745     raeburn  5263:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5264:     my %readonly_files;
1.745     raeburn  5265:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5266:         if (defined($group)) {
                   5267:             if ($file_name !~ m-^\Q$group\E/-) {
                   5268:                 next;
                   5269:             }
                   5270:         }
1.577     banghart 5271:         if (ref($value) eq "ARRAY"){
                   5272:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5273:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5274:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5275:                         if ($lock_descriptor eq 'graded') {
                   5276:                             $readonly_files{$file_name} = 'graded';
                   5277:                         } elsif ($lock_descriptor eq 'handback') {
                   5278:                             $readonly_files{$file_name} = 'handback';
                   5279:                         } else {
                   5280:                             if (!exists($readonly_files{$file_name})) {
                   5281:                                 $readonly_files{$file_name} = 'locked';
                   5282:                             }
                   5283:                         }
1.745     raeburn  5284:                     }
1.750     banghart 5285:                 } 
1.577     banghart 5286:             }
                   5287:         } 
                   5288:     }
                   5289:     return %readonly_files;
                   5290: }
1.559     banghart 5291: # ------------------------------------------------------------ Unmark as Read Only
                   5292: 
                   5293: sub unmark_as_readonly {
1.629     banghart 5294:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5295:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5296:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5297:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5298:     my $symb_crs = $what;
                   5299:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5300:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5301:     my ($tmp)=keys(%current_permissions);
                   5302:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5303:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5304:     foreach my $file (@readonly_files) {
1.759     albertel 5305: 	my $clean_file = &declutter_portfile($file);
                   5306: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5307: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5308:         my @new_locks;
                   5309:         my @del_keys;
                   5310:         if (ref($current_locks) eq "ARRAY"){
                   5311:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5312:                 my $compare=$locker;
1.749     raeburn  5313:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5314:                     $compare=join('',@{$locker});
1.746     raeburn  5315:                     if ($compare ne $symb_crs) {
                   5316:                         push(@new_locks, $locker);
                   5317:                     }
1.563     banghart 5318:                 }
                   5319:             }
1.650     albertel 5320:             if (scalar(@new_locks) > 0) {
1.563     banghart 5321:                 $current_permissions{$file} = \@new_locks;
                   5322:             } else {
                   5323:                 push(@del_keys, $file);
1.613     albertel 5324:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5325:                 delete($current_permissions{$file});
1.563     banghart 5326:             }
                   5327:         }
1.561     banghart 5328:     }
1.613     albertel 5329:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5330:     return;
                   5331: }
1.512     banghart 5332: 
1.17      www      5333: # ------------------------------------------------------------ Directory lister
                   5334: 
                   5335: sub dirlist {
1.253     stredwic 5336:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5337: 
1.18      www      5338:     $uri=~s/^\///;
                   5339:     $uri=~s/\/$//;
1.253     stredwic 5340:     my ($udom, $uname);
                   5341:     (undef,$udom,$uname)=split(/\//,$uri);
                   5342:     if(defined($userdomain)) {
                   5343:         $udom = $userdomain;
                   5344:     }
                   5345:     if(defined($username)) {
                   5346:         $uname = $username;
                   5347:     }
                   5348: 
                   5349:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5350:     if(defined($alternateDirectoryRoot)) {
                   5351:         $dirRoot = $alternateDirectoryRoot;
                   5352:         $dirRoot =~ s/\/$//;
1.751     banghart 5353:     }
1.253     stredwic 5354: 
                   5355:     if($udom) {
                   5356:         if($uname) {
1.800     albertel 5357:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5358: 				 &homeserver($uname,$udom));
1.605     matthew  5359:             my @listing_results;
                   5360:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5361:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5362: 				  &homeserver($uname,$udom));
1.605     matthew  5363:                 @listing_results = split(/:/,$listing);
                   5364:             } else {
                   5365:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5366:             }
                   5367:             return @listing_results;
1.253     stredwic 5368:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5369:             my %allusers;
                   5370:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5371:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5372:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5373: 					 $udom, $tryserver);
1.605     matthew  5374:                     my @listing_results;
                   5375:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5376:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5377: 					  $udom, $tryserver);
1.605     matthew  5378:                         @listing_results = split(/:/,$listing);
                   5379:                     } else {
                   5380:                         @listing_results =
                   5381:                             map { &unescape($_); } split(/:/,$listing);
                   5382:                     }
                   5383:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5384:                         $listing_results[0] ne 'empty'       &&
                   5385:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5386:                         foreach my $line (@listing_results) {
                   5387:                             my ($entry) = split(/&/,$line,2);
                   5388:                             $allusers{$entry} = 1;
1.253     stredwic 5389:                         }
                   5390:                     }
1.191     harris41 5391:                 }
1.253     stredwic 5392:             }
                   5393:             my $alluserstr='';
1.800     albertel 5394:             foreach my $user (sort(keys(%allusers))) {
                   5395:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5396:             }
                   5397:             $alluserstr=~s/:$//;
                   5398:             return split(/:/,$alluserstr);
                   5399:         } else {
1.800     albertel 5400:             return ('missing user name');
1.253     stredwic 5401:         }
                   5402:     } elsif(!defined($alternateDirectoryRoot)) {
                   5403:         my $tryserver;
                   5404:         my %alldom=();
1.800     albertel 5405:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5406:             $alldom{$hostdom{$tryserver}}=1;
                   5407:         }
                   5408:         my $alldomstr='';
1.800     albertel 5409:         foreach my $domain (sort(keys(%alldom))) {
                   5410:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5411:         }
                   5412:         $alldomstr=~s/:$//;
                   5413:         return split(/:/,$alldomstr);       
                   5414:     } else {
1.800     albertel 5415:         return ('missing domain');
1.275     stredwic 5416:     }
                   5417: }
                   5418: 
                   5419: # --------------------------------------------- GetFileTimestamp
                   5420: # This function utilizes dirlist and returns the date stamp for
                   5421: # when it was last modified.  It will also return an error of -1
                   5422: # if an error occurs
                   5423: 
1.410     matthew  5424: ##
                   5425: ## FIXME: This subroutine assumes its caller knows something about the
                   5426: ## directory structure of the home server for the student ($root).
                   5427: ## Not a good assumption to make.  Since this is for looking up files
                   5428: ## in user directories, the full path should be constructed by lond, not
                   5429: ## whatever machine we request data from.
                   5430: ##
1.275     stredwic 5431: sub GetFileTimestamp {
                   5432:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5433:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5434:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5435:     my $subdir=$studentName.'__';
                   5436:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5437:     my $proname="$studentDomain/$subdir/$studentName";
                   5438:     $proname .= '/'.$filename;
1.375     matthew  5439:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5440:                                               $studentName, $root);
1.275     stredwic 5441:     my @stats = split('&', $fileStat);
                   5442:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5443:         # @stats contains first the filename, then the stat output
                   5444:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5445:     } else {
                   5446:         return -1;
1.253     stredwic 5447:     }
1.26      www      5448: }
                   5449: 
1.712     albertel 5450: sub stat_file {
                   5451:     my ($uri) = @_;
1.787     albertel 5452:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5453: 
1.712     albertel 5454:     my ($udom,$uname,$file,$dir);
                   5455:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5456: 	($udom,$uname,$file) =
1.811     albertel 5457: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5458: 	$file = 'userfiles/'.$file;
1.740     www      5459: 	$dir = &propath($udom,$uname);
1.712     albertel 5460:     }
                   5461:     if ($uri =~ m-^/res/-) {
                   5462: 	($udom,$uname) = 
1.807     albertel 5463: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5464: 	$file = $uri;
                   5465:     }
                   5466: 
                   5467:     if (!$udom || !$uname || !$file) {
                   5468: 	# unable to handle the uri
                   5469: 	return ();
                   5470:     }
                   5471: 
                   5472:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5473:     my @stats = split('&', $result);
1.721     banghart 5474:     
1.712     albertel 5475:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5476: 	shift(@stats); #filename is first
                   5477: 	return @stats;
                   5478:     }
                   5479:     return ();
                   5480: }
                   5481: 
1.26      www      5482: # -------------------------------------------------------- Value of a Condition
                   5483: 
1.713     albertel 5484: # gets the value of a specific preevaluated condition
                   5485: #    stored in the string  $env{user.state.<cid>}
                   5486: # or looks up a condition reference in the bighash and if if hasn't
                   5487: # already been evaluated recurses into docondval to get the value of
                   5488: # the condition, then memoizing it to 
                   5489: #   $env{user.state.<cid>.<condition>}
1.40      www      5490: sub directcondval {
                   5491:     my $number=shift;
1.620     albertel 5492:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5493: 	&Apache::lonuserstate::evalstate();
                   5494:     }
1.713     albertel 5495:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5496: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5497:     } elsif ($number =~ /^_/) {
                   5498: 	my $sub_condition;
                   5499: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5500: 		&GDBM_READER(),0640)) {
                   5501: 	    $sub_condition=$bighash{'conditions'.$number};
                   5502: 	    untie(%bighash);
                   5503: 	}
                   5504: 	my $value = &docondval($sub_condition);
                   5505: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5506: 	return $value;
                   5507:     }
1.620     albertel 5508:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5509:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5510:     } else {
                   5511:        return 2;
                   5512:     }
                   5513: }
                   5514: 
1.713     albertel 5515: # get the collection of conditions for this resource
1.26      www      5516: sub condval {
                   5517:     my $condidx=shift;
1.54      www      5518:     my $allpathcond='';
1.713     albertel 5519:     foreach my $cond (split(/\|/,$condidx)) {
                   5520: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5521: 	    $allpathcond.=
                   5522: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5523: 	}
1.191     harris41 5524:     }
1.54      www      5525:     $allpathcond=~s/\|$//;
1.713     albertel 5526:     return &docondval($allpathcond);
                   5527: }
                   5528: 
                   5529: #evaluates an expression of conditions
                   5530: sub docondval {
                   5531:     my ($allpathcond) = @_;
                   5532:     my $result=0;
                   5533:     if ($env{'request.course.id'}
                   5534: 	&& defined($allpathcond)) {
                   5535: 	my $operand='|';
                   5536: 	my @stack;
                   5537: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5538: 	    if ($chunk eq '(') {
                   5539: 		push @stack,($operand,$result);
                   5540: 	    } elsif ($chunk eq ')') {
                   5541: 		my $before=pop @stack;
                   5542: 		if (pop @stack eq '&') {
                   5543: 		    $result=$result>$before?$before:$result;
                   5544: 		} else {
                   5545: 		    $result=$result>$before?$result:$before;
                   5546: 		}
                   5547: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5548: 		$operand=$chunk;
                   5549: 	    } else {
                   5550: 		my $new=directcondval($chunk);
                   5551: 		if ($operand eq '&') {
                   5552: 		    $result=$result>$new?$new:$result;
                   5553: 		} else {
                   5554: 		    $result=$result>$new?$result:$new;
                   5555: 		}
                   5556: 	    }
                   5557: 	}
1.26      www      5558:     }
                   5559:     return $result;
1.421     albertel 5560: }
                   5561: 
                   5562: # ---------------------------------------------------- Devalidate courseresdata
                   5563: 
                   5564: sub devalidatecourseresdata {
                   5565:     my ($coursenum,$coursedomain)=@_;
                   5566:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5567:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5568: }
                   5569: 
1.763     www      5570: 
1.200     www      5571: # --------------------------------------------------- Course Resourcedata Query
                   5572: 
1.624     albertel 5573: sub get_courseresdata {
                   5574:     my ($coursenum,$coursedomain)=@_;
1.200     www      5575:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5576:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5577:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5578:     my %dumpreply;
1.417     albertel 5579:     unless (defined($cached)) {
1.624     albertel 5580: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5581: 	$result=\%dumpreply;
1.251     albertel 5582: 	my ($tmp) = keys(%dumpreply);
                   5583: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5584: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5585: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5586: 	    return $tmp;
1.416     albertel 5587: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5588: 	    $result=undef;
1.599     albertel 5589: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5590: 	}
                   5591:     }
1.624     albertel 5592:     return $result;
                   5593: }
                   5594: 
1.633     albertel 5595: sub devalidateuserresdata {
                   5596:     my ($uname,$udom)=@_;
                   5597:     my $hashid="$udom:$uname";
                   5598:     &devalidate_cache_new('userres',$hashid);
                   5599: }
                   5600: 
1.624     albertel 5601: sub get_userresdata {
                   5602:     my ($uname,$udom)=@_;
                   5603:     #most student don\'t have any data set, check if there is some data
                   5604:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5605: 
                   5606:     my $hashid="$udom:$uname";
                   5607:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5608:     if (!defined($cached)) {
                   5609: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5610: 	$result=\%resourcedata;
                   5611: 	&do_cache_new('userres',$hashid,$result,600);
                   5612:     }
                   5613:     my ($tmp)=keys(%$result);
                   5614:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5615: 	return $result;
                   5616:     }
                   5617:     #error 2 occurs when the .db doesn't exist
                   5618:     if ($tmp!~/error: 2 /) {
1.672     albertel 5619: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5620: 		 " Trying to get resource data for ".
                   5621: 		 $uname." at ".$udom.": ".
                   5622: 		 $tmp."</font>");
                   5623:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5624: 	#&EXT_cache_set($udom,$uname);
                   5625: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5626: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5627:     }
                   5628:     return $tmp;
                   5629: }
                   5630: 
                   5631: sub resdata {
                   5632:     my ($name,$domain,$type,@which)=@_;
                   5633:     my $result;
                   5634:     if ($type eq 'course') {
                   5635: 	$result=&get_courseresdata($name,$domain);
                   5636:     } elsif ($type eq 'user') {
                   5637: 	$result=&get_userresdata($name,$domain);
                   5638:     }
                   5639:     if (!ref($result)) { return $result; }    
1.251     albertel 5640:     foreach my $item (@which) {
1.417     albertel 5641: 	if (defined($result->{$item})) {
                   5642: 	    return $result->{$item};
1.251     albertel 5643: 	}
1.250     albertel 5644:     }
1.291     albertel 5645:     return undef;
1.200     www      5646: }
                   5647: 
1.379     matthew  5648: #
                   5649: # EXT resource caching routines
                   5650: #
                   5651: 
                   5652: sub clear_EXT_cache_status {
1.383     albertel 5653:     &delenv('cache.EXT.');
1.379     matthew  5654: }
                   5655: 
                   5656: sub EXT_cache_status {
                   5657:     my ($target_domain,$target_user) = @_;
1.383     albertel 5658:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5659:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5660:         # We know already the user has no data
                   5661:         return 1;
                   5662:     } else {
                   5663:         return 0;
                   5664:     }
                   5665: }
                   5666: 
                   5667: sub EXT_cache_set {
                   5668:     my ($target_domain,$target_user) = @_;
1.383     albertel 5669:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5670:     #&appenv($cachename => time);
1.379     matthew  5671: }
                   5672: 
1.28      www      5673: # --------------------------------------------------------- Value of a Variable
1.58      www      5674: sub EXT {
1.715     albertel 5675: 
1.395     albertel 5676:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5677:     unless ($varname) { return ''; }
1.218     albertel 5678:     #get real user name/domain, courseid and symb
                   5679:     my $courseid;
1.359     albertel 5680:     my $publicuser;
1.427     www      5681:     if ($symbparm) {
                   5682: 	$symbparm=&get_symb_from_alias($symbparm);
                   5683:     }
1.218     albertel 5684:     if (!($uname && $udom)) {
1.790     albertel 5685:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5686:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5687:     } else {
1.620     albertel 5688: 	$courseid=$env{'request.course.id'};
1.218     albertel 5689:     }
1.48      www      5690:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5691:     my $rest;
1.320     albertel 5692:     if (defined($therest[0])) {
1.48      www      5693:        $rest=join('.',@therest);
                   5694:     } else {
                   5695:        $rest='';
                   5696:     }
1.320     albertel 5697: 
1.57      www      5698:     my $qualifierrest=$qualifier;
                   5699:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5700:     my $spacequalifierrest=$space;
                   5701:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5702:     if ($realm eq 'user') {
1.48      www      5703: # --------------------------------------------------------------- user.resource
                   5704: 	if ($space eq 'resource') {
1.651     albertel 5705: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5706: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5707: 		 &&
1.744     albertel 5708: 		 ($symbparm eq &symbread()) ) {	
                   5709: 		# if we are in the middle of processing the resource the
                   5710: 		# get the value we are planning on committing
                   5711:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5712:                     return $Apache::lonhomework::results{$qualifierrest};
                   5713:                 } else {
                   5714:                     return $Apache::lonhomework::history{$qualifierrest};
                   5715:                 }
1.335     albertel 5716: 	    } else {
1.359     albertel 5717: 		my %restored;
1.620     albertel 5718: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5719: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5720: 		} else {
                   5721: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5722: 		}
1.335     albertel 5723: 		return $restored{$qualifierrest};
                   5724: 	    }
1.48      www      5725: # ----------------------------------------------------------------- user.access
                   5726:         } elsif ($space eq 'access') {
1.218     albertel 5727: 	    # FIXME - not supporting calls for a specific user
1.48      www      5728:             return &allowed($qualifier,$rest);
                   5729: # ------------------------------------------ user.preferences, user.environment
                   5730:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5731: 	    if (($uname eq $env{'user.name'}) &&
                   5732: 		($udom eq $env{'user.domain'})) {
                   5733: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5734: 	    } else {
1.359     albertel 5735: 		my %returnhash;
                   5736: 		if (!$publicuser) {
                   5737: 		    %returnhash=&userenvironment($udom,$uname,
                   5738: 						 $qualifierrest);
                   5739: 		}
1.218     albertel 5740: 		return $returnhash{$qualifierrest};
                   5741: 	    }
1.48      www      5742: # ----------------------------------------------------------------- user.course
                   5743:         } elsif ($space eq 'course') {
1.218     albertel 5744: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5745:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5746: # ------------------------------------------------------------------- user.role
                   5747:         } elsif ($space eq 'role') {
1.218     albertel 5748: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5749:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5750:             if ($qualifier eq 'value') {
                   5751: 		return $role;
                   5752:             } elsif ($qualifier eq 'extent') {
                   5753:                 return $where;
                   5754:             }
                   5755: # ----------------------------------------------------------------- user.domain
                   5756:         } elsif ($space eq 'domain') {
1.218     albertel 5757:             return $udom;
1.48      www      5758: # ------------------------------------------------------------------- user.name
                   5759:         } elsif ($space eq 'name') {
1.218     albertel 5760:             return $uname;
1.48      www      5761: # ---------------------------------------------------- Any other user namespace
1.29      www      5762:         } else {
1.359     albertel 5763: 	    my %reply;
                   5764: 	    if (!$publicuser) {
                   5765: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5766: 	    }
                   5767: 	    return $reply{$qualifierrest};
1.48      www      5768:         }
1.236     www      5769:     } elsif ($realm eq 'query') {
                   5770: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5771:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5772: 						[$spacequalifierrest]);
1.620     albertel 5773: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5774:    } elsif ($realm eq 'request') {
1.48      www      5775: # ------------------------------------------------------------- request.browser
                   5776:         if ($space eq 'browser') {
1.430     www      5777: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5778: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5779: 		    return 1;
                   5780: 		} else {
                   5781: 		    return 0;
                   5782: 		}
                   5783: 	    } else {
1.620     albertel 5784: 		return $env{'browser.'.$qualifier};
1.430     www      5785: 	    }
1.57      www      5786: # ------------------------------------------------------------ request.filename
                   5787:         } else {
1.620     albertel 5788:             return $env{'request.'.$spacequalifierrest};
1.29      www      5789:         }
1.28      www      5790:     } elsif ($realm eq 'course') {
1.48      www      5791: # ---------------------------------------------------------- course.description
1.620     albertel 5792:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5793:     } elsif ($realm eq 'resource') {
1.165     www      5794: 
1.620     albertel 5795: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5796: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5797: 	}
1.693     albertel 5798: 
                   5799: 	if ($space eq 'title') {
                   5800: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5801: 	    return &gettitle($symbparm);
                   5802: 	}
                   5803: 	
                   5804: 	if ($space eq 'map') {
                   5805: 	    my ($map) = &decode_symb($symbparm);
                   5806: 	    return &symbread($map);
                   5807: 	}
                   5808: 
                   5809: 	my ($section, $group, @groups);
1.593     albertel 5810: 	my ($courselevelm,$courselevel);
1.539     albertel 5811: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5812: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5813: 
1.218     albertel 5814: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5815: 
1.60      www      5816: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5817: 	    my $symbp=$symbparm;
1.735     albertel 5818: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5819: 
                   5820: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5821: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5822: 
1.620     albertel 5823: 	    if (($env{'user.name'} eq $uname) &&
                   5824: 		($env{'user.domain'} eq $udom)) {
                   5825: 		$section=$env{'request.course.sec'};
1.733     raeburn  5826:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5827:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5828: 	    } else {
1.539     albertel 5829: 		if (! defined($usection)) {
1.551     albertel 5830: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5831: 		} else {
                   5832: 		    $section = $usection;
                   5833: 		}
1.733     raeburn  5834:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5835: 	    }
                   5836: 
                   5837: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5838: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5839: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5840: 
1.593     albertel 5841: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5842: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5843: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5844: 
1.60      www      5845: # ----------------------------------------------------------- first, check user
1.624     albertel 5846: 
                   5847: 	    my $userreply=&resdata($uname,$udom,'user',
                   5848: 				       ($courselevelr,$courselevelm,
                   5849: 					$courselevel));
                   5850: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5851: 
1.594     albertel 5852: # ------------------------------------------------ second, check some of course
1.684     raeburn  5853:             my $coursereply;
1.691     raeburn  5854:             if (@groups > 0) {
                   5855:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5856:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5857:                 if (defined($coursereply)) { return $coursereply; }
                   5858:             }
1.96      www      5859: 
1.684     raeburn  5860: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5861: 				     $env{'course.'.$courseid.'.domain'},
                   5862: 				     'course',
                   5863: 				     ($seclevelr,$seclevelm,$seclevel,
                   5864: 				      $courselevelr));
1.287     albertel 5865: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5866: 
1.60      www      5867: # ------------------------------------------------------ third, check map parms
1.218     albertel 5868: 	    my %parmhash=();
                   5869: 	    my $thisparm='';
                   5870: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5871: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5872: 		    &GDBM_READER(),0640)) {
1.218     albertel 5873: 		$thisparm=$parmhash{$symbparm};
                   5874: 		untie(%parmhash);
                   5875: 	    }
                   5876: 	    if ($thisparm) { return $thisparm; }
                   5877: 	}
1.594     albertel 5878: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5879: 
1.218     albertel 5880: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5881: 	my $filename;
                   5882: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5883: 	if ($symbparm) {
1.409     www      5884: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5885: 	} else {
1.620     albertel 5886: 	    $filename=$env{'request.filename'};
1.282     albertel 5887: 	}
                   5888: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5889: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5890: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5891: 	if (defined($metadata)) { return $metadata; }
1.142     www      5892: 
1.594     albertel 5893: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5894: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5895: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5896: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5897: 				     $env{'course.'.$courseid.'.domain'},
                   5898: 				     'course',
                   5899: 				     ($courselevelm,$courselevel));
1.593     albertel 5900: 	    if (defined($coursereply)) { return $coursereply; }
                   5901: 	}
1.145     www      5902: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5903: 	unless ($space eq '0') {
1.336     albertel 5904: 	    my @parts=split(/_/,$space);
                   5905: 	    my $id=pop(@parts);
                   5906: 	    my $part=join('_',@parts);
                   5907: 	    if ($part eq '') { $part='0'; }
                   5908: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5909: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5910: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5911: 	}
1.395     albertel 5912: 	if ($recurse) { return undef; }
                   5913: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5914: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5915: 
1.48      www      5916: # ---------------------------------------------------- Any other user namespace
                   5917:     } elsif ($realm eq 'environment') {
                   5918: # ----------------------------------------------------------------- environment
1.620     albertel 5919: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5920: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5921: 	} else {
1.770     albertel 5922: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5923: 		return '';
                   5924: 	    }
1.219     albertel 5925: 	    my %returnhash=&userenvironment($udom,$uname,
                   5926: 					    $spacequalifierrest);
                   5927: 	    return $returnhash{$spacequalifierrest};
                   5928: 	}
1.28      www      5929:     } elsif ($realm eq 'system') {
1.48      www      5930: # ----------------------------------------------------------------- system.time
                   5931: 	if ($space eq 'time') {
                   5932: 	    return time;
                   5933:         }
1.696     albertel 5934:     } elsif ($realm eq 'server') {
                   5935: # ----------------------------------------------------------------- system.time
                   5936: 	if ($space eq 'name') {
                   5937: 	    return $ENV{'SERVER_NAME'};
                   5938:         }
1.28      www      5939:     }
1.48      www      5940:     return '';
1.61      www      5941: }
                   5942: 
1.691     raeburn  5943: sub check_group_parms {
                   5944:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5945:     my @groupitems = ();
                   5946:     my $resultitem;
                   5947:     my @levels = ($symbparm,$mapparm,$what);
                   5948:     foreach my $group (@{$groups}) {
                   5949:         foreach my $level (@levels) {
                   5950:              my $item = $courseid.'.['.$group.'].'.$level;
                   5951:              push(@groupitems,$item);
                   5952:         }
                   5953:     }
                   5954:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5955:                             $env{'course.'.$courseid.'.domain'},
                   5956:                                      'course',@groupitems);
                   5957:     return $coursereply;
                   5958: }
                   5959: 
                   5960: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5961:     my ($courseid,@groups) = @_;
                   5962:     @groups = sort(@groups);
1.691     raeburn  5963:     return @groups;
                   5964: }
                   5965: 
1.395     albertel 5966: sub packages_tab_default {
                   5967:     my ($uri,$varname)=@_;
                   5968:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5969: 
                   5970:     my (@extension,@specifics,$do_default);
                   5971:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5972: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5973: 	if ($pack_type eq 'default') {
                   5974: 	    $do_default=1;
                   5975: 	} elsif ($pack_type eq 'extension') {
                   5976: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5977: 	} else {
                   5978: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5979: 	}
                   5980:     }
                   5981:     # first look for a package that matches the requested part id
                   5982:     foreach my $package (@specifics) {
                   5983: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5984: 	next if ($pack_part ne $part);
                   5985: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5986: 	    return $packagetab{"$pack_type&$name&default"};
                   5987: 	}
                   5988:     }
                   5989:     # look for any possible matching non extension_ package
                   5990:     foreach my $package (@specifics) {
                   5991: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5992: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5993: 	    return $packagetab{"$pack_type&$name&default"};
                   5994: 	}
1.585     albertel 5995: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5996: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5997: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5998: 	}
                   5999:     }
1.738     albertel 6000:     # look for any posible extension_ match
                   6001:     foreach my $package (@extension) {
                   6002: 	my ($package,$pack_type)=@{$package};
                   6003: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6004: 	    return $packagetab{"$pack_type&$name&default"};
                   6005: 	}
                   6006: 	if (defined($packagetab{$package."&$name&default"})) {
                   6007: 	    return $packagetab{$package."&$name&default"};
                   6008: 	}
                   6009:     }
                   6010:     # look for a global default setting
                   6011:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6012: 	return $packagetab{"default&$name&default"};
                   6013:     }
1.395     albertel 6014:     return undef;
                   6015: }
                   6016: 
1.334     albertel 6017: sub add_prefix_and_part {
                   6018:     my ($prefix,$part)=@_;
                   6019:     my $keyroot;
                   6020:     if (defined($prefix) && $prefix !~ /^__/) {
                   6021: 	# prefix that has a part already
                   6022: 	$keyroot=$prefix;
                   6023:     } elsif (defined($prefix)) {
                   6024: 	# prefix that is missing a part
                   6025: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6026:     } else {
                   6027: 	# no prefix at all
                   6028: 	if (defined($part)) { $keyroot='_'.$part; }
                   6029:     }
                   6030:     return $keyroot;
                   6031: }
                   6032: 
1.71      www      6033: # ---------------------------------------------------------------- Get metadata
                   6034: 
1.599     albertel 6035: my %metaentry;
1.71      www      6036: sub metadata {
1.176     www      6037:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6038:     $uri=&declutter($uri);
1.288     albertel 6039:     # if it is a non metadata possible uri return quickly
1.529     albertel 6040:     if (($uri eq '') || 
                   6041: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6042: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6043:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6044: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6045: 	return undef;
1.288     albertel 6046:     }
1.73      www      6047:     my $filename=$uri;
                   6048:     $uri=~s/\.meta$//;
1.172     www      6049: #
                   6050: # Is the metadata already cached?
1.177     www      6051: # Look at timestamp of caching
1.172     www      6052: # Everything is cached by the main uri, libraries are never directly cached
                   6053: #
1.428     albertel 6054:     if (!defined($liburi)) {
1.599     albertel 6055: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6056: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6057:     }
                   6058:     {
1.172     www      6059: #
                   6060: # Is this a recursive call for a library?
                   6061: #
1.599     albertel 6062: #	if (! exists($metacache{$uri})) {
                   6063: #	    $metacache{$uri}={};
                   6064: #	}
1.171     www      6065:         if ($liburi) {
                   6066: 	    $liburi=&declutter($liburi);
                   6067:             $filename=$liburi;
1.401     bowersj2 6068:         } else {
1.599     albertel 6069: 	    &devalidate_cache_new('meta',$uri);
                   6070: 	    undef(%metaentry);
1.401     bowersj2 6071: 	}
1.140     www      6072:         my %metathesekeys=();
1.73      www      6073:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6074: 	my $metastring;
1.768     albertel 6075: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6076: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6077: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6078: 	    $metastring=&getfile($file);
1.489     albertel 6079: 	}
1.208     albertel 6080:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6081:         my $token;
1.140     www      6082:         undef %metathesekeys;
1.71      www      6083:         while ($token=$parser->get_token) {
1.339     albertel 6084: 	    if ($token->[0] eq 'S') {
                   6085: 		if (defined($token->[2]->{'package'})) {
1.172     www      6086: #
                   6087: # This is a package - get package info
                   6088: #
1.339     albertel 6089: 		    my $package=$token->[2]->{'package'};
                   6090: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6091: 		    if (defined($token->[2]->{'id'})) { 
                   6092: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6093: 		    }
1.599     albertel 6094: 		    if ($metaentry{':packages'}) {
                   6095: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6096: 		    } else {
1.599     albertel 6097: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6098: 		    }
1.736     albertel 6099: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6100: 			my $part=$keyroot;
                   6101: 			$part=~s/^\_//;
1.736     albertel 6102: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6103: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6104: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6105: 			    # ignore package.tab specified default values
                   6106:                             # here &package_tab_default() will fetch those
                   6107: 			    if ($subp eq 'default') { next; }
1.736     albertel 6108: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6109: 			    my $unikey;
                   6110: 			    if ($pack =~ /_0$/) {
                   6111: 				$unikey='parameter_0_'.$name;
                   6112: 				$part=0;
                   6113: 			    } else {
                   6114: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6115: 			    }
1.339     albertel 6116: 			    if ($subp eq 'display') {
                   6117: 				$value.=' [Part: '.$part.']';
                   6118: 			    }
1.599     albertel 6119: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6120: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6121: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6122: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6123: 			    }
1.599     albertel 6124: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6125: 				$metaentry{':'.$unikey}=
                   6126: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6127: 			    }
1.339     albertel 6128: 			}
                   6129: 		    }
                   6130: 		} else {
1.172     www      6131: #
                   6132: # This is not a package - some other kind of start tag
1.339     albertel 6133: #
                   6134: 		    my $entry=$token->[1];
                   6135: 		    my $unikey;
                   6136: 		    if ($entry eq 'import') {
                   6137: 			$unikey='';
                   6138: 		    } else {
                   6139: 			$unikey=$entry;
                   6140: 		    }
                   6141: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6142: 
                   6143: 		    if (defined($token->[2]->{'id'})) { 
                   6144: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6145: 		    }
1.175     www      6146: 
1.339     albertel 6147: 		    if ($entry eq 'import') {
1.175     www      6148: #
                   6149: # Importing a library here
1.339     albertel 6150: #
                   6151: 			if ($depthcount<20) {
                   6152: 			    my $location=$parser->get_text('/import');
                   6153: 			    my $dir=$filename;
                   6154: 			    $dir=~s|[^/]*$||;
                   6155: 			    $location=&filelocation($dir,$location);
1.736     albertel 6156: 			    my $metadata = 
                   6157: 				&metadata($uri,'keys', $location,$unikey,
                   6158: 					  $depthcount+1);
                   6159: 			    foreach my $meta (split(',',$metadata)) {
                   6160: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6161: 				$metathesekeys{$meta}=1;
1.339     albertel 6162: 			    }
                   6163: 			}
                   6164: 		    } else { 
                   6165: 			
                   6166: 			if (defined($token->[2]->{'name'})) { 
                   6167: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6168: 			}
                   6169: 			$metathesekeys{$unikey}=1;
1.736     albertel 6170: 			foreach my $param (@{$token->[3]}) {
                   6171: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6172: 				$token->[2]->{$param};
1.339     albertel 6173: 			}
                   6174: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6175: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6176: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6177: 		 # only ws inside the tag, and not in default, so use default
                   6178: 		 # as value
1.599     albertel 6179: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6180: 			} else {
1.321     albertel 6181: 		  # either something interesting inside the tag or default
                   6182:                   # uninteresting
1.599     albertel 6183: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6184: 			}
1.172     www      6185: # end of not-a-package not-a-library import
1.339     albertel 6186: 		    }
1.172     www      6187: # end of not-a-package start tag
1.339     albertel 6188: 		}
1.172     www      6189: # the next is the end of "start tag"
1.339     albertel 6190: 	    }
                   6191: 	}
1.483     albertel 6192: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6193: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6194: 	    #no specific packages #how's our extension
                   6195: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6196: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6197: 					 \%metathesekeys);
                   6198: 	}
1.599     albertel 6199: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6200: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6201: 		#no specific packages well let's get default then
                   6202: 		if ($key!~/^default&/) { next; }
1.488     albertel 6203: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6204: 					     \%metathesekeys);
                   6205: 	    }
                   6206: 	}
1.338     www      6207: # are there custom rights to evaluate
1.599     albertel 6208: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6209: 
1.338     www      6210:     #
                   6211:     # Importing a rights file here
1.339     albertel 6212:     #
                   6213: 	    unless ($depthcount) {
1.599     albertel 6214: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6215: 		my $dir=$filename;
                   6216: 		$dir=~s|[^/]*$||;
                   6217: 		$location=&filelocation($dir,$location);
1.736     albertel 6218: 		my $rights_metadata =
                   6219: 		    &metadata($uri,'keys',$location,'_rights',
                   6220: 			      $depthcount+1);
                   6221: 		foreach my $rights (split(',',$rights_metadata)) {
                   6222: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6223: 		    $metathesekeys{$rights}=1;
1.339     albertel 6224: 		}
                   6225: 	    }
                   6226: 	}
1.737     albertel 6227: 	# uniqifiy package listing
                   6228: 	my %seen;
                   6229: 	my @uniq_packages =
                   6230: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6231: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6232: 
                   6233: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6234: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6235: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6236: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6237: # this is the end of "was not already recently cached
1.71      www      6238:     }
1.599     albertel 6239:     return $metaentry{':'.$what};
1.261     albertel 6240: }
                   6241: 
1.488     albertel 6242: sub metadata_create_package_def {
1.483     albertel 6243:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6244:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6245:     if ($subp eq 'default') { next; }
                   6246:     
1.599     albertel 6247:     if (defined($metaentry{':packages'})) {
                   6248: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6249:     } else {
1.599     albertel 6250: 	$metaentry{':packages'}=$package;
1.483     albertel 6251:     }
                   6252:     my $value=$packagetab{$key};
                   6253:     my $unikey;
                   6254:     $unikey='parameter_0_'.$name;
1.599     albertel 6255:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6256:     $$metathesekeys{$unikey}=1;
1.599     albertel 6257:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6258: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6259:     }
1.599     albertel 6260:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6261: 	$metaentry{':'.$unikey}=
                   6262: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6263:     }
                   6264: }
                   6265: 
1.261     albertel 6266: sub metadata_generate_part0 {
                   6267:     my ($metadata,$metacache,$uri) = @_;
                   6268:     my %allnames;
1.737     albertel 6269:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6270: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6271: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6272: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6273: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6274: 	    $allnames{$name}=$part;
                   6275: 	  }
                   6276: 	}
                   6277:     }
                   6278:     foreach my $name (keys(%allnames)) {
                   6279:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6280:       my $key=":parameter_0_$name";
1.261     albertel 6281:       $$metacache{"$key.part"}='0';
                   6282:       $$metacache{"$key.name"}=$name;
1.428     albertel 6283:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6284: 					   $allnames{$name}.'_'.$name.
                   6285: 					   '.type'};
1.428     albertel 6286:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6287: 			     '.display'};
1.644     www      6288:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6289:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6290:       $$metacache{"$key.display"}=$olddis;
                   6291:     }
1.71      www      6292: }
                   6293: 
1.764     albertel 6294: # ------------------------------------------------------ Devalidate title cache
                   6295: 
                   6296: sub devalidate_title_cache {
                   6297:     my ($url)=@_;
                   6298:     if (!$env{'request.course.id'}) { return; }
                   6299:     my $symb=&symbread($url);
                   6300:     if (!$symb) { return; }
                   6301:     my $key=$env{'request.course.id'}."\0".$symb;
                   6302:     &devalidate_cache_new('title',$key);
                   6303: }
                   6304: 
1.301     www      6305: # ------------------------------------------------- Get the title of a resource
                   6306: 
                   6307: sub gettitle {
                   6308:     my $urlsymb=shift;
                   6309:     my $symb=&symbread($urlsymb);
1.534     albertel 6310:     if ($symb) {
1.620     albertel 6311: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6312: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6313: 	if (defined($cached)) { 
                   6314: 	    return $result;
                   6315: 	}
1.534     albertel 6316: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6317: 	my $title='';
                   6318: 	my %bighash;
1.620     albertel 6319: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6320: 		&GDBM_READER(),0640)) {
                   6321: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6322: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6323: 	    untie %bighash;
                   6324: 	}
                   6325: 	$title=~s/\&colon\;/\:/gs;
                   6326: 	if ($title) {
1.599     albertel 6327: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6328: 	}
                   6329: 	$urlsymb=$url;
                   6330:     }
                   6331:     my $title=&metadata($urlsymb,'title');
                   6332:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6333:     return $title;
1.301     www      6334: }
1.613     albertel 6335: 
1.614     albertel 6336: sub get_slot {
                   6337:     my ($which,$cnum,$cdom)=@_;
                   6338:     if (!$cnum || !$cdom) {
1.790     albertel 6339: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6340: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6341: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6342:     }
1.703     albertel 6343:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6344:     my %slotinfo;
                   6345:     if (exists($remembered{$key})) {
                   6346: 	$slotinfo{$which} = $remembered{$key};
                   6347:     } else {
                   6348: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6349: 	&Apache::lonhomework::showhash(%slotinfo);
                   6350: 	my ($tmp)=keys(%slotinfo);
                   6351: 	if ($tmp=~/^error:/) { return (); }
                   6352: 	$remembered{$key} = $slotinfo{$which};
                   6353:     }
1.616     albertel 6354:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6355: 	return %{$slotinfo{$which}};
                   6356:     }
                   6357:     return $slotinfo{$which};
1.614     albertel 6358: }
1.31      www      6359: # ------------------------------------------------- Update symbolic store links
                   6360: 
                   6361: sub symblist {
                   6362:     my ($mapname,%newhash)=@_;
1.438     www      6363:     $mapname=&deversion(&declutter($mapname));
1.31      www      6364:     my %hash;
1.620     albertel 6365:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6366:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6367:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6368: 	    foreach my $url (keys %newhash) {
                   6369: 		next if ($url eq 'last_known'
                   6370: 			 && $env{'form.no_update_last_known'});
                   6371: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6372: 						    $newhash{$url}->[1],
                   6373: 						    $newhash{$url}->[0]);
1.191     harris41 6374:             }
1.31      www      6375:             if (untie(%hash)) {
                   6376: 		return 'ok';
                   6377:             }
                   6378:         }
                   6379:     }
                   6380:     return 'error';
1.212     www      6381: }
                   6382: 
                   6383: # --------------------------------------------------------------- Verify a symb
                   6384: 
                   6385: sub symbverify {
1.510     www      6386:     my ($symb,$thisurl)=@_;
                   6387:     my $thisfn=$thisurl;
1.439     www      6388:     $thisfn=&declutter($thisfn);
1.215     www      6389: # direct jump to resource in page or to a sequence - will construct own symbs
                   6390:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6391: # check URL part
1.409     www      6392:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6393: 
1.431     www      6394:     unless ($url eq $thisfn) { return 0; }
1.213     www      6395: 
1.216     www      6396:     $symb=&symbclean($symb);
1.510     www      6397:     $thisurl=&deversion($thisurl);
1.439     www      6398:     $thisfn=&deversion($thisfn);
1.213     www      6399: 
                   6400:     my %bighash;
                   6401:     my $okay=0;
1.431     www      6402: 
1.620     albertel 6403:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6404:                             &GDBM_READER(),0640)) {
1.510     www      6405:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6406:         unless ($ids) { 
1.510     www      6407:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6408:         }
                   6409:         if ($ids) {
                   6410: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6411: 	    foreach my $id (split(/\,/,$ids)) {
                   6412: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6413:                if (
                   6414:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6415:    eq $symb) { 
1.620     albertel 6416: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6417: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6418: 		       $okay=1; 
                   6419: 		   }
                   6420: 	       }
1.216     www      6421: 	   }
                   6422:         }
1.213     www      6423: 	untie(%bighash);
                   6424:     }
                   6425:     return $okay;
1.31      www      6426: }
                   6427: 
1.210     www      6428: # --------------------------------------------------------------- Clean-up symb
                   6429: 
                   6430: sub symbclean {
                   6431:     my $symb=shift;
1.568     albertel 6432:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6433: # remove version from map
                   6434:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6435: 
1.210     www      6436: # remove version from URL
                   6437:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6438: 
1.507     www      6439: # remove wrapper
                   6440: 
1.510     www      6441:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6442:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6443:     return $symb;
1.409     www      6444: }
                   6445: 
                   6446: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6447: 
                   6448: sub encode_symb {
                   6449:     my ($map,$resid,$url)=@_;
                   6450:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6451: }
1.409     www      6452: 
                   6453: sub decode_symb {
1.568     albertel 6454:     my $symb=shift;
                   6455:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6456:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6457:     return (&fixversion($map),$resid,&fixversion($url));
                   6458: }
                   6459: 
                   6460: sub fixversion {
                   6461:     my $fn=shift;
1.609     banghart 6462:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6463:     my %bighash;
                   6464:     my $uri=&clutter($fn);
1.620     albertel 6465:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6466: # is this cached?
1.599     albertel 6467:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6468:     if (defined($cached)) { return $result; }
                   6469: # unfortunately not cached, or expired
1.620     albertel 6470:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6471: 	    &GDBM_READER(),0640)) {
                   6472:  	if ($bighash{'version_'.$uri}) {
                   6473:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6474:  	    unless (($version eq 'mostrecent') || 
                   6475: 		    ($version==&getversion($uri))) {
1.440     www      6476:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6477:  	    }
                   6478:  	}
                   6479:  	untie %bighash;
1.413     www      6480:     }
1.599     albertel 6481:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6482: }
                   6483: 
                   6484: sub deversion {
                   6485:     my $url=shift;
                   6486:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6487:     return $url;
1.210     www      6488: }
                   6489: 
1.31      www      6490: # ------------------------------------------------------ Return symb list entry
                   6491: 
                   6492: sub symbread {
1.249     www      6493:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6494:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6495:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6496: # no filename provided? try from environment
1.44      www      6497:     unless ($thisfn) {
1.620     albertel 6498:         if ($env{'request.symb'}) {
                   6499: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6500: 	}
1.620     albertel 6501: 	$thisfn=$env{'request.filename'};
1.44      www      6502:     }
1.569     albertel 6503:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6504: # is that filename actually a symb? Verify, clean, and return
                   6505:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6506: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6507: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6508: 	}
1.242     www      6509:     }
1.44      www      6510:     $thisfn=declutter($thisfn);
1.31      www      6511:     my %hash;
1.37      www      6512:     my %bighash;
                   6513:     my $syval='';
1.620     albertel 6514:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6515:         my $targetfn = $thisfn;
1.609     banghart 6516:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6517:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6518:         }
1.687     albertel 6519: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6520: 	    $targetfn=$1;
                   6521: 	}
1.620     albertel 6522:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6523:                       &GDBM_READER(),0640)) {
1.481     raeburn  6524: 	    $syval=$hash{$targetfn};
1.37      www      6525:             untie(%hash);
                   6526:         }
                   6527: # ---------------------------------------------------------- There was an entry
                   6528:         if ($syval) {
1.601     albertel 6529: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6530: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6531: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6532: 		    #return $env{$cache_str}='';
1.601     albertel 6533: 		#}    
                   6534: 		#$syval.=$1;
                   6535: 	    #}
1.37      www      6536:         } else {
                   6537: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6538:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6539:                             &GDBM_READER(),0640)) {
1.37      www      6540: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6541:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6542:               unless ($ids) { 
                   6543:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6544:               }
                   6545:               unless ($ids) {
                   6546: # alias?
                   6547: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6548:               }
1.37      www      6549:               if ($ids) {
                   6550: # ------------------------------------------------------------------- Has ID(s)
                   6551:                  my @possibilities=split(/\,/,$ids);
1.39      www      6552:                  if ($#possibilities==0) {
                   6553: # ----------------------------------------------- There is only one possibility
1.37      www      6554: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6555: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6556: 						    $resid,$thisfn);
1.249     www      6557:                  } elsif (!$donotrecurse) {
1.39      www      6558: # ------------------------------------------ There is more than one possibility
                   6559:                      my $realpossible=0;
1.800     albertel 6560:                      foreach my $id (@possibilities) {
                   6561: 			 my $file=$bighash{'src_'.$id};
1.39      www      6562:                          if (&allowed('bre',$file)) {
1.800     albertel 6563:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6564:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6565: 				$realpossible++;
1.626     albertel 6566:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6567: 						    $resid,$thisfn);
1.39      www      6568:                             }
                   6569: 			 }
1.191     harris41 6570:                      }
1.39      www      6571: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6572:                  } else {
                   6573:                      $syval='';
1.37      www      6574:                  }
                   6575: 	      }
                   6576:               untie(%bighash)
1.481     raeburn  6577:            }
1.31      www      6578:         }
1.62      www      6579:         if ($syval) {
1.620     albertel 6580: 	    return $env{$cache_str}=$syval;
1.62      www      6581:         }
1.31      www      6582:     }
1.44      www      6583:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6584:     return $env{$cache_str}='';
1.31      www      6585: }
                   6586: 
                   6587: # ---------------------------------------------------------- Return random seed
                   6588: 
1.32      www      6589: sub numval {
                   6590:     my $txt=shift;
                   6591:     $txt=~tr/A-J/0-9/;
                   6592:     $txt=~tr/a-j/0-9/;
                   6593:     $txt=~tr/K-T/0-9/;
                   6594:     $txt=~tr/k-t/0-9/;
                   6595:     $txt=~tr/U-Z/0-5/;
                   6596:     $txt=~tr/u-z/0-5/;
                   6597:     $txt=~s/\D//g;
1.564     albertel 6598:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6599:     return int($txt);
1.368     albertel 6600: }
                   6601: 
1.484     albertel 6602: sub numval2 {
                   6603:     my $txt=shift;
                   6604:     $txt=~tr/A-J/0-9/;
                   6605:     $txt=~tr/a-j/0-9/;
                   6606:     $txt=~tr/K-T/0-9/;
                   6607:     $txt=~tr/k-t/0-9/;
                   6608:     $txt=~tr/U-Z/0-5/;
                   6609:     $txt=~tr/u-z/0-5/;
                   6610:     $txt=~s/\D//g;
                   6611:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6612:     my $total;
                   6613:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6614:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6615:     return int($total);
                   6616: }
                   6617: 
1.575     albertel 6618: sub numval3 {
                   6619:     use integer;
                   6620:     my $txt=shift;
                   6621:     $txt=~tr/A-J/0-9/;
                   6622:     $txt=~tr/a-j/0-9/;
                   6623:     $txt=~tr/K-T/0-9/;
                   6624:     $txt=~tr/k-t/0-9/;
                   6625:     $txt=~tr/U-Z/0-5/;
                   6626:     $txt=~tr/u-z/0-5/;
                   6627:     $txt=~s/\D//g;
                   6628:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6629:     my $total;
                   6630:     foreach my $val (@txts) { $total+=$val; }
                   6631:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6632:     return $total;
                   6633: }
                   6634: 
1.675     albertel 6635: sub digest {
                   6636:     my ($data)=@_;
                   6637:     my $digest=&Digest::MD5::md5($data);
                   6638:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6639:     my ($e,$f);
                   6640:     {
                   6641:         use integer;
                   6642:         $e=($a+$b);
                   6643:         $f=($c+$d);
                   6644:         if ($_64bit) {
                   6645:             $e=(($e<<32)>>32);
                   6646:             $f=(($f<<32)>>32);
                   6647:         }
                   6648:     }
                   6649:     if (wantarray) {
                   6650: 	return ($e,$f);
                   6651:     } else {
                   6652: 	my $g;
                   6653: 	{
                   6654: 	    use integer;
                   6655: 	    $g=($e+$f);
                   6656: 	    if ($_64bit) {
                   6657: 		$g=(($g<<32)>>32);
                   6658: 	    }
                   6659: 	}
                   6660: 	return $g;
                   6661:     }
                   6662: }
                   6663: 
1.368     albertel 6664: sub latest_rnd_algorithm_id {
1.675     albertel 6665:     return '64bit5';
1.366     albertel 6666: }
1.32      www      6667: 
1.503     albertel 6668: sub get_rand_alg {
                   6669:     my ($courseid)=@_;
1.790     albertel 6670:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6671:     if ($courseid) {
1.620     albertel 6672: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6673:     }
                   6674:     return &latest_rnd_algorithm_id();
                   6675: }
                   6676: 
1.562     albertel 6677: sub validCODE {
                   6678:     my ($CODE)=@_;
                   6679:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6680:     return 0;
                   6681: }
                   6682: 
1.491     albertel 6683: sub getCODE {
1.620     albertel 6684:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6685:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6686: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6687: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6688: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6689:     }
                   6690:     return undef;
                   6691: }
                   6692: 
1.31      www      6693: sub rndseed {
1.155     albertel 6694:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6695: 
1.790     albertel 6696:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6697:     if (!$symb) {
1.366     albertel 6698: 	unless ($symb=$wsymb) { return time; }
                   6699:     }
                   6700:     if (!$courseid) { $courseid=$wcourseid; }
                   6701:     if (!$domain) { $domain=$wdomain; }
                   6702:     if (!$username) { $username=$wusername }
1.503     albertel 6703:     my $which=&get_rand_alg();
1.803     albertel 6704: 
1.491     albertel 6705:     if (defined(&getCODE())) {
1.675     albertel 6706: 	if ($which eq '64bit5') {
                   6707: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6708: 	} elsif ($which eq '64bit4') {
1.575     albertel 6709: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6710: 	} else {
                   6711: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6712: 	}
1.675     albertel 6713:     } elsif ($which eq '64bit5') {
                   6714: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6715:     } elsif ($which eq '64bit4') {
                   6716: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6717:     } elsif ($which eq '64bit3') {
                   6718: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6719:     } elsif ($which eq '64bit2') {
                   6720: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6721:     } elsif ($which eq '64bit') {
                   6722: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6723:     }
                   6724:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6725: }
                   6726: 
                   6727: sub rndseed_32bit {
                   6728:     my ($symb,$courseid,$domain,$username)=@_;
                   6729:     {
                   6730: 	use integer;
                   6731: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6732: 	my $symbseed=numval($symb) << 22;
                   6733: 	my $namechck=unpack("%32C*",$username) << 17;
                   6734: 	my $nameseed=numval($username) << 12;
                   6735: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6736: 	my $courseseed=unpack("%32C*",$courseid);
                   6737: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6738: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6739: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6740: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6741: 	return $num;
                   6742:     }
                   6743: }
                   6744: 
                   6745: sub rndseed_64bit {
                   6746:     my ($symb,$courseid,$domain,$username)=@_;
                   6747:     {
                   6748: 	use integer;
                   6749: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6750: 	my $symbseed=numval($symb) << 10;
                   6751: 	my $namechck=unpack("%32S*",$username);
                   6752: 	
                   6753: 	my $nameseed=numval($username) << 21;
                   6754: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6755: 	my $courseseed=unpack("%32S*",$courseid);
                   6756: 	
                   6757: 	my $num1=$symbchck+$symbseed+$namechck;
                   6758: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6759: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6760: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6761: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6762: 	return "$num1,$num2";
1.155     albertel 6763:     }
1.366     albertel 6764: }
                   6765: 
1.443     albertel 6766: sub rndseed_64bit2 {
                   6767:     my ($symb,$courseid,$domain,$username)=@_;
                   6768:     {
                   6769: 	use integer;
                   6770: 	# strings need to be an even # of cahracters long, it it is odd the
                   6771:         # last characters gets thrown away
                   6772: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6773: 	my $symbseed=numval($symb) << 10;
                   6774: 	my $namechck=unpack("%32S*",$username.' ');
                   6775: 	
                   6776: 	my $nameseed=numval($username) << 21;
1.501     albertel 6777: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6778: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6779: 	
                   6780: 	my $num1=$symbchck+$symbseed+$namechck;
                   6781: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6782: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6783: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6784: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6785: 	return "$num1,$num2";
                   6786:     }
                   6787: }
                   6788: 
                   6789: sub rndseed_64bit3 {
                   6790:     my ($symb,$courseid,$domain,$username)=@_;
                   6791:     {
                   6792: 	use integer;
                   6793: 	# strings need to be an even # of cahracters long, it it is odd the
                   6794:         # last characters gets thrown away
                   6795: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6796: 	my $symbseed=numval2($symb) << 10;
                   6797: 	my $namechck=unpack("%32S*",$username.' ');
                   6798: 	
                   6799: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6800: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6801: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6802: 	
                   6803: 	my $num1=$symbchck+$symbseed+$namechck;
                   6804: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6805: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6806: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6807: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6808: 	
1.503     albertel 6809: 	return "$num1:$num2";
1.443     albertel 6810:     }
                   6811: }
                   6812: 
1.575     albertel 6813: sub rndseed_64bit4 {
                   6814:     my ($symb,$courseid,$domain,$username)=@_;
                   6815:     {
                   6816: 	use integer;
                   6817: 	# strings need to be an even # of cahracters long, it it is odd the
                   6818:         # last characters gets thrown away
                   6819: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6820: 	my $symbseed=numval3($symb) << 10;
                   6821: 	my $namechck=unpack("%32S*",$username.' ');
                   6822: 	
                   6823: 	my $nameseed=numval3($username) << 21;
                   6824: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6825: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6826: 	
                   6827: 	my $num1=$symbchck+$symbseed+$namechck;
                   6828: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6829: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6830: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6831: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6832: 	
                   6833: 	return "$num1:$num2";
                   6834:     }
                   6835: }
                   6836: 
1.675     albertel 6837: sub rndseed_64bit5 {
                   6838:     my ($symb,$courseid,$domain,$username)=@_;
                   6839:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6840:     return "$num1:$num2";
                   6841: }
                   6842: 
1.366     albertel 6843: sub rndseed_CODE_64bit {
                   6844:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6845:     {
1.366     albertel 6846: 	use integer;
1.443     albertel 6847: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6848: 	my $symbseed=numval2($symb);
1.491     albertel 6849: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6850: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6851: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6852: 	my $num1=$symbseed+$CODEchck;
                   6853: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6854: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6855: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6856: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6857: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6858: 	return "$num1:$num2";
1.366     albertel 6859:     }
                   6860: }
                   6861: 
1.575     albertel 6862: sub rndseed_CODE_64bit4 {
                   6863:     my ($symb,$courseid,$domain,$username)=@_;
                   6864:     {
                   6865: 	use integer;
                   6866: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6867: 	my $symbseed=numval3($symb);
                   6868: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6869: 	my $CODEseed=numval3(&getCODE());
                   6870: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6871: 	my $num1=$symbseed+$CODEchck;
                   6872: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6873: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6874: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6875: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6876: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6877: 	return "$num1:$num2";
                   6878:     }
                   6879: }
                   6880: 
1.675     albertel 6881: sub rndseed_CODE_64bit5 {
                   6882:     my ($symb,$courseid,$domain,$username)=@_;
                   6883:     my $code = &getCODE();
                   6884:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6885:     return "$num1:$num2";
                   6886: }
                   6887: 
1.366     albertel 6888: sub setup_random_from_rndseed {
                   6889:     my ($rndseed)=@_;
1.503     albertel 6890:     if ($rndseed =~/([,:])/) {
                   6891: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6892: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6893:     } else {
                   6894: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6895:     }
1.36      albertel 6896: }
                   6897: 
1.474     albertel 6898: sub latest_receipt_algorithm_id {
                   6899:     return 'receipt2';
                   6900: }
                   6901: 
1.480     www      6902: sub recunique {
                   6903:     my $fucourseid=shift;
                   6904:     my $unique;
1.620     albertel 6905:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6906: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6907:     } else {
                   6908: 	$unique=$perlvar{'lonReceipt'};
                   6909:     }
                   6910:     return unpack("%32C*",$unique);
                   6911: }
                   6912: 
                   6913: sub recprefix {
                   6914:     my $fucourseid=shift;
                   6915:     my $prefix;
1.620     albertel 6916:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6917: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6918:     } else {
                   6919: 	$prefix=$perlvar{'lonHostID'};
                   6920:     }
                   6921:     return unpack("%32C*",$prefix);
                   6922: }
                   6923: 
1.76      www      6924: sub ireceipt {
1.474     albertel 6925:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6926:     my $cuname=unpack("%32C*",$funame);
                   6927:     my $cudom=unpack("%32C*",$fudom);
                   6928:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6929:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6930:     my $cunique=&recunique($fucourseid);
1.474     albertel 6931:     my $cpart=unpack("%32S*",$part);
1.480     www      6932:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6933:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6934: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6935: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6936: 			       
                   6937: 	$return.= ($cunique%$cuname+
                   6938: 		   $cunique%$cudom+
                   6939: 		   $cusymb%$cuname+
                   6940: 		   $cusymb%$cudom+
                   6941: 		   $cucourseid%$cuname+
                   6942: 		   $cucourseid%$cudom+
                   6943: 		   $cpart%$cuname+
                   6944: 		   $cpart%$cudom);
                   6945:     } else {
                   6946: 	$return.= ($cunique%$cuname+
                   6947: 		   $cunique%$cudom+
                   6948: 		   $cusymb%$cuname+
                   6949: 		   $cusymb%$cudom+
                   6950: 		   $cucourseid%$cuname+
                   6951: 		   $cucourseid%$cudom);
                   6952:     }
                   6953:     return $return;
1.76      www      6954: }
                   6955: 
                   6956: sub receipt {
1.474     albertel 6957:     my ($part)=@_;
1.790     albertel 6958:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6959:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6960: }
1.260     ng       6961: 
1.790     albertel 6962: sub whichuser {
                   6963:     my ($passedsymb)=@_;
                   6964:     my ($symb,$courseid,$domain,$name,$publicuser);
                   6965:     if (defined($env{'form.grade_symb'})) {
                   6966: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   6967: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   6968: 	if (!$allowed &&
                   6969: 	    exists($env{'request.course.sec'}) &&
                   6970: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   6971: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   6972: 			      '/'.$env{'request.course.sec'});
                   6973: 	}
                   6974: 	if ($allowed) {
                   6975: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   6976: 	    $courseid=$tmp_courseid;
                   6977: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   6978: 	    ($name)=&get_env_multiple('form.grade_username');
                   6979: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   6980: 	}
                   6981:     }
                   6982:     if (!$passedsymb) {
                   6983: 	$symb=&symbread();
                   6984:     } else {
                   6985: 	$symb=$passedsymb;
                   6986:     }
                   6987:     $courseid=$env{'request.course.id'};
                   6988:     $domain=$env{'user.domain'};
                   6989:     $name=$env{'user.name'};
                   6990:     if ($name eq 'public' && $domain eq 'public') {
                   6991: 	if (!defined($env{'form.username'})) {
                   6992: 	    $env{'form.username'}.=time.rand(10000000);
                   6993: 	}
                   6994: 	$name.=$env{'form.username'};
                   6995:     }
                   6996:     return ($symb,$courseid,$domain,$name,$publicuser);
                   6997: 
                   6998: }
                   6999: 
1.36      albertel 7000: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7001: # returns either the contents of the file or 
                   7002: # -1 if the file doesn't exist
1.481     raeburn  7003: #
                   7004: # if the target is a file that was uploaded via DOCS, 
                   7005: # a check will be made to see if a current copy exists on the local server,
                   7006: # if it does this will be served, otherwise a copy will be retrieved from
                   7007: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7008: # the local server.   
1.472     albertel 7009: 
1.36      albertel 7010: sub getfile {
1.538     albertel 7011:     my ($file) = @_;
1.609     banghart 7012:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7013:     &repcopy($file);
                   7014:     return &readfile($file);
                   7015: }
                   7016: 
                   7017: sub repcopy_userfile {
                   7018:     my ($file)=@_;
1.609     banghart 7019:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7020:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7021:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7022: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7023:     my ($info,$rtncode);
                   7024:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7025:     if (-e "$file") {
                   7026: 	my @fileinfo = stat($file);
                   7027: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7028: 	if ($lwpresp ne 'ok') {
                   7029: 	    if ($rtncode eq '404') {
1.538     albertel 7030: 		unlink($file);
1.482     albertel 7031: 	    }
1.517     albertel 7032: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7033: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7034: 	    #my $response=$ua->request($request);
                   7035: 	    #if ($response->is_success()) {
                   7036: 	#	return $response->content;
                   7037: 	#    } else {
                   7038: 	#	return -1;
                   7039: 	#    }
1.482     albertel 7040: 	    return -1;
                   7041: 	}
                   7042: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7043: 	    return 'ok';
1.482     albertel 7044: 	}
                   7045: 	$info = '';
1.538     albertel 7046: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7047: 	if ($lwpresp ne 'ok') {
                   7048: 	    return -1;
                   7049: 	}
                   7050:     } else {
1.538     albertel 7051: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7052: 	if ($lwpresp ne 'ok') {
1.517     albertel 7053: 	    my $ua=new LWP::UserAgent;
1.538     albertel 7054: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7055: 	    my $response=$ua->request($request);
                   7056: 	    if ($response->is_success()) {
1.538     albertel 7057: 		$info=$response->content;
1.517     albertel 7058: 	    } else {
                   7059: 		return -1;
                   7060: 	    }
1.482     albertel 7061: 	}
                   7062: 	my @parts = ($cdom,$cnum); 
                   7063: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7064: 	    push @parts, split(/\//,$1);
1.518     albertel 7065: 	}
1.538     albertel 7066: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7067: 	foreach my $part (@parts) {
                   7068: 	    $path .= '/'.$part;
                   7069: 	    if (!-e $path) {
                   7070: 		mkdir($path,0770);
                   7071: 	    }
                   7072: 	}
                   7073:     }
1.538     albertel 7074:     open(FILE,">$file");
1.482     albertel 7075:     print FILE $info;
                   7076:     close(FILE);
1.607     raeburn  7077:     return 'ok';
1.481     raeburn  7078: }
                   7079: 
1.517     albertel 7080: sub tokenwrapper {
                   7081:     my $uri=shift;
1.552     albertel 7082:     $uri=~s|^http\://([^/]+)||;
                   7083:     $uri=~s|^/||;
1.620     albertel 7084:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7085:     my $token=$1;
1.552     albertel 7086:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7087:     if ($udom && $uname && $file) {
                   7088: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7089:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7090:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7091:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7092:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7093:     } else {
                   7094:         return '/adm/notfound.html';
                   7095:     }
                   7096: }
                   7097: 
1.481     raeburn  7098: sub getuploaded {
                   7099:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7100:     $uri=~s/^\///;
                   7101:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7102:     my $ua=new LWP::UserAgent;
                   7103:     my $request=new HTTP::Request($reqtype,$uri);
                   7104:     my $response=$ua->request($request);
                   7105:     $$rtncode = $response->code;
1.482     albertel 7106:     if (! $response->is_success()) {
                   7107: 	return 'failed';
                   7108:     }      
                   7109:     if ($reqtype eq 'HEAD') {
1.486     www      7110: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7111:     } elsif ($reqtype eq 'GET') {
                   7112: 	$$info = $response->content;
1.472     albertel 7113:     }
1.482     albertel 7114:     return 'ok';
1.36      albertel 7115: }
                   7116: 
1.481     raeburn  7117: sub readfile {
                   7118:     my $file = shift;
                   7119:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7120:     my $fh;
                   7121:     open($fh,"<$file");
                   7122:     my $a='';
1.800     albertel 7123:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7124:     return $a;
                   7125: }
                   7126: 
1.36      albertel 7127: sub filelocation {
1.590     banghart 7128:     my ($dir,$file) = @_;
                   7129:     my $location;
                   7130:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7131: 
                   7132:     if ($file =~ m-^/adm/-) {
                   7133: 	$file=~s-^/adm/wrapper/-/-;
                   7134: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7135:     }
1.590     banghart 7136:     if ($file=~m:^/~:) { # is a contruction space reference
                   7137:         $location = $file;
                   7138:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7139:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7140: 	# is a correct contruction space reference
                   7141:         $location = $file;
1.609     banghart 7142:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7143:         my ($udom,$uname,$filename)=
1.811     albertel 7144:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7145:         my $home=&homeserver($uname,$udom);
                   7146:         my $is_me=0;
                   7147:         my @ids=&current_machine_ids();
                   7148:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7149:         if ($is_me) {
1.740     www      7150:   	    $location=&propath($udom,$uname).
1.590     banghart 7151:   	      '/userfiles/'.$filename;
                   7152:         } else {
                   7153:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7154:   	      $udom.'/'.$uname.'/'.$filename;
                   7155:         }
                   7156:     } else {
                   7157:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7158:         $file=~s:^/res/:/:;
                   7159:         if ( !( $file =~ m:^/:) ) {
                   7160:             $location = $dir. '/'.$file;
                   7161:         } else {
                   7162:             $location = '/home/httpd/html/res'.$file;
                   7163:         }
1.59      albertel 7164:     }
1.590     banghart 7165:     $location=~s://+:/:g; # remove duplicate /
                   7166:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7167:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7168:     return $location;
1.46      www      7169: }
1.36      albertel 7170: 
1.46      www      7171: sub hreflocation {
                   7172:     my ($dir,$file)=@_;
1.460     albertel 7173:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7174: 	$file=filelocation($dir,$file);
1.700     albertel 7175:     } elsif ($file=~m-^/adm/-) {
                   7176: 	$file=~s-^/adm/wrapper/-/-;
                   7177: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7178:     }
                   7179:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7180: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7181:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7182: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7183:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7184: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7185: 	    -/uploaded/$1/$2/-x;
1.46      www      7186:     }
1.462     albertel 7187:     return $file;
1.465     albertel 7188: }
                   7189: 
                   7190: sub current_machine_domains {
                   7191:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7192:     my @domains;
                   7193:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7194: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7195: 	if ($hostname eq $name) {
                   7196: 	    push(@domains,$hostdom{$id});
                   7197: 	}
                   7198:     }
                   7199:     return @domains;
                   7200: }
                   7201: 
                   7202: sub current_machine_ids {
                   7203:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7204:     my @ids;
                   7205:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7206: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7207: 	if ($hostname eq $name) {
                   7208: 	    push(@ids,$id);
                   7209: 	}
                   7210:     }
                   7211:     return @ids;
1.31      www      7212: }
                   7213: 
                   7214: # ------------------------------------------------------------- Declutters URLs
                   7215: 
                   7216: sub declutter {
                   7217:     my $thisfn=shift;
1.569     albertel 7218:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7219:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7220:     $thisfn=~s/^\///;
1.697     albertel 7221:     $thisfn=~s|^adm/wrapper/||;
                   7222:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7223:     $thisfn=~s/^res\///;
1.235     www      7224:     $thisfn=~s/\?.+$//;
1.268     www      7225:     return $thisfn;
                   7226: }
                   7227: 
                   7228: # ------------------------------------------------------------- Clutter up URLs
                   7229: 
                   7230: sub clutter {
                   7231:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7232:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7233:        $thisfn='/res'.$thisfn; 
                   7234:     }
1.694     albertel 7235:     if ($thisfn !~m|/adm|) {
1.695     albertel 7236: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7237: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7238: 	} else {
                   7239: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7240: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7241: 	    if ($embstyle eq 'ssi'
                   7242: 		|| ($embstyle eq 'hdn')
                   7243: 		|| ($embstyle eq 'rat')
                   7244: 		|| ($embstyle eq 'prv')
                   7245: 		|| ($embstyle eq 'ign')) {
                   7246: 		#do nothing with these
                   7247: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7248: 		|| ($embstyle eq 'emb')
                   7249: 		|| ($embstyle eq 'wrp')) {
                   7250: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7251: 	    } elsif ($embstyle eq 'unk'
                   7252: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7253: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7254: 	    } else {
1.718     www      7255: #		&logthis("Got a blank emb style");
1.695     albertel 7256: 	    }
1.694     albertel 7257: 	}
                   7258:     }
1.31      www      7259:     return $thisfn;
1.12      www      7260: }
                   7261: 
1.787     albertel 7262: sub clutter_with_no_wrapper {
                   7263:     my $uri = &clutter(shift);
                   7264:     if ($uri =~ m-^/adm/-) {
                   7265: 	$uri =~ s-^/adm/wrapper/-/-;
                   7266: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7267:     }
                   7268:     return $uri;
                   7269: }
                   7270: 
1.557     albertel 7271: sub freeze_escape {
                   7272:     my ($value)=@_;
                   7273:     if (ref($value)) {
                   7274: 	$value=&nfreeze($value);
                   7275: 	return '__FROZEN__'.&escape($value);
                   7276:     }
                   7277:     return &escape($value);
                   7278: }
                   7279: 
1.11      www      7280: 
1.557     albertel 7281: sub thaw_unescape {
                   7282:     my ($value)=@_;
                   7283:     if ($value =~ /^__FROZEN__/) {
                   7284: 	substr($value,0,10,undef);
                   7285: 	$value=&unescape($value);
                   7286: 	return &thaw($value);
                   7287:     }
                   7288:     return &unescape($value);
                   7289: }
                   7290: 
1.436     albertel 7291: sub correct_line_ends {
                   7292:     my ($result)=@_;
                   7293:     $$result =~s/\r\n/\n/mg;
                   7294:     $$result =~s/\r/\n/mg;
1.415     albertel 7295: }
1.1       albertel 7296: # ================================================================ Main Program
                   7297: 
1.184     www      7298: sub goodbye {
1.204     albertel 7299:    &logthis("Starting Shut down");
1.443     albertel 7300: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7301:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7302: #converted
1.599     albertel 7303: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7304:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7305: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7306: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7307: #1.1 only
1.599     albertel 7308: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7309: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7310: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7311: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7312:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7313:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7314:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7315:    &flushcourselogs();
                   7316:    &logthis("Shutting down");
                   7317: }
                   7318: 
1.179     www      7319: BEGIN {
1.228     harris41 7320: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7321:     unless ($readit) {
1.217     harris41 7322: {
1.781     raeburn  7323:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7324:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7325: }
1.1       albertel 7326: 
1.327     albertel 7327: # ------------------------------------------------------------ Read domain file
                   7328: {
                   7329:     %domaindescription = ();
                   7330:     %domain_auth_def = ();
                   7331:     %domain_auth_arg_def = ();
1.448     albertel 7332:     my $fh;
                   7333:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7334: 	while (my $line = <$fh>) {
                   7335:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7336: #           next if /^\#/;
1.801     foxr     7337:            chomp $line;
1.403     www      7338:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7339: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7340: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7341:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7342: 	   $domaindescription{$domain}=$domain_description;
                   7343: 	   $domain_lang_def{$domain}=$def_lang;
                   7344: 	   $domain_city{$domain}=$city;
                   7345: 	   $domain_longi{$domain}=$longi;
                   7346: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7347:            $domain_primary{$domain}=$primary;
1.403     www      7348: 
1.448     albertel 7349:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7350: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7351: 	}
1.327     albertel 7352:     }
1.448     albertel 7353:     close ($fh);
1.327     albertel 7354: }
                   7355: 
                   7356: 
1.1       albertel 7357: # ------------------------------------------------------------- Read hosts file
                   7358: {
1.448     albertel 7359:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7360: 
                   7361:     while (my $configline=<$config>) {
1.303     matthew  7362:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7363:        chomp($configline);
1.595     albertel 7364:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7365:        $name=~s/\s//g;
1.595     albertel 7366:        if ($id && $domain && $role && $name) {
1.252     albertel 7367: 	 $hostname{$id}=$name;
                   7368: 	 $hostdom{$id}=$domain;
                   7369: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7370:        }
1.1       albertel 7371:     }
1.448     albertel 7372:     close($config);
1.619     albertel 7373:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7374:     #&get_iphost();
1.1       albertel 7375: }
                   7376: 
1.598     albertel 7377: sub get_iphost {
                   7378:     if (%iphost) { return %iphost; }
1.653     albertel 7379:     my %name_to_ip;
1.598     albertel 7380:     foreach my $id (keys(%hostname)) {
                   7381: 	my $name=$hostname{$id};
1.653     albertel 7382: 	my $ip;
                   7383: 	if (!exists($name_to_ip{$name})) {
                   7384: 	    $ip = gethostbyname($name);
                   7385: 	    if (!$ip || length($ip) ne 4) {
                   7386: 		&logthis("Skipping host $id name $name no IP found\n");
                   7387: 		next;
                   7388: 	    }
                   7389: 	    $ip=inet_ntoa($ip);
                   7390: 	    $name_to_ip{$name} = $ip;
                   7391: 	} else {
                   7392: 	    $ip = $name_to_ip{$name};
1.598     albertel 7393: 	}
                   7394: 	push(@{$iphost{$ip}},$id);
                   7395:     }
                   7396:     return %iphost;
                   7397: }
                   7398: 
1.1       albertel 7399: # ------------------------------------------------------ Read spare server file
                   7400: {
1.448     albertel 7401:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7402: 
                   7403:     while (my $configline=<$config>) {
                   7404:        chomp($configline);
1.284     matthew  7405:        if ($configline) {
1.784     albertel 7406: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7407: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7408: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7409:        }
                   7410:     }
1.448     albertel 7411:     close($config);
1.1       albertel 7412: }
1.11      www      7413: # ------------------------------------------------------------ Read permissions
                   7414: {
1.448     albertel 7415:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7416: 
                   7417:     while (my $configline=<$config>) {
1.448     albertel 7418: 	chomp($configline);
                   7419: 	if ($configline) {
                   7420: 	    my ($role,$perm)=split(/ /,$configline);
                   7421: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7422: 	}
1.11      www      7423:     }
1.448     albertel 7424:     close($config);
1.11      www      7425: }
                   7426: 
                   7427: # -------------------------------------------- Read plain texts for permissions
                   7428: {
1.448     albertel 7429:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7430: 
                   7431:     while (my $configline=<$config>) {
1.448     albertel 7432: 	chomp($configline);
                   7433: 	if ($configline) {
1.742     raeburn  7434: 	    my ($short,@plain)=split(/:/,$configline);
                   7435:             %{$prp{$short}} = ();
                   7436: 	    if (@plain > 0) {
                   7437:                 $prp{$short}{'std'} = $plain[0];
                   7438:                 for (my $i=1; $i<@plain; $i++) {
                   7439:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7440:                 }
                   7441:             }
1.448     albertel 7442: 	}
1.135     www      7443:     }
1.448     albertel 7444:     close($config);
1.135     www      7445: }
                   7446: 
                   7447: # ---------------------------------------------------------- Read package table
                   7448: {
1.448     albertel 7449:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7450: 
                   7451:     while (my $configline=<$config>) {
1.483     albertel 7452: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7453: 	chomp($configline);
                   7454: 	my ($short,$plain)=split(/:/,$configline);
                   7455: 	my ($pack,$name)=split(/\&/,$short);
                   7456: 	if ($plain ne '') {
                   7457: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7458: 	    $packagetab{$short}=$plain; 
                   7459: 	}
1.11      www      7460:     }
1.448     albertel 7461:     close($config);
1.329     matthew  7462: }
                   7463: 
                   7464: # ------------- set up temporary directory
                   7465: {
                   7466:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7467: 
1.11      www      7468: }
                   7469: 
1.794     albertel 7470: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7471: 				'compress_threshold'=> 20_000,
                   7472:  			        });
1.185     www      7473: 
1.281     www      7474: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7475: $dumpcount=0;
1.22      www      7476: 
1.163     harris41 7477: &logtouch();
1.672     albertel 7478: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7479: $readit=1;
1.564     albertel 7480:     {
                   7481: 	use integer;
                   7482: 	my $test=(2**32)+1;
1.568     albertel 7483: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7484: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7485:     }
1.195     www      7486: }
1.1       albertel 7487: }
1.179     www      7488: 
1.1       albertel 7489: 1;
1.191     harris41 7490: __END__
                   7491: 
1.243     albertel 7492: =pod
                   7493: 
1.191     harris41 7494: =head1 NAME
                   7495: 
1.243     albertel 7496: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7497: 
                   7498: =head1 SYNOPSIS
                   7499: 
1.243     albertel 7500: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7501: 
                   7502:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7503: 
1.243     albertel 7504: Common parameters:
                   7505: 
                   7506: =over 4
                   7507: 
                   7508: =item *
                   7509: 
                   7510: $uname : an internal username (if $cname expecting a course Id specifically)
                   7511: 
                   7512: =item *
                   7513: 
                   7514: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7515: 
                   7516: =item *
                   7517: 
                   7518: $symb : a resource instance identifier
                   7519: 
                   7520: =item *
                   7521: 
                   7522: $namespace : the name of a .db file that contains the data needed or
                   7523: being set.
                   7524: 
                   7525: =back
                   7526: 
1.394     bowersj2 7527: =head1 OVERVIEW
1.191     harris41 7528: 
1.394     bowersj2 7529: lonnet provides subroutines which interact with the
                   7530: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7531: about classes, users, and resources.
1.243     albertel 7532: 
                   7533: For many of these objects you can also use this to store data about
                   7534: them or modify them in various ways.
1.191     harris41 7535: 
1.394     bowersj2 7536: =head2 Symbs
1.191     harris41 7537: 
1.394     bowersj2 7538: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7539: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7540: map, the resource number of the resource in the map, and the URL of
                   7541: the resource itself. The latter is somewhat redundant, but might help
                   7542: if maps change.
                   7543: 
                   7544: An example is
                   7545: 
                   7546:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7547: 
                   7548: The respective map entry is
                   7549: 
                   7550:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7551:   title="Problem 2">
                   7552:  </resource>
                   7553: 
                   7554: Symbs are used by the random number generator, as well as to store and
                   7555: restore data specific to a certain instance of for example a problem.
                   7556: 
                   7557: =head2 Storing And Retrieving Data
                   7558: 
                   7559: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7560: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7561: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7562: is is the non-critical message twin of cstore. These functions are for
                   7563: handlers to store a perl hash to a user's permanent data space in an
                   7564: easy manner, and to retrieve it again on another call. It is expected
                   7565: that a handler would use this once at the beginning to retrieve data,
                   7566: and then again once at the end to send only the new data back.
                   7567: 
                   7568: The data is stored in the user's data directory on the user's
                   7569: homeserver under the ID of the course.
                   7570: 
                   7571: The hash that is returned by restore will have all of the previous
                   7572: value for all of the elements of the hash.
                   7573: 
                   7574: Example:
                   7575: 
                   7576:  #creating a hash
                   7577:  my %hash;
                   7578:  $hash{'foo'}='bar';
                   7579: 
                   7580:  #storing it
                   7581:  &Apache::lonnet::cstore(\%hash);
                   7582: 
                   7583:  #changing a value
                   7584:  $hash{'foo'}='notbar';
                   7585: 
                   7586:  #adding a new value
                   7587:  $hash{'bar'}='foo';
                   7588:  &Apache::lonnet::cstore(\%hash);
                   7589: 
                   7590:  #retrieving the hash
                   7591:  my %history=&Apache::lonnet::restore();
                   7592: 
                   7593:  #print the hash
                   7594:  foreach my $key (sort(keys(%history))) {
                   7595:    print("\%history{$key} = $history{$key}");
                   7596:  }
                   7597: 
                   7598: Will print out:
1.191     harris41 7599: 
1.394     bowersj2 7600:  %history{1:foo} = bar
                   7601:  %history{1:keys} = foo:timestamp
                   7602:  %history{1:timestamp} = 990455579
                   7603:  %history{2:bar} = foo
                   7604:  %history{2:foo} = notbar
                   7605:  %history{2:keys} = foo:bar:timestamp
                   7606:  %history{2:timestamp} = 990455580
                   7607:  %history{bar} = foo
                   7608:  %history{foo} = notbar
                   7609:  %history{timestamp} = 990455580
                   7610:  %history{version} = 2
                   7611: 
                   7612: Note that the special hash entries C<keys>, C<version> and
                   7613: C<timestamp> were added to the hash. C<version> will be equal to the
                   7614: total number of versions of the data that have been stored. The
                   7615: C<timestamp> attribute will be the UNIX time the hash was
                   7616: stored. C<keys> is available in every historical section to list which
                   7617: keys were added or changed at a specific historical revision of a
                   7618: hash.
                   7619: 
                   7620: B<Warning>: do not store the hash that restore returns directly. This
                   7621: will cause a mess since it will restore the historical keys as if the
                   7622: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7623: 
1.394     bowersj2 7624: Calling convention:
1.191     harris41 7625: 
1.394     bowersj2 7626:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7627:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7628: 
1.394     bowersj2 7629: For more detailed information, see lonnet specific documentation.
1.191     harris41 7630: 
1.394     bowersj2 7631: =head1 RETURN MESSAGES
1.191     harris41 7632: 
1.394     bowersj2 7633: =over 4
1.191     harris41 7634: 
1.394     bowersj2 7635: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7636: 
1.394     bowersj2 7637: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7638: when the connection is brought back up
1.191     harris41 7639: 
1.394     bowersj2 7640: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7641: for later delivery
1.191     harris41 7642: 
1.394     bowersj2 7643: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7644: 
1.394     bowersj2 7645: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7646: that was requested
1.191     harris41 7647: 
1.243     albertel 7648: =back
1.191     harris41 7649: 
1.243     albertel 7650: =head1 PUBLIC SUBROUTINES
1.191     harris41 7651: 
1.243     albertel 7652: =head2 Session Environment Functions
1.191     harris41 7653: 
1.243     albertel 7654: =over 4
1.191     harris41 7655: 
1.394     bowersj2 7656: =item * 
                   7657: X<appenv()>
                   7658: B<appenv(%hash)>: the value of %hash is written to
                   7659: the user envirnoment file, and will be restored for each access this
1.620     albertel 7660: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7661: process
1.191     harris41 7662: 
                   7663: =item *
1.394     bowersj2 7664: X<delenv()>
                   7665: B<delenv($regexp)>: removes all items from the session
                   7666: environment file that matches the regular expression in $regexp. The
1.620     albertel 7667: values are also delted from the current processes %env.
1.191     harris41 7668: 
1.795     albertel 7669: =item * get_env_multiple($name) 
                   7670: 
                   7671: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7672: values may be defined and end up as an array ref.
                   7673: 
                   7674: returns an array of values
                   7675: 
1.243     albertel 7676: =back
                   7677: 
                   7678: =head2 User Information
1.191     harris41 7679: 
1.243     albertel 7680: =over 4
1.191     harris41 7681: 
                   7682: =item *
1.394     bowersj2 7683: X<queryauthenticate()>
                   7684: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7685: authentication scheme
                   7686: 
                   7687: =item *
1.394     bowersj2 7688: X<authenticate()>
                   7689: B<authenticate($uname,$upass,$udom)>: try to
                   7690: authenticate user from domain's lib servers (first use the current
                   7691: one). C<$upass> should be the users password.
1.191     harris41 7692: 
                   7693: =item *
1.394     bowersj2 7694: X<homeserver()>
                   7695: B<homeserver($uname,$udom)>: find the server which has
                   7696: the user's directory and files (there must be only one), this caches
                   7697: the answer, and also caches if there is a borken connection.
1.191     harris41 7698: 
                   7699: =item *
1.394     bowersj2 7700: X<idget()>
                   7701: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7702: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7703: username, and only 1 username per ID in a specific domain) (returns
                   7704: hash: id=>name,id=>name)
1.191     harris41 7705: 
                   7706: =item *
1.394     bowersj2 7707: X<idrget()>
                   7708: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7709: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7710: 
                   7711: =item *
1.394     bowersj2 7712: X<idput()>
                   7713: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7714: 
                   7715: =item *
1.394     bowersj2 7716: X<rolesinit()>
                   7717: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7718: 
                   7719: =item *
1.551     albertel 7720: X<getsection()>
                   7721: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7722: course $cname, return section name/number or '' for "not in course"
                   7723: and '-1' for "no section"
                   7724: 
                   7725: =item *
1.394     bowersj2 7726: X<userenvironment()>
                   7727: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7728: passed in @what from the requested user's environment, returns a hash
                   7729: 
                   7730: =back
                   7731: 
                   7732: =head2 User Roles
                   7733: 
                   7734: =over 4
                   7735: 
                   7736: =item *
                   7737: 
1.810     raeburn  7738: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7739:  F: full access
                   7740:  U,I,K: authentication modes (cxx only)
                   7741:  '': forbidden
                   7742:  1: user needs to choose course
                   7743:  2: browse allowed
1.766     albertel 7744:  A: passphrase authentication needed
1.243     albertel 7745: 
                   7746: =item *
                   7747: 
                   7748: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7749: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7750: and course level
                   7751: 
                   7752: =item *
                   7753: 
                   7754: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7755: explanation of a user role term
                   7756: 
                   7757: =back
                   7758: 
                   7759: =head2 User Modification
                   7760: 
                   7761: =over 4
                   7762: 
                   7763: =item *
                   7764: 
                   7765: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7766: user for the level given by URL.  Optional start and end dates (leave empty
                   7767: string or zero for "no date")
1.191     harris41 7768: 
                   7769: =item *
                   7770: 
1.243     albertel 7771: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7772: change a users, password, possible return values are: ok,
                   7773: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7774: refused
1.191     harris41 7775: 
                   7776: =item *
                   7777: 
1.243     albertel 7778: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7779: 
                   7780: =item *
                   7781: 
1.243     albertel 7782: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7783: modify user
1.191     harris41 7784: 
                   7785: =item *
                   7786: 
1.286     matthew  7787: modifystudent
                   7788: 
                   7789: modify a students enrollment and identification information.
                   7790: The course id is resolved based on the current users environment.  
                   7791: This means the envoking user must be a course coordinator or otherwise
                   7792: associated with a course.
                   7793: 
1.297     matthew  7794: This call is essentially a wrapper for lonnet::modifyuser and
                   7795: lonnet::modify_student_enrollment
1.286     matthew  7796: 
                   7797: Inputs: 
                   7798: 
                   7799: =over 4
                   7800: 
                   7801: =item B<$udom> Students loncapa domain
                   7802: 
                   7803: =item B<$uname> Students loncapa login name
                   7804: 
                   7805: =item B<$uid> Students id/student number
                   7806: 
                   7807: =item B<$umode> Students authentication mode
                   7808: 
                   7809: =item B<$upass> Students password
                   7810: 
                   7811: =item B<$first> Students first name
                   7812: 
                   7813: =item B<$middle> Students middle name
                   7814: 
                   7815: =item B<$last> Students last name
                   7816: 
                   7817: =item B<$gene> Students generation
                   7818: 
                   7819: =item B<$usec> Students section in course
                   7820: 
                   7821: =item B<$end> Unix time of the roles expiration
                   7822: 
                   7823: =item B<$start> Unix time of the roles start date
                   7824: 
                   7825: =item B<$forceid> If defined, allow $uid to be changed
                   7826: 
                   7827: =item B<$desiredhome> server to use as home server for student
                   7828: 
                   7829: =back
1.297     matthew  7830: 
                   7831: =item *
                   7832: 
                   7833: modify_student_enrollment
                   7834: 
                   7835: Change a students enrollment status in a class.  The environment variable
                   7836: 'role.request.course' must be defined for this function to proceed.
                   7837: 
                   7838: Inputs:
                   7839: 
                   7840: =over 4
                   7841: 
                   7842: =item $udom, students domain
                   7843: 
                   7844: =item $uname, students name
                   7845: 
                   7846: =item $uid, students user id
                   7847: 
                   7848: =item $first, students first name
                   7849: 
                   7850: =item $middle
                   7851: 
                   7852: =item $last
                   7853: 
                   7854: =item $gene
                   7855: 
                   7856: =item $usec
                   7857: 
                   7858: =item $end
                   7859: 
                   7860: =item $start
                   7861: 
                   7862: =back
                   7863: 
1.191     harris41 7864: 
                   7865: =item *
                   7866: 
1.243     albertel 7867: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7868: custom role; give a custom role to a user for the level given by URL.  Specify
                   7869: name and domain of role author, and role name
1.191     harris41 7870: 
                   7871: =item *
                   7872: 
1.243     albertel 7873: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7874: 
                   7875: =item *
                   7876: 
1.243     albertel 7877: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7878: 
                   7879: =back
                   7880: 
                   7881: =head2 Course Infomation
                   7882: 
                   7883: =over 4
1.191     harris41 7884: 
                   7885: =item *
                   7886: 
1.631     albertel 7887: coursedescription($courseid) : returns a hash of information about the
                   7888: specified course id, including all environment settings for the
                   7889: course, the description of the course will be in the hash under the
                   7890: key 'description'
1.191     harris41 7891: 
                   7892: =item *
                   7893: 
1.624     albertel 7894: resdata($name,$domain,$type,@which) : request for current parameter
                   7895: setting for a specific $type, where $type is either 'course' or 'user',
                   7896: @what should be a list of parameters to ask about. This routine caches
                   7897: answers for 5 minutes.
1.243     albertel 7898: 
                   7899: =back
                   7900: 
                   7901: =head2 Course Modification
                   7902: 
                   7903: =over 4
1.191     harris41 7904: 
                   7905: =item *
                   7906: 
1.243     albertel 7907: writecoursepref($courseid,%prefs) : write preferences (environment
                   7908: database) for a course
1.191     harris41 7909: 
                   7910: =item *
                   7911: 
1.243     albertel 7912: createcourse($udom,$description,$url) : make/modify course
                   7913: 
                   7914: =back
                   7915: 
                   7916: =head2 Resource Subroutines
                   7917: 
                   7918: =over 4
1.191     harris41 7919: 
                   7920: =item *
                   7921: 
1.243     albertel 7922: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7923: 
                   7924: =item *
                   7925: 
1.243     albertel 7926: repcopy($filename) : subscribes to the requested file, and attempts to
                   7927: replicate from the owning library server, Might return
1.607     raeburn  7928: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7929: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7930: resource. Expects the local filesystem pathname
                   7931: (/home/httpd/html/res/....)
                   7932: 
                   7933: =back
                   7934: 
                   7935: =head2 Resource Information
                   7936: 
                   7937: =over 4
1.191     harris41 7938: 
                   7939: =item *
                   7940: 
1.243     albertel 7941: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7942: a vairety of different possible values, $varname should be a request
                   7943: string, and the other parameters can be used to specify who and what
                   7944: one is asking about.
                   7945: 
                   7946: Possible values for $varname are environment.lastname (or other item
                   7947: from the envirnment hash), user.name (or someother aspect about the
                   7948: user), resource.0.maxtries (or some other part and parameter of a
                   7949: resource)
1.204     albertel 7950: 
                   7951: =item *
                   7952: 
1.243     albertel 7953: directcondval($number) : get current value of a condition; reads from a state
                   7954: string
1.204     albertel 7955: 
                   7956: =item *
                   7957: 
1.243     albertel 7958: condval($condidx) : value of condition index based on state
1.204     albertel 7959: 
                   7960: =item *
                   7961: 
1.243     albertel 7962: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7963: resource's metadata, $what should be either a specific key, or either
                   7964: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7965: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7966: 
                   7967: this function automatically caches all requests
1.191     harris41 7968: 
                   7969: =item *
                   7970: 
1.243     albertel 7971: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7972: network of library servers; returns file handle of where SQL and regex results
                   7973: will be stored for query
1.191     harris41 7974: 
                   7975: =item *
                   7976: 
1.243     albertel 7977: symbread($filename) : return symbolic list entry (filename argument optional);
                   7978: returns the data handle
1.191     harris41 7979: 
                   7980: =item *
                   7981: 
1.243     albertel 7982: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7983: a possible symb for the URL in $thisfn, and if is an encryypted
                   7984: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7985: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7986: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7987: 
1.191     harris41 7988: 
                   7989: =item *
                   7990: 
1.243     albertel 7991: symbclean($symb) : removes versions numbers from a symb, returns the
                   7992: cleaned symb
1.191     harris41 7993: 
                   7994: =item *
                   7995: 
1.243     albertel 7996: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7997: course map, user must be in a course for it to work.
1.191     harris41 7998: 
                   7999: =item *
                   8000: 
1.243     albertel 8001: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8002: 
                   8003: =item *
                   8004: 
1.243     albertel 8005: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8006: a random seed, all arguments are optional, if they aren't sent it uses the
                   8007: environment to derive them. Note: if symb isn't sent and it can't get one
                   8008: from &symbread it will use the current time as its return value
1.191     harris41 8009: 
                   8010: =item *
                   8011: 
1.243     albertel 8012: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8013: unfakeable, receipt
1.191     harris41 8014: 
                   8015: =item *
                   8016: 
1.620     albertel 8017: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8018: 
                   8019: =item *
                   8020: 
1.243     albertel 8021: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8022: 
                   8023: =item *
                   8024: 
1.243     albertel 8025: 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 8026: 
                   8027: =item *
                   8028: 
1.243     albertel 8029: 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 8030: 
                   8031: =item *
                   8032: 
1.243     albertel 8033: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8034: 
                   8035: =item *
                   8036: 
1.243     albertel 8037: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8038: forcing spreadsheet to reevaluate the resource scores next time.
                   8039: 
                   8040: =back
                   8041: 
                   8042: =head2 Storing/Retreiving Data
                   8043: 
                   8044: =over 4
1.191     harris41 8045: 
                   8046: =item *
                   8047: 
1.243     albertel 8048: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8049: for this url; hashref needs to be given and should be a \%hashname; the
                   8050: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8051: be derived from the env
1.191     harris41 8052: 
                   8053: =item *
                   8054: 
1.243     albertel 8055: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8056: uses critical subroutine
1.191     harris41 8057: 
                   8058: =item *
                   8059: 
1.243     albertel 8060: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8061: all args are optional
1.191     harris41 8062: 
                   8063: =item *
                   8064: 
1.717     albertel 8065: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8066: dumps the complete (or key matching regexp) namespace into a hash
                   8067: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8068: normally &store()ed into
                   8069: 
                   8070: $range should be either an integer '100' (give me the first 100
                   8071:                                            matching records)
                   8072:               or be  two integers sperated by a - with no spaces
                   8073:                  '30-50' (give me the 30th through the 50th matching
                   8074:                           records)
                   8075: 
                   8076: 
                   8077: =item *
                   8078: 
                   8079: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8080: replaces a &store() version of data with a replacement set of data
                   8081: for a particular resource in a namespace passed in the $storehash hash 
                   8082: reference
                   8083: 
                   8084: =item *
                   8085: 
1.243     albertel 8086: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8087: works very similar to store/cstore, but all data is stored in a
                   8088: temporary location and can be reset using tmpreset, $storehash should
                   8089: be a hash reference, returns nothing on success
1.191     harris41 8090: 
                   8091: =item *
                   8092: 
1.243     albertel 8093: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8094: similar to restore, but all data is stored in a temporary location and
                   8095: can be reset using tmpreset. Returns a hash of values on success,
                   8096: error string otherwise.
1.191     harris41 8097: 
                   8098: =item *
                   8099: 
1.243     albertel 8100: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8101: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8102: 
                   8103: =item *
                   8104: 
1.243     albertel 8105: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8106: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8107: 
                   8108: =item *
                   8109: 
1.243     albertel 8110: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8111: namesp ($udom and $uname are optional)
1.191     harris41 8112: 
                   8113: =item *
                   8114: 
1.702     albertel 8115: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8116: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8117: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8118: 
1.702     albertel 8119: $range should be either an integer '100' (give me the first 100
                   8120:                                            matching records)
                   8121:               or be  two integers sperated by a - with no spaces
                   8122:                  '30-50' (give me the 30th through the 50th matching
                   8123:                           records)
1.449     matthew  8124: =item *
                   8125: 
                   8126: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8127: $store can be a scalar, an array reference, or if the amount to be 
                   8128: incremented is > 1, a hash reference.
                   8129: 
                   8130: ($udom and $uname are optional)
1.191     harris41 8131: 
                   8132: =item *
                   8133: 
1.243     albertel 8134: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8135: ($udom and $uname are optional)
1.191     harris41 8136: 
                   8137: =item *
                   8138: 
1.243     albertel 8139: cput($namespace,$storehash,$udom,$uname) : critical put
                   8140: ($udom and $uname are optional)
1.191     harris41 8141: 
                   8142: =item *
                   8143: 
1.748     albertel 8144: newput($namespace,$storehash,$udom,$uname) :
                   8145: 
                   8146: Attempts to store the items in the $storehash, but only if they don't
                   8147: currently exist, if this succeeds you can be certain that you have 
                   8148: successfully created a new key value pair in the $namespace db.
                   8149: 
                   8150: 
                   8151: Args:
                   8152:  $namespace: name of database to store values to
                   8153:  $storehash: hashref to store to the db
                   8154:  $udom: (optional) domain of user containing the db
                   8155:  $uname: (optional) name of user caontaining the db
                   8156: 
                   8157: Returns:
                   8158:  'ok' -> succeeded in storing all keys of $storehash
                   8159:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8160:                         least <key> already existed in the db (other
                   8161:                         requested keys may also already exist)
                   8162:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8163:  'con_lost' -> unable to contact request server
                   8164:  'refused' -> action was not allowed by remote machine
                   8165: 
                   8166: 
                   8167: =item *
                   8168: 
1.243     albertel 8169: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8170: reference filled in from namesp (encrypts the return communication)
                   8171: ($udom and $uname are optional)
1.191     harris41 8172: 
                   8173: =item *
                   8174: 
1.243     albertel 8175: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8176: critical subroutine
                   8177: 
1.806     raeburn  8178: =item *
                   8179: 
                   8180: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8181: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8182: 
                   8183: =item *
                   8184: 
                   8185: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8186: 
1.243     albertel 8187: =back
                   8188: 
                   8189: =head2 Network Status Functions
                   8190: 
                   8191: =over 4
1.191     harris41 8192: 
                   8193: =item *
                   8194: 
                   8195: dirlist($uri) : return directory list based on URI
                   8196: 
                   8197: =item *
                   8198: 
1.243     albertel 8199: spareserver() : find server with least workload from spare.tab
                   8200: 
                   8201: =back
                   8202: 
                   8203: =head2 Apache Request
                   8204: 
                   8205: =over 4
1.191     harris41 8206: 
                   8207: =item *
                   8208: 
1.243     albertel 8209: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8210: localhost, posts hash
                   8211: 
                   8212: =back
                   8213: 
                   8214: =head2 Data to String to Data
                   8215: 
                   8216: =over 4
1.191     harris41 8217: 
                   8218: =item *
                   8219: 
1.243     albertel 8220: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8221: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8222: 
                   8223: =item *
                   8224: 
1.243     albertel 8225: hashref2str($hashref) : convert a hashref into a string complete with
                   8226: escaping and '=' and '&' separators, supports elements that are
                   8227: arrayrefs and hashrefs
1.191     harris41 8228: 
                   8229: =item *
                   8230: 
1.243     albertel 8231: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8232: with escaping and '&' separators, supports elements that are arrayrefs
                   8233: and hashrefs
1.191     harris41 8234: 
                   8235: =item *
                   8236: 
1.243     albertel 8237: str2hash($string) : convert string to hash using unescaping and
                   8238: splitting on '=' and '&', supports elements that are arrayrefs and
                   8239: hashrefs
1.191     harris41 8240: 
                   8241: =item *
                   8242: 
1.243     albertel 8243: str2array($string) : convert string to hash using unescaping and
                   8244: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8245: 
                   8246: =back
                   8247: 
                   8248: =head2 Logging Routines
                   8249: 
                   8250: =over 4
                   8251: 
                   8252: These routines allow one to make log messages in the lonnet.log and
                   8253: lonnet.perm logfiles.
1.191     harris41 8254: 
                   8255: =item *
                   8256: 
1.243     albertel 8257: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8258: 
                   8259: =item *
                   8260: 
1.243     albertel 8261: logthis() : append message to the normal lonnet.log file, it gets
                   8262: preiodically rolled over and deleted.
1.191     harris41 8263: 
                   8264: =item *
                   8265: 
1.243     albertel 8266: logperm() : append a permanent message to lonnet.perm.log, this log
                   8267: file never gets deleted by any automated portion of the system, only
                   8268: messages of critical importance should go in here.
                   8269: 
                   8270: =back
                   8271: 
                   8272: =head2 General File Helper Routines
                   8273: 
                   8274: =over 4
1.191     harris41 8275: 
                   8276: =item *
                   8277: 
1.481     raeburn  8278: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8279: (a) files in /uploaded
                   8280:   (i) If a local copy of the file exists - 
                   8281:       compares modification date of local copy with last-modified date for 
                   8282:       definitive version stored on home server for course. If local copy is 
                   8283:       stale, requests a new version from the home server and stores it. 
                   8284:       If the original has been removed from the home server, then local copy 
                   8285:       is unlinked.
                   8286:   (ii) If local copy does not exist -
                   8287:       requests the file from the home server and stores it. 
                   8288:   
                   8289:   If $caller is 'uploadrep':  
                   8290:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8291:     for request for files originally uploaded via DOCS. 
                   8292:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8293:   
                   8294:   Otherwise:
                   8295:      This indicates a call from the content generation phase of the request.
                   8296:      -  returns the entire contents of the file or -1.
                   8297:      
                   8298: (b) files in /res
                   8299:    - returns the entire contents of a file or -1; 
                   8300:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8301: 
1.712     albertel 8302: 
                   8303: =item *
                   8304: 
                   8305: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8306:                   reference
                   8307: 
                   8308: returns either a stat() list of data about the file or an empty list
                   8309: if the file doesn't exist or couldn't find out about it (connection
                   8310: problems or user unknown)
                   8311: 
1.191     harris41 8312: =item *
                   8313: 
1.243     albertel 8314: filelocation($dir,$file) : returns file system location of a file
                   8315: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8316: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8317: and a file of ../bob will become /a/bob)
1.191     harris41 8318: 
                   8319: =item *
                   8320: 
                   8321: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8322: filelocation except for hrefs
                   8323: 
                   8324: =item *
                   8325: 
                   8326: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8327: 
1.243     albertel 8328: =back
                   8329: 
1.608     albertel 8330: =head2 Usererfile file routines (/uploaded*)
                   8331: 
                   8332: =over 4
                   8333: 
                   8334: =item *
                   8335: 
                   8336: userfileupload(): main rotine for putting a file in a user or course's
                   8337:                   filespace, arguments are,
                   8338: 
1.620     albertel 8339:  formname - required - this is the name of the element in $env where the
1.608     albertel 8340:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8341:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8342:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8343:  coursedoc - if true, store the file in the course of the active role
                   8344:              of the current user
                   8345:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8346:          if undefined, it will be placed in "unknown"
                   8347: 
                   8348:  (This routine calls clean_filename() to remove any dangerous
                   8349:  characters from the filename, and then calls finuserfileupload() to
                   8350:  complete the transaction)
                   8351: 
                   8352:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8353:  and /adm/notfound.html if unsuccessful
                   8354: 
                   8355: =item *
                   8356: 
                   8357: clean_filename(): routine for cleaing a filename up for storage in
                   8358:                  userfile space, argument is:
                   8359: 
                   8360:  filename - proposed filename
                   8361: 
                   8362: returns: the new clean filename
                   8363: 
                   8364: =item *
                   8365: 
                   8366: finishuserfileupload(): routine that creaes and sends the file to
                   8367: userspace, probably shouldn't be called directly
                   8368: 
                   8369:   docuname: username or courseid of destination for the file
                   8370:   docudom: domain of user/course of destination for the file
                   8371:   formname: same as for userfileupload()
                   8372:   fname: filename (inculding subdirectories) for the file
                   8373: 
                   8374:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8375:  and /adm/notfound.html if unsuccessful
                   8376: 
                   8377: =item *
                   8378: 
                   8379: renameuserfile(): renames an existing userfile to a new name
                   8380: 
                   8381:   Args:
                   8382:    docuname: username or courseid of destination for the file
                   8383:    docudom: domain of user/course of destination for the file
                   8384:    old: current file name (including any subdirs under userfiles)
                   8385:    new: desired file name (including any subdirs under userfiles)
                   8386: 
                   8387: =item *
                   8388: 
                   8389: mkdiruserfile(): creates a directory is a userfiles dir
                   8390: 
                   8391:   Args:
                   8392:    docuname: username or courseid of destination for the file
                   8393:    docudom: domain of user/course of destination for the file
                   8394:    dir: dir to create (including any subdirs under userfiles)
                   8395: 
                   8396: =item *
                   8397: 
                   8398: removeuserfile(): removes a file that exists in userfiles
                   8399: 
                   8400:   Args:
                   8401:    docuname: username or courseid of destination for the file
                   8402:    docudom: domain of user/course of destination for the file
                   8403:    fname: filname to delete (including any subdirs under userfiles)
                   8404: 
                   8405: =item *
                   8406: 
                   8407: removeuploadedurl(): convience function for removeuserfile()
                   8408: 
                   8409:   Args:
                   8410:    url:  a full /uploaded/... url to delete
                   8411: 
1.747     albertel 8412: =item * 
                   8413: 
                   8414: get_portfile_permissions():
                   8415:   Args:
                   8416:     domain: domain of user or course contain the portfolio files
                   8417:     user: name of user or num of course contain the portfolio files
                   8418:   Returns:
                   8419:     hashref of a dump of the proper file_permissions.db
                   8420:    
                   8421: 
                   8422: =item * 
                   8423: 
                   8424: get_access_controls():
                   8425: 
                   8426: Args:
                   8427:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8428:   group: (optional) the group you want the files associated with
                   8429:   file: (optional) the file you want access info on
                   8430: 
                   8431: Returns:
1.749     raeburn  8432:     a hash (keys are file names) of hashes containing
                   8433:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8434:         values are XML containing access control settings (see below) 
1.747     albertel 8435: 
                   8436: Internal notes:
                   8437: 
1.749     raeburn  8438:  access controls are stored in file_permissions.db as key=value pairs.
                   8439:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8440:         where scope -> public,guest,course,group,domains or users.
                   8441:               end -> UNIX time for end of access (0 -> no end date)
                   8442:               start -> UNIX time for start of access
                   8443: 
                   8444:     value -> XML description of access control
                   8445:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8446:             <start></start>
                   8447:             <end></end>
                   8448: 
                   8449:             <password></password>  for scope type = guest
                   8450: 
                   8451:             <domain></domain>     for scope type = course or group
                   8452:             <number></number>
                   8453:             <roles id="">
                   8454:              <role></role>
                   8455:              <access></access>
                   8456:              <section></section>
                   8457:              <group></group>
                   8458:             </roles>
                   8459: 
                   8460:             <dom></dom>         for scope type = domains
                   8461: 
                   8462:             <users>             for scope type = users
                   8463:              <user>
                   8464:               <uname></uname>
                   8465:               <udom></udom>
                   8466:              </user>
                   8467:             </users>
                   8468:            </scope> 
                   8469:               
                   8470:  Access data is also aggregated for each file in an additional key=value pair:
                   8471:  key -> path to file/file_name\0accesscontrol 
                   8472:  value -> reference to hash
                   8473:           hash contains key = value pairs
                   8474:           where key = uniqueID:scope_end_start
                   8475:                 value = UNIX time record was last updated
                   8476: 
                   8477:           Used to improve speed of look-ups of access controls for each file.  
                   8478:  
                   8479:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8480: 
                   8481: modify_access_controls():
                   8482: 
                   8483: Modifies access controls for a portfolio file
                   8484: Args
                   8485: 1. file name
                   8486: 2. reference to hash of required changes,
                   8487: 3. domain
                   8488: 4. username
                   8489:   where domain,username are the domain of the portfolio owner 
                   8490:   (either a user or a course) 
                   8491: 
                   8492: Returns:
                   8493: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8494: 2. result of deletions ('ok' or 'error', with error message).
                   8495: 3. reference to hash of any new or updated access controls.
                   8496: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8497:    key = integer (inbound ID)
                   8498:    value = uniqueID  
1.747     albertel 8499: 
1.608     albertel 8500: =back
                   8501: 
1.243     albertel 8502: =head2 HTTP Helper Routines
                   8503: 
                   8504: =over 4
                   8505: 
1.191     harris41 8506: =item *
                   8507: 
                   8508: escape() : unpack non-word characters into CGI-compatible hex codes
                   8509: 
                   8510: =item *
                   8511: 
                   8512: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8513: 
1.243     albertel 8514: =back
                   8515: 
                   8516: =head1 PRIVATE SUBROUTINES
                   8517: 
                   8518: =head2 Underlying communication routines (Shouldn't call)
                   8519: 
                   8520: =over 4
                   8521: 
                   8522: =item *
                   8523: 
                   8524: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8525: 
                   8526: =item *
                   8527: 
                   8528: reply() : uses subreply to send a message to remote machine, logs all failures
                   8529: 
                   8530: =item *
                   8531: 
                   8532: critical() : passes a critical message to another server; if cannot
                   8533: get through then place message in connection buffer directory and
                   8534: returns con_delayed, if incapable of saving message, returns
                   8535: con_failed
                   8536: 
                   8537: =item *
                   8538: 
                   8539: reconlonc() : tries to reconnect lonc client processes.
                   8540: 
                   8541: =back
                   8542: 
                   8543: =head2 Resource Access Logging
                   8544: 
                   8545: =over 4
                   8546: 
                   8547: =item *
                   8548: 
                   8549: flushcourselogs() : flush (save) buffer logs and access logs
                   8550: 
                   8551: =item *
                   8552: 
                   8553: courselog($what) : save message for course in hash
                   8554: 
                   8555: =item *
                   8556: 
                   8557: courseacclog($what) : save message for course using &courselog().  Perform
                   8558: special processing for specific resource types (problems, exams, quizzes, etc).
                   8559: 
1.191     harris41 8560: =item *
                   8561: 
                   8562: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8563: as a PerlChildExitHandler
1.243     albertel 8564: 
                   8565: =back
                   8566: 
                   8567: =head2 Other
                   8568: 
                   8569: =over 4
                   8570: 
                   8571: =item *
                   8572: 
                   8573: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8574: 
                   8575: =back
                   8576: 
                   8577: =cut

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