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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.820   ! raeburn     4: # $Id: lonnet.pm,v 1.819 2007/01/02 17:54:08 www 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.807     albertel   56: use LONCAPA qw(:DEFAULT :match);
1.740     www        57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.783     albertel  295: sub convert_and_load_session_env {
                    296:     my ($lonidsdir,$handle)=@_;
                    297:     my @profile;
                    298:     {
                    299: 	open(my $idf,"$lonidsdir/$handle.id");
                    300: 	flock($idf,LOCK_SH);
                    301: 	@profile=<$idf>;
                    302: 	close($idf);
                    303:     }
                    304:     my %temp_env;
                    305:     foreach my $line (@profile) {
1.786     albertel  306: 	if ($line !~ m/=/) {
                    307: 	    return 0;
                    308: 	}
1.783     albertel  309: 	chomp($line);
                    310: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    311: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    312:     }
                    313:     unlink("$lonidsdir/$handle.id");
                    314:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    315: 	    0640)) {
                    316: 	%disk_env = %temp_env;
                    317: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    318: 	untie(%disk_env);
                    319:     }
1.786     albertel  320:     return 1;
1.783     albertel  321: }
                    322: 
1.374     www       323: # ------------------------------------------- Transfer profile into environment
1.780     albertel  324: my $env_loaded;
                    325: sub transfer_profile_to_env {
1.788     albertel  326:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    327:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       328: 
1.720     albertel  329:     if (!defined($lonidsdir)) {
                    330: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    331:     }
                    332:     if (!defined($handle)) {
                    333:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    334:     }
                    335: 
1.786     albertel  336:     my $convert;
                    337:     {
                    338:     	open(my $idf,"$lonidsdir/$handle.id");
                    339: 	flock($idf,LOCK_SH);
                    340: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    341: 		&GDBM_READER(),0640)) {
                    342: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    343: 	    untie(%disk_env);
                    344: 	} else {
                    345: 	    $convert = 1;
                    346: 	}
                    347:     }
                    348:     if ($convert) {
                    349: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    350: 	    &logthis("Failed to load session, or convert session.");
                    351: 	}
1.374     www       352:     }
1.783     albertel  353: 
1.786     albertel  354:     my %remove;
1.783     albertel  355:     while ( my $envname = each(%env) ) {
1.433     matthew   356:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    357:             if ($time < time-300) {
1.783     albertel  358:                 $remove{$key}++;
1.433     matthew   359:             }
                    360:         }
                    361:     }
1.783     albertel  362: 
1.619     albertel  363:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  364:     $env_loaded=1;
1.783     albertel  365:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   366:         &delenv($expired_key);
1.374     www       367:     }
1.1       albertel  368: }
                    369: 
1.5       www       370: # ---------------------------------------------------------- Append Environment
                    371: 
                    372: sub appenv {
1.6       www       373:     my %newenv=@_;
1.692     albertel  374:     foreach my $key (keys(%newenv)) {
                    375: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  376:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  377:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       378:                 .'</font>');
1.692     albertel  379: 	    delete($newenv{$key});
1.35      www       380:         } else {
1.692     albertel  381:             $env{$key}=$newenv{$key};
1.35      www       382:         }
1.191     harris41  383:     }
1.783     albertel  384:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    385: 	    0640)) {
                    386: 	while (my ($key,$value) = each(%newenv)) {
                    387: 	    $disk_env{$key} = $value;
1.448     albertel  388: 	}
1.783     albertel  389: 	untie(%disk_env);
1.56      www       390:     }
                    391:     return 'ok';
                    392: }
                    393: # ----------------------------------------------------- Delete from Environment
                    394: 
                    395: sub delenv {
                    396:     my $delthis=shift;
                    397:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  398:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       399:                 "Attempt to delete from environment ".$delthis);
                    400:         return 'error';
                    401:     }
1.783     albertel  402:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    403: 	    0640)) {
                    404: 	foreach my $key (keys(%disk_env)) {
                    405: 	    if ($key=~/^$delthis/) { 
1.619     albertel  406:                 delete($env{$key});
1.783     albertel  407:                 delete($disk_env{$key});
1.473     matthew   408:             }
1.448     albertel  409: 	}
1.783     albertel  410: 	untie(%disk_env);
1.5       www       411:     }
                    412:     return 'ok';
1.369     albertel  413: }
                    414: 
1.790     albertel  415: sub get_env_multiple {
                    416:     my ($name) = @_;
                    417:     my @values;
                    418:     if (defined($env{$name})) {
                    419:         # exists is it an array
                    420:         if (ref($env{$name})) {
                    421:             @values=@{ $env{$name} };
                    422:         } else {
                    423:             $values[0]=$env{$name};
                    424:         }
                    425:     }
                    426:     return(@values);
                    427: }
                    428: 
1.369     albertel  429: # ------------------------------------------ Find out current server userload
                    430: # there is a copy in lond
                    431: sub userload {
                    432:     my $numusers=0;
                    433:     {
                    434: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    435: 	my $filename;
                    436: 	my $curtime=time;
                    437: 	while ($filename=readdir(LONIDS)) {
                    438: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  439: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  440: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  441: 	}
                    442: 	closedir(LONIDS);
                    443:     }
                    444:     my $userloadpercent=0;
                    445:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    446:     if ($maxuserload) {
1.371     albertel  447: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  448:     }
1.372     albertel  449:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  450:     return $userloadpercent;
1.283     www       451: }
                    452: 
                    453: # ------------------------------------------ Fight off request when overloaded
                    454: 
                    455: sub overloaderror {
                    456:     my ($r,$checkserver)=@_;
                    457:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    458:     my $loadavg;
                    459:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  460:        open(my $loadfile,'/proc/loadavg');
1.283     www       461:        $loadavg=<$loadfile>;
                    462:        $loadavg =~ s/\s.*//g;
1.285     matthew   463:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  464:        close($loadfile);
1.283     www       465:     } else {
                    466:        $loadavg=&reply('load',$checkserver);
                    467:     }
1.285     matthew   468:     my $overload=$loadavg-100;
1.283     www       469:     if ($overload>0) {
1.285     matthew   470: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       471:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       472:         return 413;
1.283     www       473:     }    
                    474:     return '';
1.5       www       475: }
1.1       albertel  476: 
                    477: # ------------------------------ Find server with least workload from spare.tab
1.11      www       478: 
1.1       albertel  479: sub spareserver {
1.670     albertel  480:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  481:     my $spare_server;
1.370     albertel  482:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  483:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    484:                                                      :  $userloadpercent;
                    485:     
                    486:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    487: 	($spare_server, $lowest_load) =
                    488: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    489:     }
                    490: 
                    491:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    492: 
                    493:     if (!$found_server) {
                    494: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    495: 	    ($spare_server, $lowest_load) =
                    496: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    497: 	}
                    498:     }
                    499: 
                    500:     if (!$want_server_name) {
                    501: 	$spare_server="http://$hostname{$spare_server}";
                    502:     }
                    503:     return $spare_server;
                    504: }
                    505: 
                    506: sub compare_server_load {
                    507:     my ($try_server, $spare_server, $lowest_load) = @_;
                    508: 
                    509:     my $loadans     = &reply('load',    $try_server);
                    510:     my $userloadans = &reply('userload',$try_server);
                    511: 
                    512:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    513: 	next; #didn't get a number from the server
                    514:     }
                    515: 
                    516:     my $load;
                    517:     if ($loadans =~ /\d/) {
                    518: 	if ($userloadans =~ /\d/) {
                    519: 	    #both are numbers, pick the bigger one
                    520: 	    $load = ($loadans > $userloadans) ? $loadans 
                    521: 		                              : $userloadans;
1.411     albertel  522: 	} else {
1.784     albertel  523: 	    $load = $loadans;
1.411     albertel  524: 	}
1.784     albertel  525:     } else {
                    526: 	$load = $userloadans;
                    527:     }
                    528: 
                    529:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    530: 	$spare_server = $try_server;
                    531: 	$lowest_load  = $load;
1.370     albertel  532:     }
1.784     albertel  533:     return ($spare_server,$lowest_load);
1.202     matthew   534: }
                    535: # --------------------------------------------- Try to change a user's password
                    536: 
                    537: sub changepass {
1.799     raeburn   538:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   539:     $currentpass = &escape($currentpass);
                    540:     $newpass     = &escape($newpass);
1.799     raeburn   541:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   542: 		       $server);
                    543:     if (! $answer) {
                    544: 	&logthis("No reply on password change request to $server ".
                    545: 		 "by $uname in domain $udom.");
                    546:     } elsif ($answer =~ "^ok") {
                    547:         &logthis("$uname in $udom successfully changed their password ".
                    548: 		 "on $server.");
                    549:     } elsif ($answer =~ "^pwchange_failure") {
                    550: 	&logthis("$uname in $udom was unable to change their password ".
                    551: 		 "on $server.  The action was blocked by either lcpasswd ".
                    552: 		 "or pwchange");
                    553:     } elsif ($answer =~ "^non_authorized") {
                    554:         &logthis("$uname in $udom did not get their password correct when ".
                    555: 		 "attempting to change it on $server.");
                    556:     } elsif ($answer =~ "^auth_mode_error") {
                    557:         &logthis("$uname in $udom attempted to change their password despite ".
                    558: 		 "not being locally or internally authenticated on $server.");
                    559:     } elsif ($answer =~ "^unknown_user") {
                    560:         &logthis("$uname in $udom attempted to change their password ".
                    561: 		 "on $server but were unable to because $server is not ".
                    562: 		 "their home server.");
                    563:     } elsif ($answer =~ "^refused") {
                    564: 	&logthis("$server refused to change $uname in $udom password because ".
                    565: 		 "it was sent an unencrypted request to change the password.");
                    566:     }
                    567:     return $answer;
1.1       albertel  568: }
                    569: 
1.169     harris41  570: # ----------------------- Try to determine user's current authentication scheme
                    571: 
                    572: sub queryauthenticate {
                    573:     my ($uname,$udom)=@_;
1.456     albertel  574:     my $uhome=&homeserver($uname,$udom);
                    575:     if (!$uhome) {
                    576: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    577: 	return 'no_host';
                    578:     }
                    579:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    580:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    581: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  582:     }
1.456     albertel  583:     return $answer;
1.169     harris41  584: }
                    585: 
1.1       albertel  586: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       587: 
1.1       albertel  588: sub authenticate {
                    589:     my ($uname,$upass,$udom)=@_;
1.807     albertel  590:     $upass=&escape($upass);
                    591:     $uname= &LONCAPA::clean_username($uname);
1.471     albertel  592:     my $uhome=&homeserver($uname,$udom);
                    593:     if (!$uhome) {
                    594: 	&logthis("User $uname at $udom is unknown in authenticate");
                    595: 	return 'no_host';
1.1       albertel  596:     }
1.471     albertel  597:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    598:     if ($answer eq 'authorized') {
                    599: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    600: 	return $uhome; 
                    601:     }
                    602:     if ($answer eq 'non_authorized') {
                    603: 	&logthis("User $uname at $udom rejected by $uhome");
                    604: 	return 'no_host'; 
1.9       www       605:     }
1.471     albertel  606:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  607:     return 'no_host';
                    608: }
                    609: 
                    610: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       611: 
1.599     albertel  612: my %homecache;
1.1       albertel  613: sub homeserver {
1.230     stredwic  614:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  615:     my $index="$uname:$udom";
1.426     albertel  616: 
1.599     albertel  617:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  618:     my $tryserver;
                    619:     foreach $tryserver (keys %libserv) {
1.230     stredwic  620:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  621: 		 exists($badServerCache{$tryserver}));
1.1       albertel  622: 	if ($hostdom{$tryserver} eq $udom) {
                    623:            my $answer=reply("home:$udom:$uname",$tryserver);
                    624:            if ($answer eq 'found') { 
1.599     albertel  625: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  626:            } elsif ($answer eq 'no_host') {
                    627: 	       $badServerCache{$tryserver}=1;
1.221     matthew   628:            }
1.1       albertel  629:        }
                    630:     }    
                    631:     return 'no_host';
1.70      www       632: }
                    633: 
                    634: # ------------------------------------- Find the usernames behind a list of IDs
                    635: 
                    636: sub idget {
                    637:     my ($udom,@ids)=@_;
                    638:     my %returnhash=();
                    639:     
                    640:     my $tryserver;
                    641:     foreach $tryserver (keys %libserv) {
                    642:        if ($hostdom{$tryserver} eq $udom) {
                    643: 	  my $idlist=join('&',@ids);
                    644:           $idlist=~tr/A-Z/a-z/; 
                    645: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    646:           my @answer=();
1.76      www       647:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       648: 	      @answer=split(/\&/,$reply);
                    649:           }                    ;
                    650:           my $i;
                    651:           for ($i=0;$i<=$#ids;$i++) {
                    652:               if ($answer[$i]) {
                    653: 		  $returnhash{$ids[$i]}=$answer[$i];
                    654:               } 
                    655:           }
                    656:        }
                    657:     }    
                    658:     return %returnhash;
                    659: }
                    660: 
                    661: # ------------------------------------- Find the IDs behind a list of usernames
                    662: 
                    663: sub idrget {
                    664:     my ($udom,@unames)=@_;
                    665:     my %returnhash=();
1.800     albertel  666:     foreach my $uname (@unames) {
                    667:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  668:     }
1.70      www       669:     return %returnhash;
                    670: }
                    671: 
                    672: # ------------------------------- Store away a list of names and associated IDs
                    673: 
                    674: sub idput {
                    675:     my ($udom,%ids)=@_;
                    676:     my %servers=();
1.800     albertel  677:     foreach my $uname (keys(%ids)) {
                    678: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    679:         my $uhom=&homeserver($uname,$udom);
1.70      www       680:         if ($uhom ne 'no_host') {
1.800     albertel  681:             my $id=&escape($ids{$uname});
1.70      www       682:             $id=~tr/A-Z/a-z/;
1.800     albertel  683:             my $esc_unam=&escape($uname);
1.70      www       684: 	    if ($servers{$uhom}) {
1.800     albertel  685: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       686:             } else {
1.800     albertel  687:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       688:             }
                    689:         }
1.191     harris41  690:     }
1.800     albertel  691:     foreach my $server (keys(%servers)) {
                    692:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  693:     }
1.344     www       694: }
                    695: 
1.806     raeburn   696: # ------------------------------------------- get items from domain db files   
                    697: 
                    698: sub get_dom {
                    699:     my ($namespace,$storearr,$udom)=@_;
                    700:     my $items='';
                    701:     foreach my $item (@$storearr) {
                    702:         $items.=&escape($item).'&';
                    703:     }
                    704:     $items=~s/\&$//;
                    705:     if (!$udom) { $udom=$env{'user.domain'}; }
                    706:     if (exists($domain_primary{$udom})) {
                    707:         my $uhome=$domain_primary{$udom};
                    708:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    709:         my @pairs=split(/\&/,$rep);
                    710:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    711:             return @pairs;
                    712:         }
                    713:         my %returnhash=();
                    714:         my $i=0;
                    715:         foreach my $item (@$storearr) {
                    716:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    717:             $i++;
                    718:         }
                    719:         return %returnhash;
                    720:     } else {
                    721:         &logthis("get_dom failed - no primary domain server for $udom");
                    722:     }
                    723: }
                    724: 
                    725: # -------------------------------------------- put items in domain db files 
                    726: 
                    727: sub put_dom {
                    728:     my ($namespace,$storehash,$udom)=@_;
                    729:     if (!$udom) { $udom=$env{'user.domain'}; }
                    730:     if (exists($domain_primary{$udom})) {
                    731:         my $uhome=$domain_primary{$udom};
                    732:         my $items='';
                    733:         foreach my $item (keys(%$storehash)) {
                    734:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    735:         }
                    736:         $items=~s/\&$//;
                    737:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    738:     } else {
                    739:         &logthis("put_dom failed - no primary domain server for $udom");
                    740:     }
                    741: }
                    742: 
1.344     www       743: # --------------------------------------------------- Assign a key to a student
                    744: 
                    745: sub assign_access_key {
1.364     www       746: #
                    747: # a valid key looks like uname:udom#comments
                    748: # comments are being appended
                    749: #
1.498     www       750:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    751:     $kdom=
1.620     albertel  752:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       753:     $knum=
1.620     albertel  754:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       755:     $cdom=
1.620     albertel  756:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       757:     $cnum=
1.620     albertel  758:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    759:     $udom=$env{'user.name'} unless (defined($udom));
                    760:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       761:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       762:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  763:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       764:                                                   # assigned to this person
                    765:                                                   # - this should not happen,
1.345     www       766:                                                   # unless something went wrong
                    767:                                                   # the first time around
                    768: # ready to assign
1.364     www       769:         $logentry=$1.'; '.$logentry;
1.496     www       770:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       771:                                                  $kdom,$knum) eq 'ok') {
1.345     www       772: # key now belongs to user
1.346     www       773: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       774:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    775:                 &appenv('environment.'.$envkey => $ckey);
                    776:                 return 'ok';
                    777:             } else {
                    778:                 return 
                    779:   'error: Count not permanently assign key, will need to be re-entered later.';
                    780: 	    }
                    781:         } else {
                    782:             return 'error: Could not assign key, try again later.';
                    783:         }
1.364     www       784:     } elsif (!$existing{$ckey}) {
1.345     www       785: # the key does not exist
                    786: 	return 'error: The key does not exist';
                    787:     } else {
                    788: # the key is somebody else's
                    789: 	return 'error: The key is already in use';
                    790:     }
1.344     www       791: }
                    792: 
1.364     www       793: # ------------------------------------------ put an additional comment on a key
                    794: 
                    795: sub comment_access_key {
                    796: #
                    797: # a valid key looks like uname:udom#comments
                    798: # comments are being appended
                    799: #
                    800:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    801:     $cdom=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       803:     $cnum=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       805:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    806:     if ($existing{$ckey}) {
                    807:         $existing{$ckey}.='; '.$logentry;
                    808: # ready to assign
1.367     www       809:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       810:                                                  $cdom,$cnum) eq 'ok') {
                    811: 	    return 'ok';
                    812:         } else {
                    813: 	    return 'error: Count not store comment.';
                    814:         }
                    815:     } else {
                    816: # the key does not exist
                    817: 	return 'error: The key does not exist';
                    818:     }
                    819: }
                    820: 
1.344     www       821: # ------------------------------------------------------ Generate a set of keys
                    822: 
                    823: sub generate_access_keys {
1.364     www       824:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       825:     $cdom=
1.620     albertel  826:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       827:     $cnum=
1.620     albertel  828:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       829:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       830:     unless (($cdom) && ($cnum)) { return 0; }
                    831:     if ($number>10000) { return 0; }
                    832:     sleep(2); # make sure don't get same seed twice
                    833:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    834:     my $total=0;
                    835:     for (my $i=1;$i<=$number;$i++) {
                    836:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    837:                   sprintf("%lx",int(100000*rand)).'-'.
                    838:                   sprintf("%lx",int(100000*rand));
                    839:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    840:        $newkey=~s/0/h/g; # and also 0 and O
                    841:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    842:        if ($existing{$newkey}) {
                    843:            $i--;
                    844:        } else {
1.364     www       845: 	  if (&put('accesskeys',
                    846:               { $newkey => '# generated '.localtime().
1.620     albertel  847:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       848:                            '; '.$logentry },
                    849: 		   $cdom,$cnum) eq 'ok') {
1.344     www       850:               $total++;
                    851: 	  }
                    852:        }
                    853:     }
1.620     albertel  854:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       855:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    856:     return $total;
                    857: }
                    858: 
                    859: # ------------------------------------------------------- Validate an accesskey
                    860: 
                    861: sub validate_access_key {
                    862:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    863:     $cdom=
1.620     albertel  864:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       865:     $cnum=
1.620     albertel  866:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    867:     $udom=$env{'user.domain'} unless (defined($udom));
                    868:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       869:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  870:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       871: }
                    872: 
                    873: # ------------------------------------- Find the section of student in a course
1.652     albertel  874: sub devalidate_getsection_cache {
                    875:     my ($udom,$unam,$courseid)=@_;
                    876:     my $hashid="$udom:$unam:$courseid";
                    877:     &devalidate_cache_new('getsection',$hashid);
                    878: }
1.298     matthew   879: 
1.815     albertel  880: sub courseid_to_courseurl {
                    881:     my ($courseid) = @_;
                    882:     #already url style courseid
                    883:     return $courseid if ($courseid =~ m{^/});
                    884: 
                    885:     if (exists($env{'course.'.$courseid.'.num'})) {
                    886: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    887: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    888: 	return "/$cdom/$cnum";
                    889:     }
                    890: 
                    891:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    892:     if (exists($courseinfo{'num'})) {
                    893: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    894:     }
                    895: 
                    896:     return undef;
                    897: }
                    898: 
1.298     matthew   899: sub getsection {
                    900:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  901:     my $cachetime=1800;
1.551     albertel  902: 
                    903:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  904:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  905:     if (defined($cached)) { return $result; }
                    906: 
1.298     matthew   907:     my %Pending; 
                    908:     my %Expired;
                    909:     #
                    910:     # Each role can either have not started yet (pending), be active, 
                    911:     #    or have expired.
                    912:     #
                    913:     # If there is an active role, we are done.
                    914:     #
                    915:     # If there is more than one role which has not started yet, 
                    916:     #     choose the one which will start sooner
                    917:     # If there is one role which has not started yet, return it.
                    918:     #
                    919:     # If there is more than one expired role, choose the one which ended last.
                    920:     # If there is a role which has expired, return it.
                    921:     #
1.815     albertel  922:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   923:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    924:     foreach my $key (keys(%roleshash)) {
1.479     albertel  925:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   926:         my $section=$1;
                    927:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   928:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   929:         my $now=time;
1.548     albertel  930:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   931:             $Expired{$end}=$section;
                    932:             next;
                    933:         }
1.548     albertel  934:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   935:             $Pending{$start}=$section;
                    936:             next;
                    937:         }
1.599     albertel  938:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   939:     }
                    940:     #
                    941:     # Presumedly there will be few matching roles from the above
                    942:     # loop and the sorting time will be negligible.
                    943:     if (scalar(keys(%Pending))) {
                    944:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  945:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   946:     } 
                    947:     if (scalar(keys(%Expired))) {
                    948:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    949:         my $time = pop(@sorted);
1.599     albertel  950:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   951:     }
1.599     albertel  952:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   953: }
1.70      www       954: 
1.599     albertel  955: sub save_cache {
                    956:     &purge_remembered();
1.722     albertel  957:     #&Apache::loncommon::validate_page();
1.620     albertel  958:     undef(%env);
1.780     albertel  959:     undef($env_loaded);
1.599     albertel  960: }
1.452     albertel  961: 
1.599     albertel  962: my $to_remember=-1;
                    963: my %remembered;
                    964: my %accessed;
                    965: my $kicks=0;
                    966: my $hits=0;
                    967: sub devalidate_cache_new {
                    968:     my ($name,$id,$debug) = @_;
                    969:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    970:     $id=&escape($name.':'.$id);
                    971:     $memcache->delete($id);
                    972:     delete($remembered{$id});
                    973:     delete($accessed{$id});
                    974: }
                    975: 
                    976: sub is_cached_new {
                    977:     my ($name,$id,$debug) = @_;
                    978:     $id=&escape($name.':'.$id);
                    979:     if (exists($remembered{$id})) {
                    980: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    981: 	$accessed{$id}=[&gettimeofday()];
                    982: 	$hits++;
                    983: 	return ($remembered{$id},1);
                    984:     }
                    985:     my $value = $memcache->get($id);
                    986:     if (!(defined($value))) {
                    987: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  988: 	return (undef,undef);
1.416     albertel  989:     }
1.599     albertel  990:     if ($value eq '__undef__') {
                    991: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    992: 	$value=undef;
                    993:     }
                    994:     &make_room($id,$value,$debug);
                    995:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    996:     return ($value,1);
                    997: }
                    998: 
                    999: sub do_cache_new {
                   1000:     my ($name,$id,$value,$time,$debug) = @_;
                   1001:     $id=&escape($name.':'.$id);
                   1002:     my $setvalue=$value;
                   1003:     if (!defined($setvalue)) {
                   1004: 	$setvalue='__undef__';
                   1005:     }
1.623     albertel 1006:     if (!defined($time) ) {
                   1007: 	$time=600;
                   1008:     }
1.599     albertel 1009:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1010:     $memcache->set($id,$setvalue,$time);
                   1011:     # need to make a copy of $value
                   1012:     #&make_room($id,$value,$debug);
1.599     albertel 1013:     return $value;
                   1014: }
                   1015: 
                   1016: sub make_room {
                   1017:     my ($id,$value,$debug)=@_;
                   1018:     $remembered{$id}=$value;
                   1019:     if ($to_remember<0) { return; }
                   1020:     $accessed{$id}=[&gettimeofday()];
                   1021:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1022:     my $to_kick;
                   1023:     my $max_time=0;
                   1024:     foreach my $other (keys(%accessed)) {
                   1025: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1026: 	    $to_kick=$other;
                   1027: 	    $max_time=&tv_interval($accessed{$other});
                   1028: 	}
                   1029:     }
                   1030:     delete($remembered{$to_kick});
                   1031:     delete($accessed{$to_kick});
                   1032:     $kicks++;
                   1033:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1034:     return;
                   1035: }
                   1036: 
1.599     albertel 1037: sub purge_remembered {
1.604     albertel 1038:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1039:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1040:     undef(%remembered);
                   1041:     undef(%accessed);
1.428     albertel 1042: }
1.70      www      1043: # ------------------------------------- Read an entry from a user's environment
                   1044: 
                   1045: sub userenvironment {
                   1046:     my ($udom,$unam,@what)=@_;
                   1047:     my %returnhash=();
                   1048:     my @answer=split(/\&/,
                   1049:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1050:                       &homeserver($unam,$udom)));
                   1051:     my $i;
                   1052:     for ($i=0;$i<=$#what;$i++) {
                   1053: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1054:     }
                   1055:     return %returnhash;
1.1       albertel 1056: }
                   1057: 
1.617     albertel 1058: # ---------------------------------------------------------- Get a studentphoto
                   1059: sub studentphoto {
                   1060:     my ($udom,$unam,$ext) = @_;
                   1061:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1062:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1063:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1064:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1065:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1066:             } else {
                   1067:                 my ($result,$perm_reqd)=
1.707     albertel 1068: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1069:                 if ($result eq 'ok') {
                   1070:                     if (!($perm_reqd eq 'yes')) {
                   1071:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1072:                     }
                   1073:                 }
                   1074:             }
                   1075:         }
                   1076:     } else {
                   1077:         my ($result,$perm_reqd) = 
1.707     albertel 1078: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1079:         if ($result eq 'ok') {
                   1080:             if (!($perm_reqd eq 'yes')) {
                   1081:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1082:             }
                   1083:         }
                   1084:     }
                   1085:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1086: }
                   1087: 
                   1088: sub retrievestudentphoto {
                   1089:     my ($udom,$unam,$ext,$type) = @_;
                   1090:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1091:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1092:     if ($ret eq 'ok') {
                   1093:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1094:         if ($type eq 'thumbnail') {
                   1095:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1096:         }
                   1097:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1098:         return $tokenurl;
                   1099:     } else {
                   1100:         if ($type eq 'thumbnail') {
                   1101:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1102:         } else { 
                   1103:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1104:         }
1.617     albertel 1105:     }
                   1106: }
                   1107: 
1.263     www      1108: # -------------------------------------------------------------------- New chat
                   1109: 
                   1110: sub chatsend {
1.724     raeburn  1111:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1112:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1113:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1114:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1115:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1116: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1117: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1118: }
                   1119: 
                   1120: # ------------------------------------------ Find current version of a resource
                   1121: 
                   1122: sub getversion {
                   1123:     my $fname=&clutter(shift);
                   1124:     unless ($fname=~/^\/res\//) { return -1; }
                   1125:     return &currentversion(&filelocation('',$fname));
                   1126: }
                   1127: 
                   1128: sub currentversion {
                   1129:     my $fname=shift;
1.599     albertel 1130:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1131:     if (defined($cached)) { return $result; }
1.292     www      1132:     my $author=$fname;
                   1133:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1134:     my ($udom,$uname)=split(/\//,$author);
                   1135:     my $home=homeserver($uname,$udom);
                   1136:     if ($home eq 'no_host') { 
                   1137:         return -1; 
                   1138:     }
                   1139:     my $answer=reply("currentversion:$fname",$home);
                   1140:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1141: 	return -1;
                   1142:     }
1.599     albertel 1143:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1144: }
                   1145: 
1.1       albertel 1146: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1147: 
1.1       albertel 1148: sub subscribe {
                   1149:     my $fname=shift;
1.761     raeburn  1150:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1151:     $fname=~s/[\n\r]//g;
1.1       albertel 1152:     my $author=$fname;
                   1153:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1154:     my ($udom,$uname)=split(/\//,$author);
                   1155:     my $home=homeserver($uname,$udom);
1.335     albertel 1156:     if ($home eq 'no_host') {
                   1157:         return 'not_found';
1.1       albertel 1158:     }
                   1159:     my $answer=reply("sub:$fname",$home);
1.64      www      1160:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1161: 	$answer.=' by '.$home;
                   1162:     }
1.1       albertel 1163:     return $answer;
                   1164: }
                   1165:     
1.8       www      1166: # -------------------------------------------------------------- Replicate file
                   1167: 
                   1168: sub repcopy {
                   1169:     my $filename=shift;
1.23      www      1170:     $filename=~s/\/+/\//g;
1.607     raeburn  1171:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1172:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1173:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1174: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1175: 	return &repcopy_userfile($filename);
                   1176:     }
1.532     albertel 1177:     $filename=~s/[\n\r]//g;
1.8       www      1178:     my $transname="$filename.in.transfer";
1.607     raeburn  1179:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1180:     my $remoteurl=subscribe($filename);
1.64      www      1181:     if ($remoteurl =~ /^con_lost by/) {
                   1182: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1183:            return 'unavailable';
1.8       www      1184:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1185: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1186: 	   return 'not_found';
1.64      www      1187:     } elsif ($remoteurl =~ /^rejected by/) {
                   1188: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1189:            return 'forbidden';
1.20      www      1190:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1191:            return 'ok';
1.8       www      1192:     } else {
1.290     www      1193:         my $author=$filename;
                   1194:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1195:         my ($udom,$uname)=split(/\//,$author);
                   1196:         my $home=homeserver($uname,$udom);
                   1197:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1198:            my @parts=split(/\//,$filename);
                   1199:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1200:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1201:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1202: 	       return 'bad_request';
1.8       www      1203:            }
                   1204:            my $count;
                   1205:            for ($count=5;$count<$#parts;$count++) {
                   1206:                $path.="/$parts[$count]";
                   1207:                if ((-e $path)!=1) {
                   1208: 		   mkdir($path,0777);
                   1209:                }
                   1210:            }
                   1211:            my $ua=new LWP::UserAgent;
                   1212:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1213:            my $response=$ua->request($request,$transname);
                   1214:            if ($response->is_error()) {
                   1215: 	       unlink($transname);
                   1216:                my $message=$response->status_line;
1.672     albertel 1217:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1218:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1219:                return 'unavailable';
1.8       www      1220:            } else {
1.16      www      1221: 	       if ($remoteurl!~/\.meta$/) {
                   1222:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1223:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1224:                   if ($mresponse->is_error()) {
                   1225: 		      unlink($filename.'.meta');
                   1226:                       &logthis(
1.672     albertel 1227:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1228:                   }
                   1229: 	       }
1.8       www      1230:                rename($transname,$filename);
1.607     raeburn  1231:                return 'ok';
1.8       www      1232:            }
1.290     www      1233:        }
1.8       www      1234:     }
1.330     www      1235: }
                   1236: 
                   1237: # ------------------------------------------------ Get server side include body
                   1238: sub ssi_body {
1.381     albertel 1239:     my ($filelink,%form)=@_;
1.606     matthew  1240:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1241:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1242:     }
1.330     www      1243:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1244:                                      &ssi($filelink,%form));
1.778     albertel 1245:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1246:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1247:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1248:     return $output;
1.8       www      1249: }
                   1250: 
1.15      www      1251: # --------------------------------------------------------- Server Side Include
                   1252: 
1.782     albertel 1253: sub absolute_url {
                   1254:     my ($host_name) = @_;
                   1255:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1256:     if ($host_name eq '') {
                   1257: 	$host_name = $ENV{'SERVER_NAME'};
                   1258:     }
                   1259:     return $protocol.$host_name;
                   1260: }
                   1261: 
1.15      www      1262: sub ssi {
                   1263: 
1.23      www      1264:     my ($fn,%form)=@_;
1.15      www      1265: 
                   1266:     my $ua=new LWP::UserAgent;
1.23      www      1267:     
                   1268:     my $request;
1.711     albertel 1269: 
                   1270:     $form{'no_update_last_known'}=1;
                   1271: 
1.23      www      1272:     if (%form) {
1.782     albertel 1273:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1274:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1275:     } else {
1.782     albertel 1276:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1277:     }
                   1278: 
1.15      www      1279:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1280:     my $response=$ua->request($request);
                   1281: 
1.324     www      1282:     return $response->content;
                   1283: }
                   1284: 
                   1285: sub externalssi {
                   1286:     my ($url)=@_;
                   1287:     my $ua=new LWP::UserAgent;
                   1288:     my $request=new HTTP::Request('GET',$url);
                   1289:     my $response=$ua->request($request);
1.15      www      1290:     return $response->content;
                   1291: }
1.254     www      1292: 
1.492     albertel 1293: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1294: 
                   1295: sub allowuploaded {
                   1296:     my ($srcurl,$url)=@_;
                   1297:     $url=&clutter(&declutter($url));
                   1298:     my $dir=$url;
                   1299:     $dir=~s/\/[^\/]+$//;
                   1300:     my %httpref=();
                   1301:     my $httpurl=&hreflocation('',$url);
                   1302:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1303:     &Apache::lonnet::appenv(%httpref);
1.254     www      1304: }
1.477     raeburn  1305: 
1.478     albertel 1306: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1307: # input: action, courseID, current domain, intended
1.637     raeburn  1308: #        path to file, source of file, instruction to parse file for objects,
                   1309: #        ref to hash for embedded objects,
                   1310: #        ref to hash for codebase of java objects.
                   1311: #
1.485     raeburn  1312: # output: url to file (if action was uploaddoc), 
                   1313: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1314: #
1.478     albertel 1315: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1316: # course.
1.477     raeburn  1317: #
1.478     albertel 1318: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1319: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1320: #          course's home server.
1.477     raeburn  1321: #
1.478     albertel 1322: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1323: #          be copied from $source (current location) to 
                   1324: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1325: #         and will then be copied to
                   1326: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1327: #         course's home server.
1.485     raeburn  1328: #
1.481     raeburn  1329: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1330: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1331: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1332: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1333: #         in course's home server.
1.637     raeburn  1334: #
1.477     raeburn  1335: 
                   1336: sub process_coursefile {
1.638     albertel 1337:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1338:     my $fetchresult;
1.638     albertel 1339:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1340:     if ($action eq 'propagate') {
1.638     albertel 1341:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1342: 			     $home);
1.481     raeburn  1343:     } else {
1.477     raeburn  1344:         my $fpath = '';
                   1345:         my $fname = $file;
1.478     albertel 1346:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1347:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1348:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1349:         if ($action eq 'copy') {
                   1350:             if ($source eq '') {
                   1351:                 $fetchresult = 'no source file';
                   1352:                 return $fetchresult;
                   1353:             } else {
                   1354:                 my $destination = $filepath.'/'.$fname;
                   1355:                 rename($source,$destination);
                   1356:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1357:                                  $home);
1.481     raeburn  1358:             }
                   1359:         } elsif ($action eq 'uploaddoc') {
                   1360:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1361:             print $fh $env{'form.'.$source};
1.481     raeburn  1362:             close($fh);
1.637     raeburn  1363:             if ($parser eq 'parse') {
                   1364:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1365:                 unless ($parse_result eq 'ok') {
                   1366:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1367:                 }
                   1368:             }
1.477     raeburn  1369:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1370:                                  $home);
1.481     raeburn  1371:             if ($fetchresult eq 'ok') {
                   1372:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1373:             } else {
                   1374:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1375:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1376:                 return '/adm/notfound.html';
                   1377:             }
1.477     raeburn  1378:         }
                   1379:     }
1.485     raeburn  1380:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1381:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1382:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1383:     }
                   1384:     return $fetchresult;
                   1385: }
                   1386: 
1.637     raeburn  1387: sub build_filepath {
                   1388:     my ($fpath) = @_;
                   1389:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1390:     unless ($fpath eq '') {
                   1391:         my @parts=split('/',$fpath);
                   1392:         foreach my $part (@parts) {
                   1393:             $filepath.= '/'.$part;
                   1394:             if ((-e $filepath)!=1) {
                   1395:                 mkdir($filepath,0777);
                   1396:             }
                   1397:         }
                   1398:     }
                   1399:     return $filepath;
                   1400: }
                   1401: 
                   1402: sub store_edited_file {
1.638     albertel 1403:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1404:     my $file = $primary_url;
                   1405:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1406:     my $fpath = '';
                   1407:     my $fname = $file;
                   1408:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1409:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1410:     my $filepath = &build_filepath($fpath);
                   1411:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1412:     print $fh $content;
                   1413:     close($fh);
1.638     albertel 1414:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1415:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1416: 			  $home);
1.637     raeburn  1417:     if ($$fetchresult eq 'ok') {
                   1418:         return '/uploaded/'.$fpath.'/'.$fname;
                   1419:     } else {
1.638     albertel 1420:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1421: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1422:         return '/adm/notfound.html';
                   1423:     }
                   1424: }
                   1425: 
1.531     albertel 1426: sub clean_filename {
                   1427:     my ($fname)=@_;
1.315     www      1428: # Replace Windows backslashes by forward slashes
1.257     www      1429:     $fname=~s/\\/\//g;
1.315     www      1430: # Get rid of everything but the actual filename
1.257     www      1431:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1432: # Replace spaces by underscores
                   1433:     $fname=~s/\s+/\_/g;
                   1434: # Replace all other weird characters by nothing
1.317     www      1435:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1436: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1437: # numbers
                   1438:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1439:     return $fname;
                   1440: }
                   1441: 
1.608     albertel 1442: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1443: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1444: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1445: #        $coursedoc - if true up to the current course
                   1446: #                     if false
                   1447: #        $subdir - directory in userfile to store the file into
                   1448: #        $parser, $allfiles, $codebase - unknown
                   1449: #
                   1450: # output: url of file in userspace, or error: <message> 
                   1451: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1452: 
                   1453: 
1.531     albertel 1454: sub userfileupload {
1.719     banghart 1455:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1456:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1457:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1458:     $fname=&clean_filename($fname);
1.315     www      1459: # See if there is anything left
1.257     www      1460:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1461:     chop($env{'form.'.$formname});
1.523     raeburn  1462:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1463:         my $now = time;
                   1464:         my $filepath = 'tmp/helprequests/'.$now;
                   1465:         my @parts=split(/\//,$filepath);
                   1466:         my $fullpath = $perlvar{'lonDaemons'};
                   1467:         for (my $i=0;$i<@parts;$i++) {
                   1468:             $fullpath .= '/'.$parts[$i];
                   1469:             if ((-e $fullpath)!=1) {
                   1470:                 mkdir($fullpath,0777);
                   1471:             }
                   1472:         }
                   1473:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1474:         print $fh $env{'form.'.$formname};
1.523     raeburn  1475:         close($fh);
1.741     raeburn  1476:         return $fullpath.'/'.$fname;
                   1477:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1478:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1479:                        '_'.$env{'user.domain'}.'/pending';
                   1480:         my @parts=split(/\//,$filepath);
                   1481:         my $fullpath = $perlvar{'lonDaemons'};
                   1482:         for (my $i=0;$i<@parts;$i++) {
                   1483:             $fullpath .= '/'.$parts[$i];
                   1484:             if ((-e $fullpath)!=1) {
                   1485:                 mkdir($fullpath,0777);
                   1486:             }
                   1487:         }
                   1488:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1489:         print $fh $env{'form.'.$formname};
                   1490:         close($fh);
                   1491:         return $fullpath.'/'.$fname;
1.523     raeburn  1492:     }
1.719     banghart 1493:     
1.258     www      1494: # Create the directory if not present
1.493     albertel 1495:     $fname="$subdir/$fname";
1.259     www      1496:     if ($coursedoc) {
1.638     albertel 1497: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1498: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1499:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1500:             return &finishuserfileupload($docuname,$docudom,
                   1501: 					 $formname,$fname,$parser,$allfiles,
                   1502: 					 $codebase);
1.481     raeburn  1503:         } else {
1.620     albertel 1504:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1505:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1506: 				       $fname,$formname,$parser,
                   1507: 				       $allfiles,$codebase);
1.481     raeburn  1508:         }
1.719     banghart 1509:     } elsif (defined($destuname)) {
                   1510:         my $docuname=$destuname;
                   1511:         my $docudom=$destudom;
                   1512: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1513: 				     $fname,$parser,$allfiles,$codebase);
                   1514:         
1.259     www      1515:     } else {
1.638     albertel 1516:         my $docuname=$env{'user.name'};
                   1517:         my $docudom=$env{'user.domain'};
1.714     raeburn  1518:         if (exists($env{'form.group'})) {
                   1519:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1520:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1521:         }
1.638     albertel 1522: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1523: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1524:     }
1.271     www      1525: }
                   1526: 
                   1527: sub finishuserfileupload {
1.638     albertel 1528:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1529:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1530:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1531:     my ($fnamepath,$file);
                   1532:     $file=$fname;
                   1533:     if ($fname=~m|/|) {
                   1534:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1535: 	$path.=$fnamepath.'/';
                   1536:     }
1.259     www      1537:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1538:     my $count;
                   1539:     for ($count=4;$count<=$#parts;$count++) {
                   1540:         $filepath.="/$parts[$count]";
                   1541:         if ((-e $filepath)!=1) {
                   1542: 	    mkdir($filepath,0777);
                   1543:         }
                   1544:     }
                   1545: # Save the file
                   1546:     {
1.701     albertel 1547: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1548: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1549: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1550: 	    return '/adm/notfound.html';
                   1551: 	}
                   1552: 	if (!print FH ($env{'form.'.$formname})) {
                   1553: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1554: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1555: 	    return '/adm/notfound.html';
                   1556: 	}
1.570     albertel 1557: 	close(FH);
1.258     www      1558:     }
1.637     raeburn  1559:     if ($parser eq 'parse') {
1.638     albertel 1560:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1561: 						   $codebase);
1.637     raeburn  1562:         unless ($parse_result eq 'ok') {
1.638     albertel 1563:             &logthis('Failed to parse '.$filepath.$file.
                   1564: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1565:         }
                   1566:     }
1.259     www      1567: # Notify homeserver to grep it
                   1568: #
1.638     albertel 1569:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1570:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1571:     if ($fetchresult eq 'ok') {
1.259     www      1572: #
1.258     www      1573: # Return the URL to it
1.494     albertel 1574:         return '/uploaded/'.$path.$file;
1.263     www      1575:     } else {
1.494     albertel 1576:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1577: 		 ': '.$fetchresult);
1.263     www      1578:         return '/adm/notfound.html';
                   1579:     }    
1.493     albertel 1580: }
                   1581: 
1.637     raeburn  1582: sub extract_embedded_items {
1.648     raeburn  1583:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1584:     my @state = ();
                   1585:     my %javafiles = (
                   1586:                       codebase => '',
                   1587:                       code => '',
                   1588:                       archive => ''
                   1589:                     );
                   1590:     my %mediafiles = (
                   1591:                       src => '',
                   1592:                       movie => '',
                   1593:                      );
1.648     raeburn  1594:     my $p;
                   1595:     if ($content) {
                   1596:         $p = HTML::LCParser->new($content);
                   1597:     } else {
                   1598:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1599:     }
1.641     albertel 1600:     while (my $t=$p->get_token()) {
1.640     albertel 1601: 	if ($t->[0] eq 'S') {
                   1602: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1603: 	    push (@state, $tagname);
1.648     raeburn  1604:             if (lc($tagname) eq 'allow') {
                   1605:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1606:             }
1.640     albertel 1607: 	    if (lc($tagname) eq 'img') {
                   1608: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1609: 	    }
1.645     raeburn  1610:             if (lc($tagname) eq 'script') {
                   1611:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1612:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1613:                 } else {
                   1614:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1615:                 }
                   1616:             }
                   1617:             if (lc($tagname) eq 'link') {
                   1618:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1619:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1620:                 }
                   1621:             }
1.640     albertel 1622: 	    if (lc($tagname) eq 'object' ||
                   1623: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1624: 		foreach my $item (keys(%javafiles)) {
                   1625: 		    $javafiles{$item} = '';
                   1626: 		}
                   1627: 	    }
                   1628: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1629: 		my $name = lc($attr->{'name'});
                   1630: 		foreach my $item (keys(%javafiles)) {
                   1631: 		    if ($name eq $item) {
                   1632: 			$javafiles{$item} = $attr->{'value'};
                   1633: 			last;
                   1634: 		    }
                   1635: 		}
                   1636: 		foreach my $item (keys(%mediafiles)) {
                   1637: 		    if ($name eq $item) {
                   1638: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1639: 			last;
                   1640: 		    }
                   1641: 		}
                   1642: 	    }
                   1643: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1644: 		foreach my $item (keys(%javafiles)) {
                   1645: 		    if ($attr->{$item}) {
                   1646: 			$javafiles{$item} = $attr->{$item};
                   1647: 			last;
                   1648: 		    }
                   1649: 		}
                   1650: 		foreach my $item (keys(%mediafiles)) {
                   1651: 		    if ($attr->{$item}) {
                   1652: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1653: 			last;
                   1654: 		    }
                   1655: 		}
                   1656: 	    }
                   1657: 	} elsif ($t->[0] eq 'E') {
                   1658: 	    my ($tagname) = ($t->[1]);
                   1659: 	    if ($javafiles{'codebase'} ne '') {
                   1660: 		$javafiles{'codebase'} .= '/';
                   1661: 	    }  
                   1662: 	    if (lc($tagname) eq 'applet' ||
                   1663: 		lc($tagname) eq 'object' ||
                   1664: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1665: 		) {
                   1666: 		foreach my $item (keys(%javafiles)) {
                   1667: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1668: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1669: 			&add_filetype($allfiles,$file,$item);
                   1670: 		    }
                   1671: 		}
                   1672: 	    } 
                   1673: 	    pop @state;
                   1674: 	}
                   1675:     }
1.637     raeburn  1676:     return 'ok';
                   1677: }
                   1678: 
1.639     albertel 1679: sub add_filetype {
                   1680:     my ($allfiles,$file,$type)=@_;
                   1681:     if (exists($allfiles->{$file})) {
                   1682: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1683: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1684: 	}
                   1685:     } else {
                   1686: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1687:     }
                   1688: }
                   1689: 
1.493     albertel 1690: sub removeuploadedurl {
                   1691:     my ($url)=@_;
                   1692:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1693:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1694: }
                   1695: 
                   1696: sub removeuserfile {
                   1697:     my ($docuname,$docudom,$fname)=@_;
                   1698:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1699:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1700:     if ($result eq 'ok') {
                   1701:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1702:             my $metafile = $fname.'.meta';
                   1703:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
                   1704:         }
                   1705:     }
                   1706:     return $result;
1.257     www      1707: }
1.15      www      1708: 
1.530     albertel 1709: sub mkdiruserfile {
                   1710:     my ($docuname,$docudom,$dir)=@_;
                   1711:     my $home=&homeserver($docuname,$docudom);
                   1712:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1713: }
                   1714: 
1.531     albertel 1715: sub renameuserfile {
                   1716:     my ($docuname,$docudom,$old,$new)=@_;
                   1717:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1718:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1719:                         &escape("$old").':'.&escape("$new"),$home);
                   1720:     if ($result eq 'ok') {
                   1721:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1722:             my $oldmeta = $old.'.meta';
                   1723:             my $newmeta = $new.'.meta';
                   1724:             my $metaresult = 
                   1725:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
                   1726:         }
                   1727:     }
                   1728:     return $result;
1.531     albertel 1729: }
                   1730: 
1.14      www      1731: # ------------------------------------------------------------------------- Log
                   1732: 
                   1733: sub log {
                   1734:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1735:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1736: }
                   1737: 
                   1738: # ------------------------------------------------------------------ Course Log
1.352     www      1739: #
                   1740: # This routine flushes several buffers of non-mission-critical nature
                   1741: #
1.157     www      1742: 
                   1743: sub flushcourselogs {
1.352     www      1744:     &logthis('Flushing log buffers');
                   1745: #
                   1746: # course logs
                   1747: # This is a log of all transactions in a course, which can be used
                   1748: # for data mining purposes
                   1749: #
                   1750: # It also collects the courseid database, which lists last transaction
                   1751: # times and course titles for all courseids
                   1752: #
                   1753:     my %courseidbuffer=();
1.800     albertel 1754:     foreach my $crsid (keys %courselogs) {
1.352     www      1755:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1756: 		          &escape($courselogs{$crsid}),
                   1757: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1758: 	    delete $courselogs{$crsid};
                   1759:         } else {
                   1760:             &logthis('Failed to flush log buffer for '.$crsid);
                   1761:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1762:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1763:                         " exceeded maximum size, deleting.</font>");
                   1764:                delete $courselogs{$crsid};
                   1765:             }
1.352     www      1766:         }
                   1767:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1768:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1769: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1770:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1771:         } else {
                   1772:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1773: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1774:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1775:         }
1.191     harris41 1776:     }
1.352     www      1777: #
                   1778: # Write course id database (reverse lookup) to homeserver of courses 
                   1779: # Is used in pickcourse
                   1780: #
1.800     albertel 1781:     foreach my $crsid (keys(%courseidbuffer)) {
                   1782:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1783:     }
                   1784: #
                   1785: # File accesses
                   1786: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1787: #
1.449     matthew  1788:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1789:         if ($entry =~ /___count$/) {
                   1790:             my ($dom,$name);
1.807     albertel 1791:             ($dom,$name,undef)=
1.811     albertel 1792: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1793:             if (! defined($dom) || $dom eq '' || 
                   1794:                 ! defined($name) || $name eq '') {
1.620     albertel 1795:                 my $cid = $env{'request.course.id'};
                   1796:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1797:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1798:             }
1.450     matthew  1799:             my $value = $accesshash{$entry};
                   1800:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1801:             my %temphash=($url => $value);
1.449     matthew  1802:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1803:             if ($result eq 'ok') {
                   1804:                 delete $accesshash{$entry};
                   1805:             } elsif ($result eq 'unknown_cmd') {
                   1806:                 # Target server has old code running on it.
1.450     matthew  1807:                 my %temphash=($entry => $value);
1.449     matthew  1808:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1809:                     delete $accesshash{$entry};
                   1810:                 }
                   1811:             }
                   1812:         } else {
1.811     albertel 1813:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1814:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1815:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1816:                 delete $accesshash{$entry};
                   1817:             }
1.185     www      1818:         }
1.191     harris41 1819:     }
1.352     www      1820: #
                   1821: # Roles
                   1822: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1823: #
1.800     albertel 1824:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1825:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1826: 	    split(/\:/,$entry);
                   1827:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1828:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1829:                 $rudom,$runame) eq 'ok') {
                   1830: 	    delete $userrolehash{$entry};
                   1831:         }
                   1832:     }
1.662     raeburn  1833: #
                   1834: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1835: #
                   1836:     my %domrolebuffer = ();
                   1837:     foreach my $entry (keys %domainrolehash) {
                   1838:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1839:         if ($domrolebuffer{$rudom}) {
                   1840:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1841:                       '='.&escape($domainrolehash{$entry});
                   1842:         } else {
                   1843:             $domrolebuffer{$rudom}.=&escape($entry).
                   1844:                       '='.&escape($domainrolehash{$entry});
                   1845:         }
                   1846:         delete $domainrolehash{$entry};
                   1847:     }
                   1848:     foreach my $dom (keys(%domrolebuffer)) {
                   1849:         foreach my $tryserver (keys %libserv) {
                   1850:             if ($hostdom{$tryserver} eq $dom) {
                   1851:                 unless (&reply('domroleput:'.$dom.':'.
                   1852:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1853:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1854:                 }
                   1855:             }
                   1856:         }
                   1857:     }
1.186     www      1858:     $dumpcount++;
1.157     www      1859: }
                   1860: 
                   1861: sub courselog {
                   1862:     my $what=shift;
1.158     www      1863:     $what=time.':'.$what;
1.620     albertel 1864:     unless ($env{'request.course.id'}) { return ''; }
                   1865:     $coursedombuf{$env{'request.course.id'}}=
                   1866:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1867:     $coursenumbuf{$env{'request.course.id'}}=
                   1868:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1869:     $coursehombuf{$env{'request.course.id'}}=
                   1870:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1871:     $coursedescrbuf{$env{'request.course.id'}}=
                   1872:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1873:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1874:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1875:     $courseownerbuf{$env{'request.course.id'}}=
                   1876:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1877:     $coursetypebuf{$env{'request.course.id'}}=
                   1878:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1879:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1880: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1881:     } else {
1.620     albertel 1882: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1883:     }
1.620     albertel 1884:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1885: 	&flushcourselogs();
                   1886:     }
1.158     www      1887: }
                   1888: 
                   1889: sub courseacclog {
                   1890:     my $fnsymb=shift;
1.620     albertel 1891:     unless ($env{'request.course.id'}) { return ''; }
                   1892:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1893:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1894:         $what.=':POST';
1.583     matthew  1895:         # FIXME: Probably ought to escape things....
1.800     albertel 1896: 	foreach my $key (keys(%env)) {
                   1897:             if ($key=~/^form\.(.*)/) {
                   1898: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1899:             }
1.191     harris41 1900:         }
1.583     matthew  1901:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1902:         # FIXME: We should not be depending on a form parameter that someone
                   1903:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1904:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1905:             $what.= ':POST';
                   1906:             # FIXME: Probably ought to escape things....
                   1907:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1908:                                  'crsdiscuss') {
1.620     albertel 1909:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1910:             }
                   1911:         }
1.158     www      1912:     }
                   1913:     &courselog($what);
1.149     www      1914: }
                   1915: 
1.185     www      1916: sub countacc {
                   1917:     my $url=&declutter(shift);
1.458     matthew  1918:     return if (! defined($url) || $url eq '');
1.620     albertel 1919:     unless ($env{'request.course.id'}) { return ''; }
                   1920:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1921:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1922:     $accesshash{$key}++;
1.185     www      1923: }
1.349     www      1924: 
1.361     www      1925: sub linklog {
                   1926:     my ($from,$to)=@_;
                   1927:     $from=&declutter($from);
                   1928:     $to=&declutter($to);
                   1929:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1930:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1931: }
                   1932:   
1.349     www      1933: sub userrolelog {
                   1934:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1935:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1936:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1937:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1938:         ($trole=~/^ta/)) {
1.350     www      1939:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1940:        $userrolehash
                   1941:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1942:                     =$tend.':'.$tstart;
1.662     raeburn  1943:     }
                   1944:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1945:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1946:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1947:         ($trole=~/^sc/)) {
                   1948:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1949:        $domainrolehash
                   1950:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1951:                     = $tend.':'.$tstart;
                   1952:     }
1.351     www      1953: }
                   1954: 
                   1955: sub get_course_adv_roles {
                   1956:     my $cid=shift;
1.620     albertel 1957:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1958:     my %coursehash=&coursedescription($cid);
1.470     www      1959:     my %nothide=();
1.800     albertel 1960:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1961: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      1962:     }
1.351     www      1963:     my %returnhash=();
                   1964:     my %dumphash=
                   1965:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1966:     my $now=time;
1.800     albertel 1967:     foreach my $entry (keys %dumphash) {
                   1968: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      1969:         if (($tstart) && ($tstart<0)) { next; }
                   1970:         if (($tend) && ($tend<$now)) { next; }
                   1971:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1972:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 1973: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1974: 	if ((&privileged($username,$domain)) && 
                   1975: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1976: 	if ($role eq 'cr') { next; }
1.351     www      1977:         my $key=&plaintext($role);
                   1978:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1979:         if ($returnhash{$key}) {
                   1980: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1981:         } else {
                   1982:             $returnhash{$key}=$username.':'.$domain;
                   1983:         }
1.400     www      1984:      }
                   1985:     return %returnhash;
                   1986: }
                   1987: 
                   1988: sub get_my_roles {
                   1989:     my ($uname,$udom)=@_;
1.620     albertel 1990:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1991:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1992:     my %dumphash=
                   1993:             &dump('nohist_userroles',$udom,$uname);
                   1994:     my %returnhash=();
                   1995:     my $now=time;
1.800     albertel 1996:     foreach my $entry (keys(%dumphash)) {
                   1997: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      1998:         if (($tstart) && ($tstart<0)) { next; }
                   1999:         if (($tend) && ($tend<$now)) { next; }
                   2000:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2001:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2002: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2003:      }
                   2004:     return %returnhash;
1.399     www      2005: }
                   2006: 
                   2007: # ----------------------------------------------------- Frontpage Announcements
                   2008: #
                   2009: #
                   2010: 
                   2011: sub postannounce {
                   2012:     my ($server,$text)=@_;
                   2013:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2014:     unless ($text=~/\w/) { $text=''; }
                   2015:     return &reply('setannounce:'.&escape($text),$server);
                   2016: }
                   2017: 
                   2018: sub getannounce {
1.448     albertel 2019: 
                   2020:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2021: 	my $announcement='';
1.800     albertel 2022: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2023: 	close($fh);
1.399     www      2024: 	if ($announcement=~/\w/) { 
                   2025: 	    return 
                   2026:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2027:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2028: 	} else {
                   2029: 	    return '';
                   2030: 	}
                   2031:     } else {
                   2032: 	return '';
                   2033:     }
1.351     www      2034: }
1.353     www      2035: 
                   2036: # ---------------------------------------------------------- Course ID routines
                   2037: # Deal with domain's nohist_courseid.db files
                   2038: #
                   2039: 
                   2040: sub courseidput {
                   2041:     my ($domain,$what,$coursehome)=@_;
                   2042:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2043: }
                   2044: 
                   2045: sub courseiddump {
1.791     raeburn  2046:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2047:     my %returnhash=();
1.355     www      2048:     unless ($domfilter) { $domfilter=''; }
1.353     www      2049:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2050:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2051: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2052: 	        foreach my $line (
1.506     raeburn  2053:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2054: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2055:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2056:                                $tryserver))) {
1.800     albertel 2057: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2058:                     if (($key) && ($value)) {
1.516     raeburn  2059: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2060:                     }
1.353     www      2061:                 }
                   2062:             }
                   2063:         }
                   2064:     }
                   2065:     return %returnhash;
                   2066: }
                   2067: 
1.658     raeburn  2068: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2069: 
                   2070: sub dcmailput {
1.685     raeburn  2071:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2072:     my $status = &Apache::lonnet::critical(
1.740     www      2073:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2074:        &escape($message),$server);
1.662     raeburn  2075:     return $status;
                   2076: }
                   2077: 
1.658     raeburn  2078: sub dcmaildump {
                   2079:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2080:     my %returnhash=();
                   2081:     if (exists($domain_primary{$dom})) {
                   2082:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2083:                                                          &escape($enddate).':';
                   2084: 	my @esc_senders=map { &escape($_)} @$senders;
                   2085: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2086: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2087:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2088:             if (($key) && ($value)) {
                   2089:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2090:             }
                   2091:         }
                   2092:     }
                   2093:     return %returnhash;
                   2094: }
1.662     raeburn  2095: # ---------------------------------------------------------- Domain roles
                   2096: 
                   2097: sub get_domain_roles {
                   2098:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2099:     if (undef($startdate) || $startdate eq '') {
                   2100:         $startdate = '.';
                   2101:     }
                   2102:     if (undef($enddate) || $enddate eq '') {
                   2103:         $enddate = '.';
                   2104:     }
                   2105:     my $rolelist = join(':',@{$roles});
                   2106:     my %personnel = ();
                   2107:     foreach my $tryserver (keys(%libserv)) {
                   2108:         if ($hostdom{$tryserver} eq $dom) {
                   2109:             %{$personnel{$tryserver}}=();
1.800     albertel 2110:             foreach my $line (
1.662     raeburn  2111:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2112:                    &escape($startdate).':'.&escape($enddate).':'.
                   2113:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2114:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2115:                 if (($key) && ($value)) {
                   2116:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2117:                 }
                   2118:             }
                   2119:         }
                   2120:     }
                   2121:     return %personnel;
                   2122: }
1.658     raeburn  2123: 
1.149     www      2124: # ----------------------------------------------------------- Check out an item
                   2125: 
1.504     albertel 2126: sub get_first_access {
                   2127:     my ($type,$argsymb)=@_;
1.790     albertel 2128:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2129:     if ($argsymb) { $symb=$argsymb; }
                   2130:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2131:     if ($type eq 'map') {
                   2132: 	$res=&symbread($map);
                   2133:     } else {
                   2134: 	$res=$symb;
                   2135:     }
                   2136:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2137:     return $times{"$courseid\0$res"};
1.504     albertel 2138: }
                   2139: 
                   2140: sub set_first_access {
                   2141:     my ($type)=@_;
1.790     albertel 2142:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2143:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2144:     if ($type eq 'map') {
                   2145: 	$res=&symbread($map);
                   2146:     } else {
                   2147: 	$res=$symb;
                   2148:     }
                   2149:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2150:     if (!$firstaccess) {
1.588     albertel 2151: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2152:     }
                   2153:     return 'already_set';
1.504     albertel 2154: }
                   2155: 
1.149     www      2156: sub checkout {
                   2157:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2158:     my $now=time;
                   2159:     my $lonhost=$perlvar{'lonHostID'};
                   2160:     my $infostr=&escape(
1.234     www      2161:                  'CHECKOUTTOKEN&'.
1.149     www      2162:                  $tuname.'&'.
                   2163:                  $tudom.'&'.
                   2164:                  $tcrsid.'&'.
                   2165:                  $symb.'&'.
                   2166: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2167:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2168:     if ($token=~/^error\:/) { 
1.672     albertel 2169:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2170:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2171:                  "</font>");
                   2172:         return ''; 
                   2173:     }
                   2174: 
1.149     www      2175:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2176:     $token=~tr/a-z/A-Z/;
                   2177: 
1.153     www      2178:     my %infohash=('resource.0.outtoken' => $token,
                   2179:                   'resource.0.checkouttime' => $now,
                   2180:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2181: 
                   2182:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2183:        return '';
1.151     www      2184:     } else {
1.672     albertel 2185:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2186:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2187:                  "</font>");
1.149     www      2188:     }    
                   2189: 
                   2190:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2191:                          &escape('Checkout '.$infostr.' - '.
                   2192:                                                  $token)) ne 'ok') {
                   2193: 	return '';
1.151     www      2194:     } else {
1.672     albertel 2195:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2196:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2197:                  "</font>");
1.149     www      2198:     }
1.151     www      2199:     return $token;
1.149     www      2200: }
                   2201: 
                   2202: # ------------------------------------------------------------ Check in an item
                   2203: 
                   2204: sub checkin {
                   2205:     my $token=shift;
1.150     www      2206:     my $now=time;
                   2207:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2208:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2209:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2210:     $dtoken=~s/\W/\_/g;
1.234     www      2211:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2212:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2213: 
1.154     www      2214:     unless (($tuname) && ($tudom)) {
                   2215:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2216:         return '';
                   2217:     }
                   2218:     
                   2219:     unless (&allowed('mgr',$tcrsid)) {
                   2220:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2221:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2222:         return '';
                   2223:     }
                   2224: 
1.153     www      2225:     my %infohash=('resource.0.intoken' => $token,
                   2226:                   'resource.0.checkintime' => $now,
                   2227:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2228: 
                   2229:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2230:        return '';
                   2231:     }    
                   2232: 
                   2233:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2234:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2235: 	return '';
                   2236:     }
                   2237: 
                   2238:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2239: }
                   2240: 
                   2241: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2242: 
                   2243: sub expirespread {
                   2244:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2245:     my $cid=$env{'request.course.id'}; 
1.110     www      2246:     if ($cid) {
                   2247:        my $now=time;
                   2248:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2249:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2250:                             $env{'course.'.$cid.'.num'}.
1.110     www      2251: 	        	    ':nohist_expirationdates:'.
                   2252:                             &escape($key).'='.$now,
1.620     albertel 2253:                             $env{'course.'.$cid.'.home'})
1.110     www      2254:     }
                   2255:     return 'ok';
1.14      www      2256: }
                   2257: 
1.109     www      2258: # ----------------------------------------------------- Devalidate Spreadsheets
                   2259: 
                   2260: sub devalidate {
1.325     www      2261:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2262:     my $cid=$env{'request.course.id'}; 
1.109     www      2263:     if ($cid) {
1.391     matthew  2264:         # delete the stored spreadsheets for
                   2265:         # - the student level sheet of this user in course's homespace
                   2266:         # - the assessment level sheet for this resource 
                   2267:         #   for this user in user's homespace
1.553     albertel 2268: 	# - current conditional state info
1.325     www      2269: 	my $key=$uname.':'.$udom.':';
1.109     www      2270:         my $status=
1.299     matthew  2271: 	    &del('nohist_calculatedsheets',
1.391     matthew  2272: 		 [$key.'studentcalc:'],
1.620     albertel 2273: 		 $env{'course.'.$cid.'.domain'},
                   2274: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2275: 		.' '.
                   2276: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2277: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2278:         unless ($status eq 'ok ok') {
                   2279:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2280:                     $uname.' at '.$udom.' for '.
1.109     www      2281: 		    $symb.': '.$status);
1.133     albertel 2282:         }
1.553     albertel 2283: 	&delenv('user.state.'.$cid);
1.109     www      2284:     }
                   2285: }
                   2286: 
1.265     albertel 2287: sub get_scalar {
                   2288:     my ($string,$end) = @_;
                   2289:     my $value;
                   2290:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2291: 	$value = $1;
                   2292:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2293: 	$value = $1;
                   2294:     }
                   2295:     return &unescape($value);
                   2296: }
                   2297: 
                   2298: sub array2str {
                   2299:   my (@array) = @_;
                   2300:   my $result=&arrayref2str(\@array);
                   2301:   $result=~s/^__ARRAY_REF__//;
                   2302:   $result=~s/__END_ARRAY_REF__$//;
                   2303:   return $result;
                   2304: }
                   2305: 
1.204     albertel 2306: sub arrayref2str {
                   2307:   my ($arrayref) = @_;
1.265     albertel 2308:   my $result='__ARRAY_REF__';
1.204     albertel 2309:   foreach my $elem (@$arrayref) {
1.265     albertel 2310:     if(ref($elem) eq 'ARRAY') {
                   2311:       $result.=&arrayref2str($elem).'&';
                   2312:     } elsif(ref($elem) eq 'HASH') {
                   2313:       $result.=&hashref2str($elem).'&';
                   2314:     } elsif(ref($elem)) {
                   2315:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2316:     } else {
                   2317:       $result.=&escape($elem).'&';
                   2318:     }
                   2319:   }
                   2320:   $result=~s/\&$//;
1.265     albertel 2321:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2322:   return $result;
                   2323: }
                   2324: 
1.168     albertel 2325: sub hash2str {
1.204     albertel 2326:   my (%hash) = @_;
                   2327:   my $result=&hashref2str(\%hash);
1.265     albertel 2328:   $result=~s/^__HASH_REF__//;
                   2329:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2330:   return $result;
                   2331: }
                   2332: 
                   2333: sub hashref2str {
                   2334:   my ($hashref)=@_;
1.265     albertel 2335:   my $result='__HASH_REF__';
1.800     albertel 2336:   foreach my $key (sort(keys(%$hashref))) {
                   2337:     if (ref($key) eq 'ARRAY') {
                   2338:       $result.=&arrayref2str($key).'=';
                   2339:     } elsif (ref($key) eq 'HASH') {
                   2340:       $result.=&hashref2str($key).'=';
                   2341:     } elsif (ref($key)) {
1.265     albertel 2342:       $result.='=';
1.800     albertel 2343:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2344:     } else {
1.800     albertel 2345: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2346:     }
                   2347: 
1.800     albertel 2348:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2349:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2350:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2351:       $result.=&hashref2str($hashref->{$key}).'&';
                   2352:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2353:        $result.='&';
1.800     albertel 2354:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2355:     } else {
1.800     albertel 2356:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2357:     }
                   2358:   }
1.168     albertel 2359:   $result=~s/\&$//;
1.265     albertel 2360:   $result .= '__END_HASH_REF__';
1.168     albertel 2361:   return $result;
                   2362: }
                   2363: 
                   2364: sub str2hash {
1.265     albertel 2365:     my ($string)=@_;
                   2366:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2367:     return %$hash;
                   2368: }
                   2369: 
                   2370: sub str2hashref {
1.168     albertel 2371:   my ($string) = @_;
1.265     albertel 2372: 
                   2373:   my %hash;
                   2374: 
                   2375:   if($string !~ /^__HASH_REF__/) {
                   2376:       if (! ($string eq '' || !defined($string))) {
                   2377: 	  $hash{'error'}='Not hash reference';
                   2378:       }
                   2379:       return (\%hash, $string);
                   2380:   }
                   2381: 
                   2382:   $string =~ s/^__HASH_REF__//;
                   2383: 
                   2384:   while($string !~ /^__END_HASH_REF__/) {
                   2385:       #key
                   2386:       my $key='';
                   2387:       if($string =~ /^__HASH_REF__/) {
                   2388:           ($key, $string)=&str2hashref($string);
                   2389:           if(defined($key->{'error'})) {
                   2390:               $hash{'error'}='Bad data';
                   2391:               return (\%hash, $string);
                   2392:           }
                   2393:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2394:           ($key, $string)=&str2arrayref($string);
                   2395:           if($key->[0] eq 'Array reference error') {
                   2396:               $hash{'error'}='Bad data';
                   2397:               return (\%hash, $string);
                   2398:           }
                   2399:       } else {
                   2400:           $string =~ s/^(.*?)=//;
1.267     albertel 2401: 	  $key=&unescape($1);
1.265     albertel 2402:       }
                   2403:       $string =~ s/^=//;
                   2404: 
                   2405:       #value
                   2406:       my $value='';
                   2407:       if($string =~ /^__HASH_REF__/) {
                   2408:           ($value, $string)=&str2hashref($string);
                   2409:           if(defined($value->{'error'})) {
                   2410:               $hash{'error'}='Bad data';
                   2411:               return (\%hash, $string);
                   2412:           }
                   2413:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2414:           ($value, $string)=&str2arrayref($string);
                   2415:           if($value->[0] eq 'Array reference error') {
                   2416:               $hash{'error'}='Bad data';
                   2417:               return (\%hash, $string);
                   2418:           }
                   2419:       } else {
                   2420: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2421:       }
                   2422:       $string =~ s/^&//;
                   2423: 
                   2424:       $hash{$key}=$value;
1.204     albertel 2425:   }
1.265     albertel 2426: 
                   2427:   $string =~ s/^__END_HASH_REF__//;
                   2428: 
                   2429:   return (\%hash, $string);
1.204     albertel 2430: }
                   2431: 
                   2432: sub str2array {
1.265     albertel 2433:     my ($string)=@_;
                   2434:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2435:     return @$array;
                   2436: }
                   2437: 
                   2438: sub str2arrayref {
1.204     albertel 2439:   my ($string) = @_;
1.265     albertel 2440:   my @array;
                   2441: 
                   2442:   if($string !~ /^__ARRAY_REF__/) {
                   2443:       if (! ($string eq '' || !defined($string))) {
                   2444: 	  $array[0]='Array reference error';
                   2445:       }
                   2446:       return (\@array, $string);
                   2447:   }
                   2448: 
                   2449:   $string =~ s/^__ARRAY_REF__//;
                   2450: 
                   2451:   while($string !~ /^__END_ARRAY_REF__/) {
                   2452:       my $value='';
                   2453:       if($string =~ /^__HASH_REF__/) {
                   2454:           ($value, $string)=&str2hashref($string);
                   2455:           if(defined($value->{'error'})) {
                   2456:               $array[0] ='Array reference error';
                   2457:               return (\@array, $string);
                   2458:           }
                   2459:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2460:           ($value, $string)=&str2arrayref($string);
                   2461:           if($value->[0] eq 'Array reference error') {
                   2462:               $array[0] ='Array reference error';
                   2463:               return (\@array, $string);
                   2464:           }
                   2465:       } else {
                   2466: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2467:       }
                   2468:       $string =~ s/^&//;
                   2469: 
                   2470:       push(@array, $value);
1.191     harris41 2471:   }
1.265     albertel 2472: 
                   2473:   $string =~ s/^__END_ARRAY_REF__//;
                   2474: 
                   2475:   return (\@array, $string);
1.168     albertel 2476: }
                   2477: 
1.167     albertel 2478: # -------------------------------------------------------------------Temp Store
                   2479: 
1.168     albertel 2480: sub tmpreset {
                   2481:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2482:   if (!$symb) {
                   2483:     $symb=&symbread();
1.620     albertel 2484:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2485:   }
                   2486:   $symb=escape($symb);
                   2487: 
1.620     albertel 2488:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2489:   $namespace=~s/\//\_/g;
                   2490:   $namespace=~s/\W//g;
                   2491: 
1.620     albertel 2492:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2493:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2494:   if ($domain eq 'public' && $stuname eq 'public') {
                   2495:       $stuname=$ENV{'REMOTE_ADDR'};
                   2496:   }
1.168     albertel 2497:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2498:   my %hash;
                   2499:   if (tie(%hash,'GDBM_File',
                   2500: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2501: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2502:     foreach my $key (keys %hash) {
1.180     albertel 2503:       if ($key=~ /:$symb/) {
1.168     albertel 2504: 	delete($hash{$key});
                   2505:       }
                   2506:     }
                   2507:   }
                   2508: }
                   2509: 
1.167     albertel 2510: sub tmpstore {
1.168     albertel 2511:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2512: 
                   2513:   if (!$symb) {
                   2514:     $symb=&symbread();
1.620     albertel 2515:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2516:   }
                   2517:   $symb=escape($symb);
                   2518: 
                   2519:   if (!$namespace) {
                   2520:     # I don't think we would ever want to store this for a course.
                   2521:     # it seems this will only be used if we don't have a course.
1.620     albertel 2522:     #$namespace=$env{'request.course.id'};
1.168     albertel 2523:     #if (!$namespace) {
1.620     albertel 2524:       $namespace=$env{'request.state'};
1.168     albertel 2525:     #}
                   2526:   }
                   2527:   $namespace=~s/\//\_/g;
                   2528:   $namespace=~s/\W//g;
1.620     albertel 2529:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2530:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2531:   if ($domain eq 'public' && $stuname eq 'public') {
                   2532:       $stuname=$ENV{'REMOTE_ADDR'};
                   2533:   }
1.168     albertel 2534:   my $now=time;
                   2535:   my %hash;
                   2536:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2537:   if (tie(%hash,'GDBM_File',
                   2538: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2539: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2540:     $hash{"version:$symb"}++;
                   2541:     my $version=$hash{"version:$symb"};
                   2542:     my $allkeys=''; 
                   2543:     foreach my $key (keys(%$storehash)) {
                   2544:       $allkeys.=$key.':';
1.591     albertel 2545:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2546:     }
                   2547:     $hash{"$version:$symb:timestamp"}=$now;
                   2548:     $allkeys.='timestamp';
                   2549:     $hash{"$version:keys:$symb"}=$allkeys;
                   2550:     if (untie(%hash)) {
                   2551:       return 'ok';
                   2552:     } else {
                   2553:       return "error:$!";
                   2554:     }
                   2555:   } else {
                   2556:     return "error:$!";
                   2557:   }
                   2558: }
1.167     albertel 2559: 
1.168     albertel 2560: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2561: 
1.168     albertel 2562: sub tmprestore {
                   2563:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2564: 
1.168     albertel 2565:   if (!$symb) {
                   2566:     $symb=&symbread();
1.620     albertel 2567:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2568:   }
                   2569:   $symb=escape($symb);
                   2570: 
1.620     albertel 2571:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2572: 
1.620     albertel 2573:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2574:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2575:   if ($domain eq 'public' && $stuname eq 'public') {
                   2576:       $stuname=$ENV{'REMOTE_ADDR'};
                   2577:   }
1.168     albertel 2578:   my %returnhash;
                   2579:   $namespace=~s/\//\_/g;
                   2580:   $namespace=~s/\W//g;
                   2581:   my %hash;
                   2582:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2583:   if (tie(%hash,'GDBM_File',
                   2584: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2585: 	  &GDBM_READER(),0640)) {
1.168     albertel 2586:     my $version=$hash{"version:$symb"};
                   2587:     $returnhash{'version'}=$version;
                   2588:     my $scope;
                   2589:     for ($scope=1;$scope<=$version;$scope++) {
                   2590:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2591:       my @keys=split(/:/,$vkeys);
                   2592:       my $key;
                   2593:       $returnhash{"$scope:keys"}=$vkeys;
                   2594:       foreach $key (@keys) {
1.591     albertel 2595: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2596: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2597:       }
                   2598:     }
1.168     albertel 2599:     if (!(untie(%hash))) {
                   2600:       return "error:$!";
                   2601:     }
                   2602:   } else {
                   2603:     return "error:$!";
                   2604:   }
                   2605:   return %returnhash;
1.167     albertel 2606: }
                   2607: 
1.9       www      2608: # ----------------------------------------------------------------------- Store
                   2609: 
                   2610: sub store {
1.124     www      2611:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2612:     my $home='';
                   2613: 
1.168     albertel 2614:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2615: 
1.213     www      2616:     $symb=&symbclean($symb);
1.122     albertel 2617:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2618: 
1.620     albertel 2619:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2620:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2621: 
                   2622:     &devalidate($symb,$stuname,$domain);
1.109     www      2623: 
                   2624:     $symb=escape($symb);
1.187     www      2625:     if (!$namespace) { 
1.620     albertel 2626:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2627:           return ''; 
                   2628:        } 
                   2629:     }
1.620     albertel 2630:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2631: 
                   2632:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2633:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2634: 
1.12      www      2635:     my $namevalue='';
1.800     albertel 2636:     foreach my $key (keys(%$storehash)) {
                   2637:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2638:     }
1.12      www      2639:     $namevalue=~s/\&$//;
1.187     www      2640:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2641:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2642: }
                   2643: 
1.47      www      2644: # -------------------------------------------------------------- Critical Store
                   2645: 
                   2646: sub cstore {
1.124     www      2647:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2648:     my $home='';
                   2649: 
1.168     albertel 2650:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2651: 
1.213     www      2652:     $symb=&symbclean($symb);
1.122     albertel 2653:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2654: 
1.620     albertel 2655:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2656:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2657: 
                   2658:     &devalidate($symb,$stuname,$domain);
1.109     www      2659: 
                   2660:     $symb=escape($symb);
1.187     www      2661:     if (!$namespace) { 
1.620     albertel 2662:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2663:           return ''; 
                   2664:        } 
                   2665:     }
1.620     albertel 2666:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2667: 
                   2668:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2669:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2670: 
1.47      www      2671:     my $namevalue='';
1.800     albertel 2672:     foreach my $key (keys(%$storehash)) {
                   2673:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2674:     }
1.47      www      2675:     $namevalue=~s/\&$//;
1.187     www      2676:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2677:     return critical
                   2678:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2679: }
                   2680: 
1.9       www      2681: # --------------------------------------------------------------------- Restore
                   2682: 
                   2683: sub restore {
1.124     www      2684:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2685:     my $home='';
                   2686: 
1.168     albertel 2687:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2688: 
1.122     albertel 2689:     if (!$symb) {
                   2690:       unless ($symb=escape(&symbread())) { return ''; }
                   2691:     } else {
1.213     www      2692:       $symb=&escape(&symbclean($symb));
1.122     albertel 2693:     }
1.188     www      2694:     if (!$namespace) { 
1.620     albertel 2695:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2696:           return ''; 
                   2697:        } 
                   2698:     }
1.620     albertel 2699:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2700:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2701:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2702:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2703: 
1.12      www      2704:     my %returnhash=();
1.800     albertel 2705:     foreach my $line (split(/\&/,$answer)) {
                   2706: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2707:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2708:     }
1.75      www      2709:     my $version;
                   2710:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2711:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2712:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2713:        }
1.75      www      2714:     }
1.13      www      2715:     return %returnhash;
1.34      www      2716: }
                   2717: 
                   2718: # ---------------------------------------------------------- Course Description
                   2719: 
                   2720: sub coursedescription {
1.731     albertel 2721:     my ($courseid,$args)=@_;
1.34      www      2722:     $courseid=~s/^\///;
1.49      www      2723:     $courseid=~s/\_/\//g;
1.34      www      2724:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2725:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2726:     my $normalid=$cdomain.'_'.$cnum;
                   2727:     # need to always cache even if we get errors otherwise we keep 
                   2728:     # trying and trying and trying to get the course description.
                   2729:     my %envhash=();
                   2730:     my %returnhash=();
1.731     albertel 2731:     
                   2732:     my $expiretime=600;
                   2733:     if ($env{'request.course.id'} eq $normalid) {
                   2734: 	$expiretime=120;
                   2735:     }
                   2736: 
                   2737:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2738:     if (!$args->{'freshen_cache'}
                   2739: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2740: 	foreach my $key (keys(%env)) {
                   2741: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2742: 	    my ($setting) = $1;
                   2743: 	    $returnhash{$setting} = $env{$key};
                   2744: 	}
                   2745: 	return %returnhash;
                   2746:     }
                   2747: 
                   2748:     # get the data agin
                   2749:     if (!$args->{'one_time'}) {
                   2750: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2751:     }
1.811     albertel 2752: 
1.34      www      2753:     if ($chome ne 'no_host') {
1.302     albertel 2754:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2755:        if (!exists($returnhash{'con_lost'})) {
                   2756:            $returnhash{'home'}= $chome;
                   2757: 	   $returnhash{'domain'} = $cdomain;
                   2758: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2759:            if (!defined($returnhash{'type'})) {
                   2760:                $returnhash{'type'} = 'Course';
                   2761:            }
1.130     albertel 2762:            while (my ($name,$value) = each %returnhash) {
1.53      www      2763:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2764:            }
1.270     www      2765:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2766:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2767: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2768:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2769:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2770:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2771:        }
                   2772:     }
1.731     albertel 2773:     if (!$args->{'one_time'}) {
                   2774: 	&appenv(%envhash);
                   2775:     }
1.302     albertel 2776:     return %returnhash;
1.461     www      2777: }
                   2778: 
                   2779: # -------------------------------------------------See if a user is privileged
                   2780: 
                   2781: sub privileged {
                   2782:     my ($username,$domain)=@_;
                   2783:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2784: 			&homeserver($username,$domain));
                   2785:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2786:     my $now=time;
                   2787:     if ($rolesdump ne '') {
1.800     albertel 2788:         foreach my $entry (split(/&/,$rolesdump)) {
                   2789: 	    if ($entry!~/^rolesdef_/) {
                   2790: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2791: 		$area=~s/\_\w\w$//;
                   2792: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2793: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2794: 		    my $active=1;
                   2795: 		    if ($tend) {
                   2796: 			if ($tend<$now) { $active=0; }
                   2797: 		    }
                   2798: 		    if ($tstart) {
                   2799: 			if ($tstart>$now) { $active=0; }
                   2800: 		    }
                   2801: 		    if ($active) { return 1; }
                   2802: 		}
                   2803: 	    }
                   2804: 	}
                   2805:     }
                   2806:     return 0;
1.9       www      2807: }
1.1       albertel 2808: 
1.103     harris41 2809: # -------------------------------------------------------- Get user privileges
1.11      www      2810: 
                   2811: sub rolesinit {
                   2812:     my ($domain,$username,$authhost)=@_;
                   2813:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2814:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2815:     my %allroles=();
1.678     raeburn  2816:     my %allgroups=();   
1.11      www      2817:     my $now=time;
1.743     albertel 2818:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2819:     my $group_privs;
1.11      www      2820: 
                   2821:     if ($rolesdump ne '') {
1.800     albertel 2822:         foreach my $entry (split(/&/,$rolesdump)) {
                   2823: 	  if ($entry!~/^rolesdef_/) {
                   2824:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2825: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2826:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2827: 	    if ($role=~/^cr/) { 
1.807     albertel 2828: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2829: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2830: 		    ($tend,$tstart)=split('_',$trest);
                   2831: 		} else {
                   2832: 		    $trole=$role;
                   2833: 		}
1.678     raeburn  2834:             } elsif ($role =~ m|^gr/|) {
                   2835:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2836:                 ($trole,$group_privs) = split(/\//,$trole);
                   2837:                 $group_privs = &unescape($group_privs);
1.587     albertel 2838: 	    } else {
                   2839: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2840: 	    }
1.743     albertel 2841: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2842: 					 $username);
                   2843: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2844:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2845:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2846:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2847: 		my $spec=$trole.'.'.$area;
                   2848: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2849: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2850:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2851:                 } elsif ($trole eq 'gr') {
                   2852:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2853: 		} else {
1.567     raeburn  2854:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2855: 		}
1.12      www      2856:             }
1.662     raeburn  2857:           }
1.191     harris41 2858:         }
1.743     albertel 2859:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2860:         $userroles{'user.adv'}    = $adv;
                   2861: 	$userroles{'user.author'} = $author;
1.620     albertel 2862:         $env{'user.adv'}=$adv;
1.11      www      2863:     }
1.743     albertel 2864:     return \%userroles;  
1.11      www      2865: }
                   2866: 
1.567     raeburn  2867: sub set_arearole {
                   2868:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2869: # log the associated role with the area
                   2870:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2871:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2872: }
                   2873: 
                   2874: sub custom_roleprivs {
                   2875:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2876:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2877:     my $homsvr=homeserver($rauthor,$rdomain);
                   2878:     if ($hostname{$homsvr} ne '') {
                   2879:         my ($rdummy,$roledef)=
                   2880:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2881:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2882:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2883:             if (defined($syspriv)) {
                   2884:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2885:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2886:             }
                   2887:             if ($tdomain ne '') {
                   2888:                 if (defined($dompriv)) {
                   2889:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2890:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2891:                 }
                   2892:                 if (($trest ne '') && (defined($coursepriv))) {
                   2893:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2894:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2895:                 }
                   2896:             }
                   2897:         }
                   2898:     }
                   2899: }
                   2900: 
1.678     raeburn  2901: sub group_roleprivs {
                   2902:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2903:     my $access = 1;
                   2904:     my $now = time;
                   2905:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2906:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2907:     if ($access) {
1.811     albertel 2908:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2909:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2910:     }
                   2911: }
1.567     raeburn  2912: 
                   2913: sub standard_roleprivs {
                   2914:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2915:     if (defined($pr{$trole.':s'})) {
                   2916:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2917:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2918:     }
                   2919:     if ($tdomain ne '') {
                   2920:         if (defined($pr{$trole.':d'})) {
                   2921:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2922:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2923:         }
                   2924:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2925:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2926:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2927:         }
                   2928:     }
                   2929: }
                   2930: 
                   2931: sub set_userprivs {
1.678     raeburn  2932:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2933:     my $author=0;
                   2934:     my $adv=0;
1.678     raeburn  2935:     my %grouproles = ();
                   2936:     if (keys(%{$allgroups}) > 0) {
                   2937:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2938:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2939:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2940:                 $trole = $1;
                   2941:                 $area = $2;
1.681     raeburn  2942:                 $sec = $3;
                   2943:                 $extendedarea = $area.$sec;
                   2944:                 if (exists($$allgroups{$area})) {
                   2945:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2946:                         my $spec = $trole.'.'.$extendedarea;
                   2947:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2948:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2949:                     }
                   2950:                 }
                   2951:             }
                   2952:         }
                   2953:     }
1.800     albertel 2954:     foreach my $group (keys(%grouproles)) {
                   2955:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2956:     }
1.800     albertel 2957:     foreach my $role (keys(%{$allroles})) {
                   2958:         my %thesepriv;
                   2959:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   2960:         foreach my $item (split(/:/,$$allroles{$role})) {
                   2961:             if ($item ne '') {
                   2962:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  2963:                 if ($restrictions eq '') {
                   2964:                     $thesepriv{$privilege}='F';
                   2965:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2966:                     $thesepriv{$privilege}.=$restrictions;
                   2967:                 }
                   2968:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2969:             }
                   2970:         }
                   2971:         my $thesestr='';
1.800     albertel 2972:         foreach my $priv (keys(%thesepriv)) {
                   2973: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   2974: 	}
                   2975:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  2976:     }
                   2977:     return ($author,$adv);
                   2978: }
                   2979: 
1.12      www      2980: # --------------------------------------------------------------- get interface
                   2981: 
                   2982: sub get {
1.131     albertel 2983:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2984:    my $items='';
1.800     albertel 2985:    foreach my $item (@$storearr) {
                   2986:        $items.=&escape($item).'&';
1.191     harris41 2987:    }
1.12      www      2988:    $items=~s/\&$//;
1.620     albertel 2989:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2990:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2991:    my $uhome=&homeserver($uname,$udomain);
                   2992: 
1.133     albertel 2993:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2994:    my @pairs=split(/\&/,$rep);
1.273     albertel 2995:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2996:      return @pairs;
                   2997:    }
1.15      www      2998:    my %returnhash=();
1.42      www      2999:    my $i=0;
1.800     albertel 3000:    foreach my $item (@$storearr) {
                   3001:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3002:       $i++;
1.191     harris41 3003:    }
1.15      www      3004:    return %returnhash;
1.27      www      3005: }
                   3006: 
                   3007: # --------------------------------------------------------------- del interface
                   3008: 
                   3009: sub del {
1.133     albertel 3010:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3011:    my $items='';
1.800     albertel 3012:    foreach my $item (@$storearr) {
                   3013:        $items.=&escape($item).'&';
1.191     harris41 3014:    }
1.27      www      3015:    $items=~s/\&$//;
1.620     albertel 3016:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3017:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3018:    my $uhome=&homeserver($uname,$udomain);
                   3019: 
                   3020:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3021: }
                   3022: 
                   3023: # -------------------------------------------------------------- dump interface
                   3024: 
                   3025: sub dump {
1.755     albertel 3026:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3027:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3028:     if (!$uname) { $uname=$env{'user.name'}; }
                   3029:     my $uhome=&homeserver($uname,$udomain);
                   3030:     if ($regexp) {
                   3031: 	$regexp=&escape($regexp);
                   3032:     } else {
                   3033: 	$regexp='.';
                   3034:     }
                   3035:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3036:     my @pairs=split(/\&/,$rep);
                   3037:     my %returnhash=();
                   3038:     foreach my $item (@pairs) {
                   3039: 	my ($key,$value)=split(/=/,$item,2);
                   3040: 	$key = &unescape($key);
                   3041: 	next if ($key =~ /^error: 2 /);
                   3042: 	$returnhash{$key}=&thaw_unescape($value);
                   3043:     }
                   3044:     return %returnhash;
1.407     www      3045: }
                   3046: 
1.717     albertel 3047: # --------------------------------------------------------- dumpstore interface
                   3048: 
                   3049: sub dumpstore {
                   3050:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3051:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   3052: }
                   3053: 
1.407     www      3054: # -------------------------------------------------------------- keys interface
                   3055: 
                   3056: sub getkeys {
                   3057:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3058:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3059:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3060:    my $uhome=&homeserver($uname,$udomain);
                   3061:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3062:    my @keyarray=();
1.800     albertel 3063:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3064:       next if ($key =~ /^error: 2 /);
1.800     albertel 3065:       push(@keyarray,&unescape($key));
1.407     www      3066:    }
                   3067:    return @keyarray;
1.318     matthew  3068: }
                   3069: 
1.319     matthew  3070: # --------------------------------------------------------------- currentdump
                   3071: sub currentdump {
1.328     matthew  3072:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3073:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3074:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3075:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3076:    my $uhome = &homeserver($sname,$sdom);
                   3077:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3078:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3079:    #
1.318     matthew  3080:    my %returnhash=();
1.319     matthew  3081:    #
                   3082:    if ($rep eq "unknown_cmd") { 
                   3083:        # an old lond will not know currentdump
                   3084:        # Do a dump and make it look like a currentdump
1.326     matthew  3085:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3086:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3087:        my %hash = @tmp;
                   3088:        @tmp=();
1.424     matthew  3089:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3090:    } else {
                   3091:        my @pairs=split(/\&/,$rep);
1.800     albertel 3092:        foreach my $pair (@pairs) {
                   3093:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3094:            my ($symb,$param) = split(/:/,$key);
                   3095:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3096:                                                         &thaw_unescape($value);
1.319     matthew  3097:        }
1.191     harris41 3098:    }
1.12      www      3099:    return %returnhash;
1.424     matthew  3100: }
                   3101: 
                   3102: sub convert_dump_to_currentdump{
                   3103:     my %hash = %{shift()};
                   3104:     my %returnhash;
                   3105:     # Code ripped from lond, essentially.  The only difference
                   3106:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3107:     # we might run in to problems with parameter names =~ /^v\./
                   3108:     while (my ($key,$value) = each(%hash)) {
                   3109:         my ($v,$symb,$param) = split(/:/,$key);
                   3110:         next if ($v eq 'version' || $symb eq 'keys');
                   3111:         next if (exists($returnhash{$symb}) &&
                   3112:                  exists($returnhash{$symb}->{$param}) &&
                   3113:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3114:         $returnhash{$symb}->{$param}=$value;
                   3115:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3116:     }
                   3117:     #
                   3118:     # Remove all of the keys in the hashes which keep track of
                   3119:     # the version of the parameter.
                   3120:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3121:         # use a foreach because we are going to delete from the hash.
                   3122:         foreach my $key (keys(%$param_hash)) {
                   3123:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3124:         }
                   3125:     }
                   3126:     return \%returnhash;
1.12      www      3127: }
                   3128: 
1.627     albertel 3129: # ------------------------------------------------------ critical inc interface
                   3130: 
                   3131: sub cinc {
                   3132:     return &inc(@_,'critical');
                   3133: }
                   3134: 
1.449     matthew  3135: # --------------------------------------------------------------- inc interface
                   3136: 
                   3137: sub inc {
1.627     albertel 3138:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3139:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3140:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3141:     my $uhome=&homeserver($uname,$udomain);
                   3142:     my $items='';
                   3143:     if (! ref($store)) {
                   3144:         # got a single value, so use that instead
                   3145:         $items = &escape($store).'=&';
                   3146:     } elsif (ref($store) eq 'SCALAR') {
                   3147:         $items = &escape($$store).'=&';        
                   3148:     } elsif (ref($store) eq 'ARRAY') {
                   3149:         $items = join('=&',map {&escape($_);} @{$store});
                   3150:     } elsif (ref($store) eq 'HASH') {
                   3151:         while (my($key,$value) = each(%{$store})) {
                   3152:             $items.= &escape($key).'='.&escape($value).'&';
                   3153:         }
                   3154:     }
                   3155:     $items=~s/\&$//;
1.627     albertel 3156:     if ($critical) {
                   3157: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3158:     } else {
                   3159: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3160:     }
1.449     matthew  3161: }
                   3162: 
1.12      www      3163: # --------------------------------------------------------------- put interface
                   3164: 
                   3165: sub put {
1.134     albertel 3166:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3167:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3168:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3169:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3170:    my $items='';
1.800     albertel 3171:    foreach my $item (keys(%$storehash)) {
                   3172:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3173:    }
1.12      www      3174:    $items=~s/\&$//;
1.134     albertel 3175:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3176: }
                   3177: 
1.631     albertel 3178: # ------------------------------------------------------------ newput interface
                   3179: 
                   3180: sub newput {
                   3181:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3182:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3183:    if (!$uname) { $uname=$env{'user.name'}; }
                   3184:    my $uhome=&homeserver($uname,$udomain);
                   3185:    my $items='';
                   3186:    foreach my $key (keys(%$storehash)) {
                   3187:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3188:    }
                   3189:    $items=~s/\&$//;
                   3190:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3191: }
                   3192: 
                   3193: # ---------------------------------------------------------  putstore interface
                   3194: 
1.524     raeburn  3195: sub putstore {
1.715     albertel 3196:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3197:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3198:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3199:    my $uhome=&homeserver($uname,$udomain);
                   3200:    my $items='';
1.715     albertel 3201:    foreach my $key (keys(%$storehash)) {
                   3202:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3203:    }
1.715     albertel 3204:    $items=~s/\&$//;
1.716     albertel 3205:    my $esc_symb=&escape($symb);
                   3206:    my $esc_v=&escape($version);
1.715     albertel 3207:    my $reply =
1.716     albertel 3208:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3209: 	      $uhome);
                   3210:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3211:        # gfall back to way things use to be done
1.715     albertel 3212:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3213: 			    $uname);
1.524     raeburn  3214:    }
1.715     albertel 3215:    return $reply;
                   3216: }
                   3217: 
                   3218: sub old_putstore {
1.716     albertel 3219:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3220:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3221:     if (!$uname) { $uname=$env{'user.name'}; }
                   3222:     my $uhome=&homeserver($uname,$udomain);
                   3223:     my %newstorehash;
1.800     albertel 3224:     foreach my $item (keys(%$storehash)) {
                   3225: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3226: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3227:     }
                   3228:     my $items='';
                   3229:     my %allitems = ();
1.800     albertel 3230:     foreach my $item (keys(%newstorehash)) {
                   3231: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3232: 	    my $key = $1.':keys:'.$2;
                   3233: 	    $allitems{$key} .= $3.':';
                   3234: 	}
1.800     albertel 3235: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3236:     }
1.800     albertel 3237:     foreach my $item (keys(%allitems)) {
                   3238: 	$allitems{$item} =~ s/\:$//;
                   3239: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3240:     }
                   3241:     $items=~s/\&$//;
                   3242:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3243: }
                   3244: 
1.47      www      3245: # ------------------------------------------------------ critical put interface
                   3246: 
                   3247: sub cput {
1.134     albertel 3248:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3249:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3250:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3251:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3252:    my $items='';
1.800     albertel 3253:    foreach my $item (keys(%$storehash)) {
                   3254:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3255:    }
1.47      www      3256:    $items=~s/\&$//;
1.134     albertel 3257:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3258: }
                   3259: 
                   3260: # -------------------------------------------------------------- eget interface
                   3261: 
                   3262: sub eget {
1.133     albertel 3263:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3264:    my $items='';
1.800     albertel 3265:    foreach my $item (@$storearr) {
                   3266:        $items.=&escape($item).'&';
1.191     harris41 3267:    }
1.12      www      3268:    $items=~s/\&$//;
1.620     albertel 3269:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3270:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3271:    my $uhome=&homeserver($uname,$udomain);
                   3272:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3273:    my @pairs=split(/\&/,$rep);
                   3274:    my %returnhash=();
1.42      www      3275:    my $i=0;
1.800     albertel 3276:    foreach my $item (@$storearr) {
                   3277:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3278:       $i++;
1.191     harris41 3279:    }
1.12      www      3280:    return %returnhash;
                   3281: }
                   3282: 
1.667     albertel 3283: # ------------------------------------------------------------ tmpput interface
                   3284: sub tmpput {
1.802     raeburn  3285:     my ($storehash,$server,$context)=@_;
1.667     albertel 3286:     my $items='';
1.800     albertel 3287:     foreach my $item (keys(%$storehash)) {
                   3288: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3289:     }
                   3290:     $items=~s/\&$//;
1.802     raeburn  3291:     if (defined($context)) {
                   3292:         $items .= ':'.&escape($context);
                   3293:     }
1.667     albertel 3294:     return &reply("tmpput:$items",$server);
                   3295: }
                   3296: 
                   3297: # ------------------------------------------------------------ tmpget interface
                   3298: sub tmpget {
1.688     albertel 3299:     my ($token,$server)=@_;
                   3300:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3301:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3302:     my %returnhash;
                   3303:     foreach my $item (split(/\&/,$rep)) {
                   3304: 	my ($key,$value)=split(/=/,$item);
                   3305: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3306:     }
                   3307:     return %returnhash;
                   3308: }
                   3309: 
1.688     albertel 3310: # ------------------------------------------------------------ tmpget interface
                   3311: sub tmpdel {
                   3312:     my ($token,$server)=@_;
                   3313:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3314:     return &reply("tmpdel:$token",$server);
                   3315: }
                   3316: 
1.765     albertel 3317: # -------------------------------------------------- portfolio access checking
                   3318: 
                   3319: sub portfolio_access {
1.766     albertel 3320:     my ($requrl) = @_;
1.765     albertel 3321:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3322:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3323:     if ($result) {
                   3324:         my %setters;
                   3325:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3326:             my ($startblock,$endblock) =
                   3327:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3328:             if ($startblock && $endblock) {
                   3329:                 return 'B';
                   3330:             }
                   3331:         } else {
                   3332:             my ($startblock,$endblock) =
                   3333:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3334:             if ($startblock && $endblock) {
                   3335:                 return 'B';
                   3336:             }
                   3337:         }
                   3338:     }
1.765     albertel 3339:     if ($result eq 'ok') {
1.766     albertel 3340:        return 'F';
1.765     albertel 3341:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3342:        return 'A';
1.765     albertel 3343:     }
1.766     albertel 3344:     return '';
1.765     albertel 3345: }
                   3346: 
                   3347: sub get_portfolio_access {
1.767     albertel 3348:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3349: 
                   3350:     if (!ref($access_hash)) {
                   3351: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3352: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3353: 						   $file_name);
                   3354: 	$access_hash = $access_controls{$file_name};
                   3355:     }
                   3356: 
1.765     albertel 3357:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3358:     my $now = time;
                   3359:     if (ref($access_hash) eq 'HASH') {
                   3360:         foreach my $key (keys(%{$access_hash})) {
                   3361:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3362:             if ($start > $now) {
                   3363:                 next;
                   3364:             }
                   3365:             if ($end && $end<$now) {
                   3366:                 next;
                   3367:             }
                   3368:             if ($scope eq 'public') {
                   3369:                 $public = $key;
                   3370:                 last;
                   3371:             } elsif ($scope eq 'guest') {
                   3372:                 $guest = $key;
                   3373:             } elsif ($scope eq 'domains') {
                   3374:                 push(@domains,$key);
                   3375:             } elsif ($scope eq 'users') {
                   3376:                 push(@users,$key);
                   3377:             } elsif ($scope eq 'course') {
                   3378:                 push(@courses,$key);
                   3379:             } elsif ($scope eq 'group') {
                   3380:                 push(@groups,$key);
                   3381:             }
                   3382:         }
                   3383:         if ($public) {
                   3384:             return 'ok';
                   3385:         }
                   3386:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3387:             if ($guest) {
                   3388:                 return $guest;
                   3389:             }
                   3390:         } else {
                   3391:             if (@domains > 0) {
                   3392:                 foreach my $domkey (@domains) {
                   3393:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3394:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3395:                             return 'ok';
                   3396:                         }
                   3397:                     }
                   3398:                 }
                   3399:             }
                   3400:             if (@users > 0) {
                   3401:                 foreach my $userkey (@users) {
                   3402:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3403:                         return 'ok';
                   3404:                     }
                   3405:                 }
                   3406:             }
                   3407:             my %roleshash;
                   3408:             my @courses_and_groups = @courses;
                   3409:             push(@courses_and_groups,@groups); 
                   3410:             if (@courses_and_groups > 0) {
                   3411:                 my (%allgroups,%allroles); 
                   3412:                 my ($start,$end,$role,$sec,$group);
                   3413:                 foreach my $envkey (%env) {
1.811     albertel 3414:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3415:                         my $cid = $2.'_'.$3; 
                   3416:                         if ($1 eq 'gr') {
                   3417:                             $group = $4;
                   3418:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3419:                         } else {
                   3420:                             if ($4 eq '') {
                   3421:                                 $sec = 'none';
                   3422:                             } else {
                   3423:                                 $sec = $4;
                   3424:                             }
                   3425:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3426:                         }
1.811     albertel 3427:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3428:                         my $cid = $2.'_'.$3;
                   3429:                         if ($4 eq '') {
                   3430:                             $sec = 'none';
                   3431:                         } else {
                   3432:                             $sec = $4;
                   3433:                         }
                   3434:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3435:                     }
                   3436:                 }
                   3437:                 if (keys(%allroles) == 0) {
                   3438:                     return;
                   3439:                 }
                   3440:                 foreach my $key (@courses_and_groups) {
                   3441:                     my %content = %{$$access_hash{$key}};
                   3442:                     my $cnum = $content{'number'};
                   3443:                     my $cdom = $content{'domain'};
                   3444:                     my $cid = $cdom.'_'.$cnum;
                   3445:                     if (!exists($allroles{$cid})) {
                   3446:                         next;
                   3447:                     }    
                   3448:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3449:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3450:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3451:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3452:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3453:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3454:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3455:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3456:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3457:                                         if (grep/^all$/,@sections) {
                   3458:                                             return 'ok';
                   3459:                                         } else {
                   3460:                                             if (grep/^$sec$/,@sections) {
                   3461:                                                 return 'ok';
                   3462:                                             }
                   3463:                                         }
                   3464:                                     }
                   3465:                                 }
                   3466:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3467:                                     if (grep/^none$/,@groups) {
                   3468:                                         return 'ok';
                   3469:                                     }
                   3470:                                 } else {
                   3471:                                     if (grep/^all$/,@groups) {
                   3472:                                         return 'ok';
                   3473:                                     } 
                   3474:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3475:                                         if (grep/^$group$/,@groups) {
                   3476:                                             return 'ok';
                   3477:                                         }
                   3478:                                     }
                   3479:                                 } 
                   3480:                             }
                   3481:                         }
                   3482:                     }
                   3483:                 }
                   3484:             }
                   3485:             if ($guest) {
                   3486:                 return $guest;
                   3487:             }
                   3488:         }
                   3489:     }
                   3490:     return;
                   3491: }
                   3492: 
                   3493: sub course_group_datechecker {
                   3494:     my ($dates,$now,$status) = @_;
                   3495:     my ($start,$end) = split(/\./,$dates);
                   3496:     if (!$start && !$end) {
                   3497:         return 'ok';
                   3498:     }
                   3499:     if (grep/^active$/,@{$status}) {
                   3500:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3501:             return 'ok';
                   3502:         }
                   3503:     }
                   3504:     if (grep/^previous$/,@{$status}) {
                   3505:         if ($end > $now ) {
                   3506:             return 'ok';
                   3507:         }
                   3508:     }
                   3509:     if (grep/^future$/,@{$status}) {
                   3510:         if ($start > $now) {
                   3511:             return 'ok';
                   3512:         }
                   3513:     }
                   3514:     return; 
                   3515: }
                   3516: 
                   3517: sub parse_portfolio_url {
                   3518:     my ($url) = @_;
                   3519: 
                   3520:     my ($type,$udom,$unum,$group,$file_name);
                   3521:     
1.807     albertel 3522:     if ($url =~  m-^/*uploaded/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3523: 	$type = 1;
                   3524:         $udom = $1;
                   3525:         $unum = $2;
                   3526:         $file_name = $3;
1.811     albertel 3527:     } elsif ($url =~ m-^/*uploaded/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3528: 	$type = 2;
                   3529:         $udom = $1;
                   3530:         $unum = $2;
                   3531:         $group = $3;
                   3532:         $file_name = $3.'/'.$4;
                   3533:     }
                   3534:     if (wantarray) {
                   3535: 	return ($type,$udom,$unum,$file_name,$group);
                   3536:     }
                   3537:     return $type;
                   3538: }
                   3539: 
                   3540: sub is_portfolio_url {
                   3541:     my ($url) = @_;
                   3542:     return scalar(&parse_portfolio_url($url));
                   3543: }
                   3544: 
1.798     raeburn  3545: sub is_portfolio_file {
                   3546:     my ($file) = @_;
1.820   ! raeburn  3547:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3548:         return 1;
                   3549:     }
                   3550:     return;
                   3551: }
                   3552: 
                   3553: 
1.341     www      3554: # ---------------------------------------------- Custom access rule evaluation
                   3555: 
                   3556: sub customaccess {
                   3557:     my ($priv,$uri)=@_;
1.807     albertel 3558:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3559:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3560:     $udom = &LONCAPA::clean_domain($udom);
                   3561:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3562:     my $access=0;
1.800     albertel 3563:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3564: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3565:         if ($role) {
                   3566: 	   if ($role ne $urole) { next; }
                   3567:         }
1.800     albertel 3568:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3569:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3570:             if ($tdom) {
                   3571: 		if ($tdom ne $udom) { next; }
                   3572:             }
                   3573:             if ($tcrs) {
                   3574: 		if ($tcrs ne $ucrs) { next; }
                   3575:             }
                   3576:             if ($tsec) {
                   3577: 		if ($tsec ne $usec) { next; }
                   3578:             }
                   3579:             $access=($effect eq 'allow');
                   3580:             last;
1.342     www      3581:         }
1.402     bowersj2 3582: 	if ($realm eq '' && $role eq '') {
                   3583:             $access=($effect eq 'allow');
                   3584: 	}
1.341     www      3585:     }
                   3586:     return $access;
                   3587: }
                   3588: 
1.103     harris41 3589: # ------------------------------------------------- Check for a user privilege
1.12      www      3590: 
                   3591: sub allowed {
1.810     raeburn  3592:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3593:     my $ver_orguri=$uri;
1.439     www      3594:     $uri=&deversion($uri);
1.152     www      3595:     my $orguri=$uri;
1.52      www      3596:     $uri=&declutter($uri);
1.809     raeburn  3597: 
1.810     raeburn  3598:     if ($priv eq 'evb') {
                   3599: # Evade communication block restrictions for specified role in a course
                   3600:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3601:             return $1;
                   3602:         } else {
                   3603:             return;
                   3604:         }
                   3605:     }
                   3606: 
1.620     albertel 3607:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3608: # Free bre access to adm and meta resources
1.775     albertel 3609:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3610: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3611: 	&& ($priv eq 'bre')) {
1.14      www      3612: 	return 'F';
1.159     www      3613:     }
                   3614: 
1.545     banghart 3615: # Free bre access to user's own portfolio contents
1.714     raeburn  3616:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3617:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3618: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3619:         my %setters;
                   3620:         my ($startblock,$endblock) = 
                   3621:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3622:         if ($startblock && $endblock) {
                   3623:             return 'B';
                   3624:         } else {
                   3625:             return 'F';
                   3626:         }
1.545     banghart 3627:     }
                   3628: 
1.762     raeburn  3629: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3630:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3631:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3632:         if (exists($env{'request.course.id'})) {
                   3633:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3634:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3635:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3636:                 my $courseprivid=$env{'request.course.id'};
                   3637:                 $courseprivid=~s/\_/\//;
                   3638:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3639:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3640:                     return $1; 
1.762     raeburn  3641:                 } else {
                   3642:                     if ($env{'request.course.sec'}) {
                   3643:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3644:                     }
                   3645:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3646:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3647:                         return $2;
                   3648:                     }
1.714     raeburn  3649:                 }
                   3650:             }
                   3651:         }
                   3652:     }
                   3653: 
1.159     www      3654: # Free bre to public access
                   3655: 
                   3656:     if ($priv eq 'bre') {
1.238     www      3657:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3658: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3659:            return 'F'; 
                   3660:         }
1.238     www      3661:         if ($copyright eq 'priv') {
                   3662:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3663: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3664: 		return '';
                   3665:             }
                   3666:         }
                   3667:         if ($copyright eq 'domain') {
                   3668:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3669: 	    unless (($env{'user.domain'} eq $1) ||
                   3670:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3671: 		return '';
                   3672:             }
1.262     matthew  3673:         }
1.620     albertel 3674:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3675:             # Library role, so allow browsing of resources in this domain.
                   3676:             return 'F';
1.238     www      3677:         }
1.341     www      3678:         if ($copyright eq 'custom') {
                   3679: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3680:         }
1.14      www      3681:     }
1.264     matthew  3682:     # Domain coordinator is trying to create a course
1.620     albertel 3683:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3684:         # uri is the requested domain in this case.
                   3685:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3686:         # a role of dc for the domain in question.
1.620     albertel 3687:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3688:     }
1.29      www      3689: 
1.52      www      3690:     my $thisallowed='';
                   3691:     my $statecond=0;
                   3692:     my $courseprivid='';
                   3693: 
                   3694: # Course
                   3695: 
1.620     albertel 3696:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3697:        $thisallowed.=$1;
                   3698:     }
1.29      www      3699: 
1.52      www      3700: # Domain
                   3701: 
1.620     albertel 3702:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3703:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3704:        $thisallowed.=$1;
                   3705:     }
1.52      www      3706: 
                   3707: # Course: uri itself is a course
1.66      www      3708:     my $courseuri=$uri;
                   3709:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3710:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3711: 
1.620     albertel 3712:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3713:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3714:        $thisallowed.=$1;
                   3715:     }
1.29      www      3716: 
1.665     albertel 3717: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3718: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3719:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3720: 	$thisallowed='';
1.671     raeburn  3721:         my ($match)=&is_on_map($uri);
                   3722:         if ($match) {
                   3723:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3724:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3725:                 $thisallowed.=$1;
                   3726:             }
                   3727:         } else {
1.705     albertel 3728:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3729:             if ($refuri) {
                   3730:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3731:                     $thisallowed='F';
1.671     raeburn  3732:                 } else {
                   3733:                     $refuri=&declutter($refuri);
                   3734:                     my ($match) = &is_on_map($refuri);
                   3735:                     if ($match) {
                   3736:                         $thisallowed='F';
                   3737:                     }
1.669     raeburn  3738:                 }
1.671     raeburn  3739:             }
                   3740:         }
1.314     www      3741:     }
1.492     albertel 3742: 
1.766     albertel 3743:     if ($priv eq 'bre'
                   3744: 	&& $thisallowed ne 'F' 
                   3745: 	&& $thisallowed ne '2'
                   3746: 	&& &is_portfolio_url($uri)) {
                   3747: 	$thisallowed = &portfolio_access($uri);
                   3748:     }
                   3749:     
1.52      www      3750: # Full access at system, domain or course-wide level? Exit.
1.29      www      3751: 
                   3752:     if ($thisallowed=~/F/) {
                   3753: 	return 'F';
                   3754:     }
                   3755: 
1.52      www      3756: # If this is generating or modifying users, exit with special codes
1.29      www      3757: 
1.643     www      3758:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3759: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3760: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3761: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3762: 	    unless ($auname) { return $thisallowed; }
                   3763: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3764: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3765: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3766: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3767: 	}
1.52      www      3768: 	return $thisallowed;
                   3769:     }
                   3770: #
1.103     harris41 3771: # Gathered so far: system, domain and course wide privileges
1.52      www      3772: #
                   3773: # Course: See if uri or referer is an individual resource that is part of 
                   3774: # the course
                   3775: 
1.620     albertel 3776:     if ($env{'request.course.id'}) {
1.232     www      3777: 
1.620     albertel 3778:        $courseprivid=$env{'request.course.id'};
                   3779:        if ($env{'request.course.sec'}) {
                   3780:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3781:        }
                   3782:        $courseprivid=~s/\_/\//;
                   3783:        my $checkreferer=1;
1.232     www      3784:        my ($match,$cond)=&is_on_map($uri);
                   3785:        if ($match) {
                   3786:            $statecond=$cond;
1.620     albertel 3787:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3788:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3789:                $thisallowed.=$1;
                   3790:                $checkreferer=0;
                   3791:            }
1.29      www      3792:        }
1.83      www      3793:        
1.148     www      3794:        if ($checkreferer) {
1.620     albertel 3795: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3796:             unless ($refuri) {
1.800     albertel 3797:                 foreach my $key (keys(%env)) {
                   3798: 		    if ($key=~/^httpref\..*\*/) {
                   3799: 			my $pattern=$key;
1.156     www      3800:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3801:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3802:                         $pattern=~s/\//\\\//g;
1.152     www      3803:                         if ($orguri=~/$pattern/) {
1.800     albertel 3804: 			    $refuri=$env{$key};
1.148     www      3805:                         }
                   3806:                     }
1.191     harris41 3807:                 }
1.148     www      3808:             }
1.232     www      3809: 
1.148     www      3810:          if ($refuri) { 
1.152     www      3811: 	  $refuri=&declutter($refuri);
1.232     www      3812:           my ($match,$cond)=&is_on_map($refuri);
                   3813:             if ($match) {
                   3814:               my $refstatecond=$cond;
1.620     albertel 3815:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3816:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3817:                   $thisallowed.=$1;
1.53      www      3818:                   $uri=$refuri;
                   3819:                   $statecond=$refstatecond;
1.52      www      3820:               }
                   3821:           }
1.148     www      3822:         }
1.29      www      3823:        }
1.52      www      3824:    }
1.29      www      3825: 
1.52      www      3826: #
1.103     harris41 3827: # Gathered now: all privileges that could apply, and condition number
1.52      www      3828: # 
                   3829: #
                   3830: # Full or no access?
                   3831: #
1.29      www      3832: 
1.52      www      3833:     if ($thisallowed=~/F/) {
                   3834: 	return 'F';
                   3835:     }
1.29      www      3836: 
1.52      www      3837:     unless ($thisallowed) {
                   3838:         return '';
                   3839:     }
1.29      www      3840: 
1.52      www      3841: # Restrictions exist, deal with them
                   3842: #
                   3843: #   C:according to course preferences
                   3844: #   R:according to resource settings
                   3845: #   L:unless locked
                   3846: #   X:according to user session state
                   3847: #
                   3848: 
                   3849: # Possibly locked functionality, check all courses
1.54      www      3850: # Locks might take effect only after 10 minutes cache expiration for other
                   3851: # courses, and 2 minutes for current course
1.52      www      3852: 
                   3853:     my $envkey;
                   3854:     if ($thisallowed=~/L/) {
1.620     albertel 3855:         foreach $envkey (keys %env) {
1.54      www      3856:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3857:                my $courseid=$2;
                   3858:                my $roleid=$1.'.'.$2;
1.92      www      3859:                $courseid=~s/^\///;
1.54      www      3860:                my $expiretime=600;
1.620     albertel 3861:                if ($env{'request.role'} eq $roleid) {
1.54      www      3862: 		  $expiretime=120;
                   3863:                }
                   3864: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3865:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3866:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3867: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3868:                }
1.620     albertel 3869:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3870:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3871: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3872:                        &log($env{'user.domain'},$env{'user.name'},
                   3873:                             $env{'user.home'},
1.57      www      3874:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3875:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3876:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3877: 		       return '';
                   3878:                    }
                   3879:                }
1.620     albertel 3880:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3881:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3882: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3883:                        &log($env{'user.domain'},$env{'user.name'},
                   3884:                             $env{'user.home'},
1.57      www      3885:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3886:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3887:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3888: 		       return '';
                   3889:                    }
                   3890:                }
                   3891: 	   }
1.29      www      3892:        }
1.52      www      3893:     }
                   3894:    
                   3895: #
                   3896: # Rest of the restrictions depend on selected course
                   3897: #
                   3898: 
1.620     albertel 3899:     unless ($env{'request.course.id'}) {
1.766     albertel 3900: 	if ($thisallowed eq 'A') {
                   3901: 	    return 'A';
1.814     raeburn  3902:         } elsif ($thisallowed eq 'B') {
                   3903:             return 'B';
1.766     albertel 3904: 	} else {
                   3905: 	    return '1';
                   3906: 	}
1.52      www      3907:     }
1.29      www      3908: 
1.52      www      3909: #
                   3910: # Now user is definitely in a course
                   3911: #
1.53      www      3912: 
                   3913: 
                   3914: # Course preferences
                   3915: 
                   3916:    if ($thisallowed=~/C/) {
1.620     albertel 3917:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3918:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3919:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3920: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3921: 	   if ($priv ne 'pch') { 
                   3922: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3923: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3924: 			$env{'request.course.id'});
                   3925: 	   }
1.237     www      3926:            return '';
                   3927:        }
                   3928: 
1.620     albertel 3929:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3930: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3931: 	   if ($priv ne 'pch') { 
                   3932: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3933: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3934: 			$env{'request.course.id'});
                   3935: 	   }
1.54      www      3936:            return '';
                   3937:        }
1.53      www      3938:    }
                   3939: 
                   3940: # Resource preferences
                   3941: 
                   3942:    if ($thisallowed=~/R/) {
1.620     albertel 3943:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3944:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3945: 	   if ($priv ne 'pch') { 
                   3946: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3947: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3948: 	   }
                   3949: 	   return '';
1.54      www      3950:        }
1.53      www      3951:    }
1.30      www      3952: 
1.246     www      3953: # Restricted by state or randomout?
1.30      www      3954: 
1.52      www      3955:    if ($thisallowed=~/X/) {
1.620     albertel 3956:       if ($env{'acc.randomout'}) {
1.579     albertel 3957: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3958:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3959:             return ''; 
                   3960:          }
1.247     www      3961:       }
                   3962:       if (&condval($statecond)) {
1.52      www      3963: 	 return '2';
                   3964:       } else {
                   3965:          return '';
                   3966:       }
                   3967:    }
1.30      www      3968: 
1.766     albertel 3969:     if ($thisallowed eq 'A') {
                   3970: 	return 'A';
1.814     raeburn  3971:     } elsif ($thisallowed eq 'B') {
                   3972:         return 'B';
1.766     albertel 3973:     }
1.52      www      3974:    return 'F';
1.232     www      3975: }
                   3976: 
1.710     albertel 3977: sub split_uri_for_cond {
                   3978:     my $uri=&deversion(&declutter(shift));
                   3979:     my @uriparts=split(/\//,$uri);
                   3980:     my $filename=pop(@uriparts);
                   3981:     my $pathname=join('/',@uriparts);
                   3982:     return ($pathname,$filename);
                   3983: }
1.232     www      3984: # --------------------------------------------------- Is a resource on the map?
                   3985: 
                   3986: sub is_on_map {
1.710     albertel 3987:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3988:     #Trying to find the conditional for the file
1.620     albertel 3989:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3990: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3991:     if ($match) {
1.289     bowersj2 3992: 	return (1,$1);
                   3993:     } else {
1.434     www      3994: 	return (0,0);
1.289     bowersj2 3995:     }
1.12      www      3996: }
                   3997: 
1.427     www      3998: # --------------------------------------------------------- Get symb from alias
                   3999: 
                   4000: sub get_symb_from_alias {
                   4001:     my $symb=shift;
                   4002:     my ($map,$resid,$url)=&decode_symb($symb);
                   4003: # Already is a symb
                   4004:     if ($url) { return $symb; }
                   4005: # Must be an alias
                   4006:     my $aliassymb='';
                   4007:     my %bighash;
1.620     albertel 4008:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4009:                             &GDBM_READER(),0640)) {
                   4010:         my $rid=$bighash{'mapalias_'.$symb};
                   4011: 	if ($rid) {
                   4012: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4013: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4014: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4015: 	}
                   4016:         untie %bighash;
                   4017:     }
                   4018:     return $aliassymb;
                   4019: }
                   4020: 
1.12      www      4021: # ----------------------------------------------------------------- Define Role
                   4022: 
                   4023: sub definerole {
                   4024:   if (allowed('mcr','/')) {
                   4025:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4026:     foreach my $role (split(':',$sysrole)) {
                   4027: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4028:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4029:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4030: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4031:                return "refused:s:$crole&$cqual"; 
                   4032:             }
                   4033:         }
1.191     harris41 4034:     }
1.800     albertel 4035:     foreach my $role (split(':',$domrole)) {
                   4036: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4037:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4038:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4039: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4040:                return "refused:d:$crole&$cqual"; 
                   4041:             }
                   4042:         }
1.191     harris41 4043:     }
1.800     albertel 4044:     foreach my $role (split(':',$courole)) {
                   4045: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4046:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4047:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4048: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4049:                return "refused:c:$crole&$cqual"; 
                   4050:             }
                   4051:         }
1.191     harris41 4052:     }
1.620     albertel 4053:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4054:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4055: 	        "rolesdef_$rolename=".
                   4056:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4057:     return reply($command,$env{'user.home'});
1.12      www      4058:   } else {
                   4059:     return 'refused';
                   4060:   }
1.105     harris41 4061: }
                   4062: 
                   4063: # ---------------- Make a metadata query against the network of library servers
                   4064: 
                   4065: sub metadata_query {
1.244     matthew  4066:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4067:     my %rhash;
1.244     matthew  4068:     my @server_list = (defined($server_array) ? @$server_array
                   4069:                                               : keys(%libserv) );
                   4070:     for my $server (@server_list) {
1.118     harris41 4071: 	unless ($custom or $customshow) {
                   4072: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4073: 	    $rhash{$server}=$reply;
                   4074: 	}
                   4075: 	else {
                   4076: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4077: 			     &escape($custom).':'.&escape($customshow),
                   4078: 			     $server);
                   4079: 	    $rhash{$server}=$reply;
                   4080: 	}
1.112     harris41 4081:     }
1.118     harris41 4082:     return \%rhash;
1.240     www      4083: }
                   4084: 
                   4085: # ----------------------------------------- Send log queries and wait for reply
                   4086: 
                   4087: sub log_query {
                   4088:     my ($uname,$udom,$query,%filters)=@_;
                   4089:     my $uhome=&homeserver($uname,$udom);
                   4090:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4091:     my $uhost=$hostname{$uhome};
1.800     albertel 4092:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4093:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4094:                        $uhome);
1.479     albertel 4095:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4096:     return get_query_reply($queryid);
                   4097: }
                   4098: 
1.818     raeburn  4099: # -------------------------- Update MySQL table for portfolio file
                   4100: 
                   4101: sub update_portfolio_table {
                   4102:     my ($uname,$udom,$file_name,$query,$group) = @_;
                   4103:     my $homeserver = &homeserver($uname,$udom);
                   4104:     my $queryid=
                   4105:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom).':'.
                   4106:               &escape($file_name).':'.&escape($group),$homeserver);
                   4107:     my $reply = &get_query_reply($queryid);
                   4108:     return $reply;
                   4109: }
                   4110: 
1.508     raeburn  4111: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4112: 
                   4113: sub fetch_enrollment_query {
1.511     raeburn  4114:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4115:     my $homeserver;
1.547     raeburn  4116:     my $maxtries = 1;
1.508     raeburn  4117:     if ($context eq 'automated') {
                   4118:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4119:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4120:     } else {
                   4121:         $homeserver = &homeserver($cnum,$dom);
                   4122:     }
1.506     raeburn  4123:     my $host=$hostname{$homeserver};
                   4124:     my $cmd = '';
1.800     albertel 4125:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4126:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4127:     }
                   4128:     $cmd =~ s/%%$//;
                   4129:     $cmd = &escape($cmd);
                   4130:     my $query = 'fetchenrollment';
1.620     albertel 4131:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4132:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4133:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4134:         return 'error: '.$queryid;
                   4135:     }
1.506     raeburn  4136:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4137:     my $tries = 1;
                   4138:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4139:         $reply = &get_query_reply($queryid);
                   4140:         $tries ++;
                   4141:     }
1.526     raeburn  4142:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4143:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4144:     } else {
1.515     raeburn  4145:         my @responses = split/:/,$reply;
                   4146:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4147:             foreach my $line (@responses) {
                   4148:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4149:                 $$replyref{$key} = $value;
                   4150:             }
                   4151:         } else {
1.506     raeburn  4152:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4153:             foreach my $line (@responses) {
                   4154:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4155:                 $$replyref{$key} = $value;
                   4156:                 if ($value > 0) {
1.800     albertel 4157:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4158:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4159:                         my $destname = $pathname.'/'.$filename;
                   4160:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4161:                         if ($xml_classlist =~ /^error/) {
                   4162:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4163:                         } else {
1.506     raeburn  4164:                             if ( open(FILE,">$destname") ) {
                   4165:                                 print FILE &unescape($xml_classlist);
                   4166:                                 close(FILE);
1.526     raeburn  4167:                             } else {
                   4168:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4169:                             }
                   4170:                         }
                   4171:                     }
                   4172:                 }
                   4173:             }
                   4174:         }
                   4175:         return 'ok';
                   4176:     }
                   4177:     return 'error';
                   4178: }
                   4179: 
1.242     www      4180: sub get_query_reply {
                   4181:     my $queryid=shift;
1.240     www      4182:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4183:     my $reply='';
                   4184:     for (1..100) {
                   4185: 	sleep 2;
                   4186:         if (-e $replyfile.'.end') {
1.448     albertel 4187: 	    if (open(my $fh,$replyfile)) {
1.240     www      4188:                $reply.=<$fh>;
1.448     albertel 4189:                close($fh);
1.240     www      4190: 	   } else { return 'error: reply_file_error'; }
1.242     www      4191:            return &unescape($reply);
                   4192: 	}
1.240     www      4193:     }
1.242     www      4194:     return 'timeout:'.$queryid;
1.240     www      4195: }
                   4196: 
                   4197: sub courselog_query {
1.241     www      4198: #
                   4199: # possible filters:
                   4200: # url: url or symb
                   4201: # username
                   4202: # domain
                   4203: # action: view, submit, grade
                   4204: # start: timestamp
                   4205: # end: timestamp
                   4206: #
1.240     www      4207:     my (%filters)=@_;
1.620     albertel 4208:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4209:     if ($filters{'url'}) {
                   4210: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4211:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4212:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4213:     }
1.620     albertel 4214:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4215:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4216:     return &log_query($cname,$cdom,'courselog',%filters);
                   4217: }
                   4218: 
                   4219: sub userlog_query {
                   4220:     my ($uname,$udom,%filters)=@_;
                   4221:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4222: }
                   4223: 
1.506     raeburn  4224: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4225: 
                   4226: sub auto_run {
1.508     raeburn  4227:     my ($cnum,$cdom) = @_;
                   4228:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4229:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4230:     return $response;
                   4231: }
1.776     albertel 4232: 
1.506     raeburn  4233: sub auto_get_sections {
1.508     raeburn  4234:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4235:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4236:     my @secs = ();
1.511     raeburn  4237:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4238:     unless ($response eq 'refused') {
                   4239:         @secs = split/:/,$response;
                   4240:     }
                   4241:     return @secs;
                   4242: }
1.776     albertel 4243: 
1.506     raeburn  4244: sub auto_new_course {
1.508     raeburn  4245:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4246:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4247:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4248:     return $response;
                   4249: }
1.776     albertel 4250: 
1.506     raeburn  4251: sub auto_validate_courseID {
1.508     raeburn  4252:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4253:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4254:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4255:     return $response;
                   4256: }
1.776     albertel 4257: 
1.506     raeburn  4258: sub auto_create_password {
1.508     raeburn  4259:     my ($cnum,$cdom,$authparam) = @_;
                   4260:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4261:     my $create_passwd = 0;
                   4262:     my $authchk = '';
1.511     raeburn  4263:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4264:     if ($response eq 'refused') {
                   4265:         $authchk = 'refused';
                   4266:     } else {
                   4267:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4268:     }
                   4269:     return ($authparam,$create_passwd,$authchk);
                   4270: }
                   4271: 
1.706     raeburn  4272: sub auto_photo_permission {
                   4273:     my ($cnum,$cdom,$students) = @_;
                   4274:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4275:     my ($outcome,$perm_reqd,$conditions) = 
                   4276: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4277:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4278: 	return (undef,undef);
                   4279:     }
1.706     raeburn  4280:     return ($outcome,$perm_reqd,$conditions);
                   4281: }
                   4282: 
                   4283: sub auto_checkphotos {
                   4284:     my ($uname,$udom,$pid) = @_;
                   4285:     my $homeserver = &homeserver($uname,$udom);
                   4286:     my ($result,$resulttype);
                   4287:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4288: 				   &escape($uname).':'.&escape($pid),
                   4289: 				   $homeserver));
1.709     albertel 4290:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4291: 	return (undef,undef);
                   4292:     }
1.706     raeburn  4293:     if ($outcome) {
                   4294:         ($result,$resulttype) = split(/:/,$outcome);
                   4295:     } 
                   4296:     return ($result,$resulttype);
                   4297: }
                   4298: 
                   4299: sub auto_photochoice {
                   4300:     my ($cnum,$cdom) = @_;
                   4301:     my $homeserver = &homeserver($cnum,$cdom);
                   4302:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4303: 						       &escape($cdom),
                   4304: 						       $homeserver)));
1.709     albertel 4305:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4306: 	return (undef,undef);
                   4307:     }
1.706     raeburn  4308:     return ($update,$comment);
                   4309: }
                   4310: 
                   4311: sub auto_photoupdate {
                   4312:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4313:     my $homeserver = &homeserver($cnum,$dom);
                   4314:     my $host=$hostname{$homeserver};
                   4315:     my $cmd = '';
                   4316:     my $maxtries = 1;
1.800     albertel 4317:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4318:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4319:     }
                   4320:     $cmd =~ s/%%$//;
                   4321:     $cmd = &escape($cmd);
                   4322:     my $query = 'institutionalphotos';
                   4323:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4324:     unless ($queryid=~/^\Q$host\E\_/) {
                   4325:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4326:         return 'error: '.$queryid;
                   4327:     }
                   4328:     my $reply = &get_query_reply($queryid);
                   4329:     my $tries = 1;
                   4330:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4331:         $reply = &get_query_reply($queryid);
                   4332:         $tries ++;
                   4333:     }
                   4334:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4335:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4336:     } else {
                   4337:         my @responses = split(/:/,$reply);
                   4338:         my $outcome = shift(@responses); 
                   4339:         foreach my $item (@responses) {
                   4340:             my ($key,$value) = split(/=/,$item);
                   4341:             $$photo{$key} = $value;
                   4342:         }
                   4343:         return $outcome;
                   4344:     }
                   4345:     return 'error';
                   4346: }
                   4347: 
1.521     raeburn  4348: sub auto_instcode_format {
1.793     albertel 4349:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4350: 	$cat_order) = @_;
1.521     raeburn  4351:     my $courses = '';
1.772     raeburn  4352:     my @homeservers;
1.521     raeburn  4353:     if ($caller eq 'global') {
1.793     albertel 4354:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4355:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4356:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4357:                     push(@homeservers,$tryserver);
                   4358:                 }
1.584     raeburn  4359:             }
                   4360:         }
1.521     raeburn  4361:     } else {
1.772     raeburn  4362:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4363:     }
1.793     albertel 4364:     foreach my $code (keys(%{$instcodes})) {
                   4365:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4366:     }
                   4367:     chop($courses);
1.772     raeburn  4368:     my $ok_response = 0;
                   4369:     my $response;
                   4370:     while (@homeservers > 0 && $ok_response == 0) {
                   4371:         my $server = shift(@homeservers); 
                   4372:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4373:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4374:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4375: 		split/:/,$response;
1.772     raeburn  4376:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4377:             push(@{$codetitles},&str2array($codetitles_str));
                   4378:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4379:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4380:             $ok_response = 1;
                   4381:         }
                   4382:     }
                   4383:     if ($ok_response) {
1.521     raeburn  4384:         return 'ok';
1.772     raeburn  4385:     } else {
                   4386:         return $response;
1.521     raeburn  4387:     }
                   4388: }
                   4389: 
1.792     raeburn  4390: sub auto_instcode_defaults {
                   4391:     my ($domain,$returnhash,$code_order) = @_;
                   4392:     my @homeservers;
1.793     albertel 4393:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4394:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4395:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4396:                 push(@homeservers,$tryserver);
                   4397:             }
                   4398:         }
                   4399:     }
                   4400:     my $ok_response = 0;
                   4401:     my $response;
                   4402:     while (@homeservers > 0 && $ok_response == 0) {
                   4403:         my $server = shift(@homeservers);
                   4404:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4405:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4406:             foreach my $pair (split(/\&/,$response)) {
                   4407:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4408:                 if ($name eq 'code_order') {
1.796     raeburn  4409:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4410:                 } else {
1.796     raeburn  4411:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4412:                 }
                   4413:             }
1.804     raeburn  4414:             $ok_response = 1;
1.792     raeburn  4415:         }
                   4416:     }
                   4417:     if ($ok_response) {
                   4418:         return 'ok';
                   4419:     } else {
                   4420:         return $response;
                   4421:     }
                   4422: } 
                   4423: 
1.777     albertel 4424: sub auto_validate_class_sec {
1.773     raeburn  4425:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4426:     my $homeserver = &homeserver($cnum,$cdom);
                   4427:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4428:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4429:     return $response;
                   4430: }
                   4431: 
1.679     raeburn  4432: # ------------------------------------------------------- Course Group routines
                   4433: 
                   4434: sub get_coursegroups {
1.809     raeburn  4435:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4436:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4437: }
                   4438: 
1.679     raeburn  4439: sub modify_coursegroup {
                   4440:     my ($cdom,$cnum,$groupsettings) = @_;
                   4441:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4442: }
                   4443: 
1.809     raeburn  4444: sub toggle_coursegroup_status {
                   4445:     my ($cdom,$cnum,$group,$action) = @_;
                   4446:     my ($from_namespace,$to_namespace);
                   4447:     if ($action eq 'delete') {
                   4448:         $from_namespace = 'coursegroups';
                   4449:         $to_namespace = 'deleted_groups';
                   4450:     } else {
                   4451:         $from_namespace = 'deleted_groups';
                   4452:         $to_namespace = 'coursegroups';
                   4453:     }
                   4454:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4455:     if (my $tmp = &error(%curr_group)) {
                   4456:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4457:         return ('read error',$tmp);
                   4458:     } else {
                   4459:         my %savedsettings = %curr_group; 
1.809     raeburn  4460:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4461:         my $deloutcome;
                   4462:         if ($result eq 'ok') {
1.809     raeburn  4463:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4464:         } else {
                   4465:             return ('write error',$result);
                   4466:         }
                   4467:         if ($deloutcome eq 'ok') {
                   4468:             return 'ok';
                   4469:         } else {
                   4470:             return ('delete error',$deloutcome);
                   4471:         }
                   4472:     }
                   4473: }
                   4474: 
1.679     raeburn  4475: sub modify_group_roles {
                   4476:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4477:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4478:     my $role = 'gr/'.&escape($userprivs);
                   4479:     my ($uname,$udom) = split(/:/,$user);
                   4480:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4481:     if ($result eq 'ok') {
                   4482:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4483:     }
1.679     raeburn  4484:     return $result;
                   4485: }
                   4486: 
                   4487: sub modify_coursegroup_membership {
                   4488:     my ($cdom,$cnum,$membership) = @_;
                   4489:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4490:     return $result;
                   4491: }
                   4492: 
1.682     raeburn  4493: sub get_active_groups {
                   4494:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4495:     my $now = time;
                   4496:     my %groups = ();
                   4497:     foreach my $key (keys(%env)) {
1.811     albertel 4498:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4499:             my ($start,$end) = split(/\./,$env{$key});
                   4500:             if (($end!=0) && ($end<$now)) { next; }
                   4501:             if (($start!=0) && ($start>$now)) { next; }
                   4502:             if ($1 eq $cdom && $2 eq $cnum) {
                   4503:                 $groups{$3} = $env{$key} ;
                   4504:             }
                   4505:         }
                   4506:     }
                   4507:     return %groups;
                   4508: }
                   4509: 
1.683     raeburn  4510: sub get_group_membership {
                   4511:     my ($cdom,$cnum,$group) = @_;
                   4512:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4513: }
                   4514: 
                   4515: sub get_users_groups {
                   4516:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4517:     my @usersgroups;
1.683     raeburn  4518:     my $cachetime=1800;
                   4519: 
                   4520:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4521:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4522:     if (defined($cached)) {
1.734     albertel 4523:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4524:     } else {  
                   4525:         $grouplist = '';
1.816     raeburn  4526:         my $courseurl = &courseid_to_courseurl($courseid);
                   4527:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4528:         my $access_end = $env{'course.'.$courseid.
                   4529:                               '.default_enrollment_end_date'};
                   4530:         my $now = time;
                   4531:         foreach my $key (keys(%roleshash)) {
                   4532:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4533:                 my $group = $1;
                   4534:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4535:                     my $start = $2;
                   4536:                     my $end = $1;
                   4537:                     if ($start == -1) { next; } # deleted from group
                   4538:                     if (($start!=0) && ($start>$now)) { next; }
                   4539:                     if (($end!=0) && ($end<$now)) {
                   4540:                         if ($access_end && $access_end < $now) {
                   4541:                             if ($access_end - $end < 86400) {
                   4542:                                 push(@usersgroups,$group);
1.733     raeburn  4543:                             }
                   4544:                         }
1.817     raeburn  4545:                         next;
1.733     raeburn  4546:                     }
1.817     raeburn  4547:                     push(@usersgroups,$group);
1.683     raeburn  4548:                 }
                   4549:             }
                   4550:         }
1.817     raeburn  4551:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4552:         $grouplist = join(':',@usersgroups);
                   4553:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4554:     }
1.733     raeburn  4555:     return @usersgroups;
1.683     raeburn  4556: }
                   4557: 
                   4558: sub devalidate_getgroups_cache {
                   4559:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4560:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4561: 
1.683     raeburn  4562:     my $hashid="$udom:$uname:$courseid";
                   4563:     &devalidate_cache_new('getgroups',$hashid);
                   4564: }
                   4565: 
1.12      www      4566: # ------------------------------------------------------------------ Plain Text
                   4567: 
                   4568: sub plaintext {
1.742     raeburn  4569:     my ($short,$type,$cid) = @_;
1.758     albertel 4570:     if ($short =~ /^cr/) {
                   4571: 	return (split('/',$short))[-1];
                   4572:     }
1.742     raeburn  4573:     if (!defined($cid)) {
                   4574:         $cid = $env{'request.course.id'};
                   4575:     }
                   4576:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4577:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4578:                                           '.plaintext'});
                   4579:     }
                   4580:     my %rolenames = (
                   4581:                       Course => 'std',
                   4582:                       Group => 'alt1',
                   4583:                     );
                   4584:     if (defined($type) && 
                   4585:          defined($rolenames{$type}) && 
                   4586:          defined($prp{$short}{$rolenames{$type}})) {
                   4587:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4588:     } else {
                   4589:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4590:     }
1.12      www      4591: }
                   4592: 
                   4593: # ----------------------------------------------------------------- Assign Role
                   4594: 
                   4595: sub assignrole {
1.357     www      4596:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4597:     my $mrole;
                   4598:     if ($role =~ /^cr\//) {
1.393     www      4599:         my $cwosec=$url;
1.811     albertel 4600:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4601: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4602:            &logthis('Refused custom assignrole: '.
                   4603:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4604: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4605:            return 'refused'; 
                   4606:         }
1.21      www      4607:         $mrole='cr';
1.678     raeburn  4608:     } elsif ($role =~ /^gr\//) {
                   4609:         my $cwogrp=$url;
1.811     albertel 4610:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4611:         unless (&allowed('mdg',$cwogrp)) {
                   4612:             &logthis('Refused group assignrole: '.
                   4613:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4614:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4615:             return 'refused';
                   4616:         }
                   4617:         $mrole='gr';
1.21      www      4618:     } else {
1.82      www      4619:         my $cwosec=$url;
1.811     albertel 4620:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4621:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4622:            &logthis('Refused assignrole: '.
                   4623:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4624: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4625:            return 'refused'; 
                   4626:         }
1.21      www      4627:         $mrole=$role;
                   4628:     }
1.620     albertel 4629:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4630:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4631:     if ($end) { $command.='_'.$end; }
1.21      www      4632:     if ($start) {
                   4633: 	if ($end) { 
1.81      www      4634:            $command.='_'.$start; 
1.21      www      4635:         } else {
1.81      www      4636:            $command.='_0_'.$start;
1.21      www      4637:         }
                   4638:     }
1.739     raeburn  4639:     my $origstart = $start;
                   4640:     my $origend = $end;
1.357     www      4641: # actually delete
                   4642:     if ($deleteflag) {
1.373     www      4643: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4644: # modify command to delete the role
1.620     albertel 4645:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4646:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4647: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4648: # set start and finish to negative values for userrolelog
                   4649:            $start=-1;
                   4650:            $end=-1;
                   4651:         }
                   4652:     }
                   4653: # send command
1.349     www      4654:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4655: # log new user role if status is ok
1.349     www      4656:     if ($answer eq 'ok') {
1.663     raeburn  4657: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4658: # for course roles, perform group memberships changes triggered by role change.
                   4659:         unless ($role =~ /^gr/) {
                   4660:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4661:                                              $origstart);
                   4662:         }
1.349     www      4663:     }
                   4664:     return $answer;
1.169     harris41 4665: }
                   4666: 
                   4667: # -------------------------------------------------- Modify user authentication
1.197     www      4668: # Overrides without validation
                   4669: 
1.169     harris41 4670: sub modifyuserauth {
                   4671:     my ($udom,$uname,$umode,$upass)=@_;
                   4672:     my $uhome=&homeserver($uname,$udom);
1.197     www      4673:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4674:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4675:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4676:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4677:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4678: 		     &escape($upass),$uhome);
1.620     albertel 4679:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4680:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4681:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4682:     &log($udom,,$uname,$uhome,
1.620     albertel 4683:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4684:                                      $env{'user.name'}.', '.$umode.
1.197     www      4685:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4686:     unless ($reply eq 'ok') {
1.197     www      4687:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4688: 	return 'error: '.$reply;
                   4689:     }   
1.170     harris41 4690:     return 'ok';
1.80      www      4691: }
                   4692: 
1.81      www      4693: # --------------------------------------------------------------- Modify a user
1.80      www      4694: 
1.81      www      4695: sub modifyuser {
1.206     matthew  4696:     my ($udom,    $uname, $uid,
                   4697:         $umode,   $upass, $first,
                   4698:         $middle,  $last,  $gene,
1.387     www      4699:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4700:     $udom= &LONCAPA::clean_domain($udom);
                   4701:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4702:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4703:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4704: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4705:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4706:                                      ' desiredhome not specified'). 
1.620     albertel 4707:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4708:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4709:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4710: # ----------------------------------------------------------------- Create User
1.406     albertel 4711:     if (($uhome eq 'no_host') && 
                   4712: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4713:         my $unhome='';
1.209     matthew  4714:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4715:             $unhome = $desiredhome;
1.620     albertel 4716: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4717: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4718:         } else { # load balancing routine for determining $unhome
1.80      www      4719:             my $tryserver;
1.81      www      4720:             my $loadm=10000000;
1.80      www      4721:             foreach $tryserver (keys %libserv) {
                   4722: 	       if ($hostdom{$tryserver} eq $udom) {
                   4723:                   my $answer=reply('load',$tryserver);
                   4724:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4725: 		      $loadm=$answer;
                   4726:                       $unhome=$tryserver;
                   4727:                   }
                   4728: 	       }
                   4729: 	    }
                   4730:         }
                   4731:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4732: 	    return 'error: unable to find a home server for '.$uname.
                   4733:                    ' in domain '.$udom;
1.80      www      4734:         }
                   4735:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4736:                          &escape($upass),$unhome);
                   4737: 	unless ($reply eq 'ok') {
                   4738:             return 'error: '.$reply;
                   4739:         }   
1.230     stredwic 4740:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4741:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4742: 	    return 'error: unable verify users home machine.';
1.80      www      4743:         }
1.209     matthew  4744:     }   # End of creation of new user
1.80      www      4745: # ---------------------------------------------------------------------- Add ID
                   4746:     if ($uid) {
                   4747:        $uid=~tr/A-Z/a-z/;
                   4748:        my %uidhash=&idrget($udom,$uname);
1.196     www      4749:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4750:          && (!$forceid)) {
1.80      www      4751: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4752: 	      return 'error: user id "'.$uid.'" does not match '.
                   4753:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4754:           }
                   4755:        } else {
                   4756: 	  &idput($udom,($uname => $uid));
                   4757:        }
                   4758:     }
                   4759: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4760:     my @tmp=&get('environment',
1.134     albertel 4761: 		   ['firstname','middlename','lastname','generation'],
                   4762: 		   $udom,$uname);
1.313     matthew  4763:     my %names;
                   4764:     if ($tmp[0] =~ m/^error:.*/) { 
                   4765:         %names=(); 
                   4766:     } else {
                   4767:         %names = @tmp;
                   4768:     }
1.388     www      4769: #
                   4770: # Make sure to not trash student environment if instructor does not bother
                   4771: # to supply name and email information
                   4772: #
                   4773:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4774:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4775:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4776:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4777:     if ($email) {
                   4778:        $email=~s/[^\w\@\.\-\,]//gs;
                   4779:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4780: 			   $names{'critnotification'} = $email;
                   4781: 			   $names{'permanentemail'} = $email; }
                   4782:     }
1.134     albertel 4783:     my $reply = &put('environment', \%names, $udom,$uname);
                   4784:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4785:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4786:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4787:              $umode.', '.$first.', '.$middle.', '.
                   4788: 	     $last.', '.$gene.' by '.
1.620     albertel 4789:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4790:     return 'ok';
1.80      www      4791: }
                   4792: 
1.81      www      4793: # -------------------------------------------------------------- Modify student
1.80      www      4794: 
1.81      www      4795: sub modifystudent {
                   4796:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4797:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4798:     if (!$cid) {
1.620     albertel 4799: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4800: 	    return 'not_in_class';
                   4801: 	}
1.80      www      4802:     }
                   4803: # --------------------------------------------------------------- Make the user
1.81      www      4804:     my $reply=&modifyuser
1.209     matthew  4805: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4806:          $desiredhome,$email);
1.80      www      4807:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4808:     # This will cause &modify_student_enrollment to get the uid from the
                   4809:     # students environment
                   4810:     $uid = undef if (!$forceid);
1.455     albertel 4811:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4812: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4813:     return $reply;
                   4814: }
                   4815: 
                   4816: sub modify_student_enrollment {
1.515     raeburn  4817:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4818:     my ($cdom,$cnum,$chome);
                   4819:     if (!$cid) {
1.620     albertel 4820: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4821: 	    return 'not_in_class';
                   4822: 	}
1.620     albertel 4823: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4824: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4825:     } else {
                   4826: 	($cdom,$cnum)=split(/_/,$cid);
                   4827:     }
1.620     albertel 4828:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4829:     if (!$chome) {
1.457     raeburn  4830: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4831:     }
1.455     albertel 4832:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4833:     # Make sure the user exists
1.81      www      4834:     my $uhome=&homeserver($uname,$udom);
                   4835:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4836: 	return 'error: no such user';
                   4837:     }
1.297     matthew  4838:     # Get student data if we were not given enough information
                   4839:     if (!defined($first)  || $first  eq '' || 
                   4840:         !defined($last)   || $last   eq '' || 
                   4841:         !defined($uid)    || $uid    eq '' || 
                   4842:         !defined($middle) || $middle eq '' || 
                   4843:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4844:         # They did not supply us with enough data to enroll the student, so
                   4845:         # we need to pick up more information.
1.297     matthew  4846:         my %tmp = &get('environment',
1.294     matthew  4847:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4848:                        ,$udom,$uname);
                   4849: 
1.800     albertel 4850:         #foreach my $key (keys(%tmp)) {
                   4851:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4852:         #}
1.294     matthew  4853:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4854:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4855:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4856:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4857:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4858:     }
1.556     albertel 4859:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4860:     my $reply=cput('classlist',
                   4861: 		   {"$uname:$udom" => 
1.515     raeburn  4862: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4863: 		   $cdom,$cnum);
1.81      www      4864:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4865: 	return 'error: '.$reply;
1.652     albertel 4866:     } else {
                   4867: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4868:     }
1.297     matthew  4869:     # Add student role to user
1.83      www      4870:     my $uurl='/'.$cid;
1.81      www      4871:     $uurl=~s/\_/\//g;
                   4872:     if ($usec) {
                   4873: 	$uurl.='/'.$usec;
                   4874:     }
                   4875:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4876: }
                   4877: 
1.556     albertel 4878: sub format_name {
                   4879:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4880:     my $name;
                   4881:     if ($first ne 'lastname') {
                   4882: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4883:     } else {
                   4884: 	if ($lastname=~/\S/) {
                   4885: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4886: 	    $name=~s/\s+,/,/;
                   4887: 	} else {
                   4888: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4889: 	}
                   4890:     }
                   4891:     $name=~s/^\s+//;
                   4892:     $name=~s/\s+$//;
                   4893:     $name=~s/\s+/ /g;
                   4894:     return $name;
                   4895: }
                   4896: 
1.84      www      4897: # ------------------------------------------------- Write to course preferences
                   4898: 
                   4899: sub writecoursepref {
                   4900:     my ($courseid,%prefs)=@_;
                   4901:     $courseid=~s/^\///;
                   4902:     $courseid=~s/\_/\//g;
                   4903:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4904:     my $chome=homeserver($cnum,$cdomain);
                   4905:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4906: 	return 'error: no such course';
                   4907:     }
                   4908:     my $cstring='';
1.800     albertel 4909:     foreach my $pref (keys(%prefs)) {
                   4910: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4911:     }
1.84      www      4912:     $cstring=~s/\&$//;
                   4913:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4914: }
                   4915: 
                   4916: # ---------------------------------------------------------- Make/modify course
                   4917: 
                   4918: sub createcourse {
1.741     raeburn  4919:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4920:         $course_owner,$crstype)=@_;
1.84      www      4921:     $url=&declutter($url);
                   4922:     my $cid='';
1.264     matthew  4923:     unless (&allowed('ccc',$udom)) {
1.84      www      4924:         return 'refused';
                   4925:     }
                   4926: # ------------------------------------------------------------------- Create ID
1.674     www      4927:    my $uname=int(1+rand(9)).
                   4928:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4929:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4930:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4931: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4932:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4933:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4934:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4935:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4936:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4937:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4938:            return 'error: unable to generate unique course-ID';
                   4939:        } 
                   4940:    }
1.264     matthew  4941: # ------------------------------------------------ Check supplied server name
1.620     albertel 4942:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4943:     if (! exists($libserv{$course_server})) {
                   4944:         return 'error:bad server name '.$course_server;
                   4945:     }
1.84      www      4946: # ------------------------------------------------------------- Make the course
                   4947:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4948:                       $course_server);
1.84      www      4949:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4950:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4951:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4952: 	return 'error: no such course';
                   4953:     }
1.271     www      4954: # ----------------------------------------------------------------- Course made
1.516     raeburn  4955: # log existence
                   4956:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4957:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4958:                   &escape($crstype),$uhome);
1.358     www      4959:     &flushcourselogs();
                   4960: # set toplevel url
1.271     www      4961:     my $topurl=$url;
                   4962:     unless ($nonstandard) {
                   4963: # ------------------------------------------ For standard courses, make top url
                   4964:         my $mapurl=&clutter($url);
1.278     www      4965:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4966:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4967: <map>
                   4968: <resource id="1" type="start"></resource>
                   4969: <resource id="2" src="$mapurl"></resource>
                   4970: <resource id="3" type="finish"></resource>
                   4971: <link index="1" from="1" to="2"></link>
                   4972: <link index="2" from="2" to="3"></link>
                   4973: </map>
                   4974: ENDINITMAP
                   4975:         $topurl=&declutter(
1.638     albertel 4976:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4977:                           );
                   4978:     }
                   4979: # ----------------------------------------------------------- Write preferences
1.84      www      4980:     &writecoursepref($udom.'_'.$uname,
                   4981:                      ('description' => $description,
1.271     www      4982:                       'url'         => $topurl));
1.84      www      4983:     return '/'.$udom.'/'.$uname;
                   4984: }
                   4985: 
1.813     albertel 4986: sub is_course {
                   4987:     my ($cdom,$cnum) = @_;
                   4988:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   4989: 				undef,'.');
                   4990:     if (exists($courses{$cdom.'_'.$cnum})) {
                   4991:         return 1;
                   4992:     }
                   4993:     return 0;
                   4994: }
                   4995: 
1.21      www      4996: # ---------------------------------------------------------- Assign Custom Role
                   4997: 
                   4998: sub assigncustomrole {
1.357     www      4999:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5000:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5001:                        $end,$start,$deleteflag);
1.21      www      5002: }
                   5003: 
                   5004: # ----------------------------------------------------------------- Revoke Role
                   5005: 
                   5006: sub revokerole {
1.357     www      5007:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5008:     my $now=time;
1.357     www      5009:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5010: }
                   5011: 
                   5012: # ---------------------------------------------------------- Revoke Custom Role
                   5013: 
                   5014: sub revokecustomrole {
1.357     www      5015:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5016:     my $now=time;
1.357     www      5017:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5018:            $deleteflag);
1.17      www      5019: }
                   5020: 
1.533     banghart 5021: # ------------------------------------------------------------ Disk usage
1.535     albertel 5022: sub diskusage {
1.533     banghart 5023:     my ($udom,$uname,$directoryRoot)=@_;
                   5024:     $directoryRoot =~ s/\/$//;
1.535     albertel 5025:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5026:     return $listing;
1.512     banghart 5027: }
                   5028: 
1.566     banghart 5029: sub is_locked {
                   5030:     my ($file_name, $domain, $user) = @_;
                   5031:     my @check;
                   5032:     my $is_locked;
                   5033:     push @check, $file_name;
1.613     albertel 5034:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5035: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5036:     my ($tmp)=keys(%locked);
                   5037:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5038:     
1.566     banghart 5039:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5040:         $is_locked = 'false';
                   5041:         foreach my $entry (@{$locked{$file_name}}) {
                   5042:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5043:                $is_locked = 'true';
                   5044:                last;
1.745     raeburn  5045:            }
                   5046:        }
1.566     banghart 5047:     } else {
                   5048:         $is_locked = 'false';
                   5049:     }
                   5050: }
                   5051: 
1.759     albertel 5052: sub declutter_portfile {
                   5053:     my ($file) = @_;
                   5054:     &logthis("got $file");
                   5055:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5056:     &logthis("ret $file");
                   5057:     return $file;
                   5058: }
                   5059: 
1.559     banghart 5060: # ------------------------------------------------------------- Mark as Read Only
                   5061: 
                   5062: sub mark_as_readonly {
                   5063:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5064:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5065:     my ($tmp)=keys(%current_permissions);
                   5066:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5067:     foreach my $file (@{$files}) {
1.759     albertel 5068: 	$file = &declutter_portfile($file);
1.561     banghart 5069:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5070:     }
1.613     albertel 5071:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5072:     return;
                   5073: }
                   5074: 
1.572     banghart 5075: # ------------------------------------------------------------Save Selected Files
                   5076: 
                   5077: sub save_selected_files {
                   5078:     my ($user, $path, @files) = @_;
                   5079:     my $filename = $user."savedfiles";
1.573     banghart 5080:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5081:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5082:     foreach my $file (@files) {
1.620     albertel 5083:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5084:     }
                   5085:     foreach my $file (@other_files) {
1.574     banghart 5086:         print (OUT $file."\n");
1.572     banghart 5087:     }
1.574     banghart 5088:     close (OUT);
1.572     banghart 5089:     return 'ok';
                   5090: }
                   5091: 
1.574     banghart 5092: sub clear_selected_files {
                   5093:     my ($user) = @_;
                   5094:     my $filename = $user."savedfiles";
                   5095:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5096:     print (OUT undef);
                   5097:     close (OUT);
                   5098:     return ("ok");    
                   5099: }
                   5100: 
1.572     banghart 5101: sub files_in_path {
                   5102:     my ($user, $path) = @_;
                   5103:     my $filename = $user."savedfiles";
                   5104:     my %return_files;
1.574     banghart 5105:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5106:     while (my $line_in = <IN>) {
1.574     banghart 5107:         chomp ($line_in);
                   5108:         my @paths_and_file = split (m!/!, $line_in);
                   5109:         my $file_part = pop (@paths_and_file);
                   5110:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5111:         $path_part.='/';
                   5112:         my $path_and_file = $path_part.$file_part;
                   5113:         if ($path_part eq $path) {
                   5114:             $return_files{$file_part}= 'selected';
                   5115:         }
                   5116:     }
1.574     banghart 5117:     close (IN);
                   5118:     return (\%return_files);
1.572     banghart 5119: }
                   5120: 
                   5121: # called in portfolio select mode, to show files selected NOT in current directory
                   5122: sub files_not_in_path {
                   5123:     my ($user, $path) = @_;
                   5124:     my $filename = $user."savedfiles";
                   5125:     my @return_files;
                   5126:     my $path_part;
1.800     albertel 5127:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5128:     while (my $line = <IN>) {
1.572     banghart 5129:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5130:         my @paths_and_file = split(m|/|, $line);
                   5131:         my $file_part = pop(@paths_and_file);
                   5132:         chomp($file_part);
                   5133:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5134:         $path_part .= '/';
                   5135:         my $path_and_file = $path_part.$file_part;
                   5136:         if ($path_part ne $path) {
1.800     albertel 5137:             push(@return_files, ($path_and_file));
1.572     banghart 5138:         }
                   5139:     }
1.800     albertel 5140:     close(OUT);
1.574     banghart 5141:     return (@return_files);
1.572     banghart 5142: }
                   5143: 
1.745     raeburn  5144: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5145: 
1.745     raeburn  5146: sub get_portfile_permissions {
                   5147:     my ($domain,$user) = @_;
1.613     albertel 5148:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5149:     my ($tmp)=keys(%current_permissions);
                   5150:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5151:     return \%current_permissions;
                   5152: }
                   5153: 
                   5154: #---------------------------------------------Get portfolio file access controls
                   5155: 
1.749     raeburn  5156: sub get_access_controls {
1.745     raeburn  5157:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5158:     my %access;
                   5159:     my $real_file = $file;
                   5160:     $file =~ s/\.meta$//;
1.745     raeburn  5161:     if (defined($file)) {
1.749     raeburn  5162:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5163:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5164:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5165:             }
                   5166:         }
1.745     raeburn  5167:     } else {
1.749     raeburn  5168:         foreach my $key (keys(%{$current_permissions})) {
                   5169:             if ($key =~ /\0accesscontrol$/) {
                   5170:                 if (defined($group)) {
                   5171:                     if ($key !~ m-^\Q$group\E/-) {
                   5172:                         next;
                   5173:                     }
                   5174:                 }
                   5175:                 my ($fullpath) = split(/\0/,$key);
                   5176:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5177:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5178:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5179:                     }
                   5180:                 }
                   5181:             }
                   5182:         }
                   5183:     }
                   5184:     return %access;
                   5185: }
                   5186: 
                   5187: sub modify_access_controls {
                   5188:     my ($file_name,$changes,$domain,$user)=@_;
                   5189:     my ($outcome,$deloutcome);
                   5190:     my %store_permissions;
                   5191:     my %new_values;
                   5192:     my %new_control;
                   5193:     my %translation;
                   5194:     my @deletions = ();
                   5195:     my $now = time;
                   5196:     if (exists($$changes{'activate'})) {
                   5197:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5198:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5199:             my $numnew = scalar(@newitems);
                   5200:             for (my $i=0; $i<$numnew; $i++) {
                   5201:                 my $newkey = $newitems[$i];
                   5202:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5203:                 if ($newkey =~ /^\d+:/) { 
                   5204:                     $newkey =~ s/^(\d+)/$newid/;
                   5205:                     $translation{$1} = $newid;
                   5206:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5207:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5208:                     $translation{$1} = $newid;
                   5209:                 }
1.749     raeburn  5210:                 $new_values{$file_name."\0".$newkey} = 
                   5211:                                           $$changes{'activate'}{$newitems[$i]};
                   5212:                 $new_control{$newkey} = $now;
                   5213:             }
                   5214:         }
                   5215:     }
                   5216:     my %todelete;
                   5217:     my %changed_items;
                   5218:     foreach my $action ('delete','update') {
                   5219:         if (exists($$changes{$action})) {
                   5220:             if (ref($$changes{$action}) eq 'HASH') {
                   5221:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5222:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5223:                     if ($action eq 'delete') { 
                   5224:                         $todelete{$itemnum} = 1;
                   5225:                     } else {
                   5226:                         $changed_items{$itemnum} = $key;
                   5227:                     }
                   5228:                 }
1.745     raeburn  5229:             }
                   5230:         }
1.749     raeburn  5231:     }
                   5232:     # get lock on access controls for file.
                   5233:     my $lockhash = {
                   5234:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5235:                                                        ':'.$env{'user.domain'},
                   5236:                    }; 
                   5237:     my $tries = 0;
                   5238:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5239:    
                   5240:     while (($gotlock ne 'ok') && $tries <3) {
                   5241:         $tries ++;
                   5242:         sleep 1;
                   5243:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5244:     }
                   5245:     if ($gotlock eq 'ok') {
                   5246:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5247:         my ($tmp)=keys(%curr_permissions);
                   5248:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5249:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5250:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5251:             if (ref($curr_controls) eq 'HASH') {
                   5252:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5253:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5254:                     if (defined($todelete{$itemnum})) {
                   5255:                         push(@deletions,$file_name."\0".$control_item);
                   5256:                     } else {
                   5257:                         if (defined($changed_items{$itemnum})) {
                   5258:                             $new_control{$changed_items{$itemnum}} = $now;
                   5259:                             push(@deletions,$file_name."\0".$control_item);
                   5260:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5261:                         } else {
                   5262:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5263:                         }
                   5264:                     }
1.745     raeburn  5265:                 }
                   5266:             }
                   5267:         }
1.749     raeburn  5268:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5269:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5270:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5271:         #  remove lock
                   5272:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5273:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5274:         my ($file,$group);
                   5275:         if (&is_course($domain,$user)) {
                   5276:             ($group,$file) = split(/\//,$file_name,2);
                   5277:         } else {
                   5278:             $file = $file_name;
                   5279:         }
                   5280:         my $sqlresult =
                   5281:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5282:                                     $group);
1.749     raeburn  5283:     } else {
                   5284:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5285:     }
1.749     raeburn  5286:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5287: }
                   5288: 
                   5289: #------------------------------------------------------Get Marked as Read Only
                   5290: 
                   5291: sub get_marked_as_readonly {
                   5292:     my ($domain,$user,$what,$group) = @_;
                   5293:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5294:     my @readonly_files;
1.629     banghart 5295:     my $cmp1=$what;
                   5296:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5297:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5298:         if (defined($group)) {
                   5299:             if ($file_name !~ m-^\Q$group\E/-) {
                   5300:                 next;
                   5301:             }
                   5302:         }
1.561     banghart 5303:         if (ref($value) eq "ARRAY"){
                   5304:             foreach my $stored_what (@{$value}) {
1.629     banghart 5305:                 my $cmp2=$stored_what;
1.759     albertel 5306:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5307:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5308:                 }
1.629     banghart 5309:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5310:                     push(@readonly_files, $file_name);
1.745     raeburn  5311:                     last;
1.563     banghart 5312:                 } elsif (!defined($what)) {
                   5313:                     push(@readonly_files, $file_name);
1.745     raeburn  5314:                     last;
1.561     banghart 5315:                 }
                   5316:             }
1.745     raeburn  5317:         }
1.561     banghart 5318:     }
                   5319:     return @readonly_files;
                   5320: }
1.577     banghart 5321: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5322: 
1.577     banghart 5323: sub get_marked_as_readonly_hash {
1.745     raeburn  5324:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5325:     my %readonly_files;
1.745     raeburn  5326:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5327:         if (defined($group)) {
                   5328:             if ($file_name !~ m-^\Q$group\E/-) {
                   5329:                 next;
                   5330:             }
                   5331:         }
1.577     banghart 5332:         if (ref($value) eq "ARRAY"){
                   5333:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5334:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5335:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5336:                         if ($lock_descriptor eq 'graded') {
                   5337:                             $readonly_files{$file_name} = 'graded';
                   5338:                         } elsif ($lock_descriptor eq 'handback') {
                   5339:                             $readonly_files{$file_name} = 'handback';
                   5340:                         } else {
                   5341:                             if (!exists($readonly_files{$file_name})) {
                   5342:                                 $readonly_files{$file_name} = 'locked';
                   5343:                             }
                   5344:                         }
1.745     raeburn  5345:                     }
1.750     banghart 5346:                 } 
1.577     banghart 5347:             }
                   5348:         } 
                   5349:     }
                   5350:     return %readonly_files;
                   5351: }
1.559     banghart 5352: # ------------------------------------------------------------ Unmark as Read Only
                   5353: 
                   5354: sub unmark_as_readonly {
1.629     banghart 5355:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5356:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5357:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5358:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5359:     my $symb_crs = $what;
                   5360:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5361:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5362:     my ($tmp)=keys(%current_permissions);
                   5363:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5364:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5365:     foreach my $file (@readonly_files) {
1.759     albertel 5366: 	my $clean_file = &declutter_portfile($file);
                   5367: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5368: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5369:         my @new_locks;
                   5370:         my @del_keys;
                   5371:         if (ref($current_locks) eq "ARRAY"){
                   5372:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5373:                 my $compare=$locker;
1.749     raeburn  5374:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5375:                     $compare=join('',@{$locker});
1.746     raeburn  5376:                     if ($compare ne $symb_crs) {
                   5377:                         push(@new_locks, $locker);
                   5378:                     }
1.563     banghart 5379:                 }
                   5380:             }
1.650     albertel 5381:             if (scalar(@new_locks) > 0) {
1.563     banghart 5382:                 $current_permissions{$file} = \@new_locks;
                   5383:             } else {
                   5384:                 push(@del_keys, $file);
1.613     albertel 5385:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5386:                 delete($current_permissions{$file});
1.563     banghart 5387:             }
                   5388:         }
1.561     banghart 5389:     }
1.613     albertel 5390:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5391:     return;
                   5392: }
1.512     banghart 5393: 
1.17      www      5394: # ------------------------------------------------------------ Directory lister
                   5395: 
                   5396: sub dirlist {
1.253     stredwic 5397:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5398: 
1.18      www      5399:     $uri=~s/^\///;
                   5400:     $uri=~s/\/$//;
1.253     stredwic 5401:     my ($udom, $uname);
                   5402:     (undef,$udom,$uname)=split(/\//,$uri);
                   5403:     if(defined($userdomain)) {
                   5404:         $udom = $userdomain;
                   5405:     }
                   5406:     if(defined($username)) {
                   5407:         $uname = $username;
                   5408:     }
                   5409: 
                   5410:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5411:     if(defined($alternateDirectoryRoot)) {
                   5412:         $dirRoot = $alternateDirectoryRoot;
                   5413:         $dirRoot =~ s/\/$//;
1.751     banghart 5414:     }
1.253     stredwic 5415: 
                   5416:     if($udom) {
                   5417:         if($uname) {
1.800     albertel 5418:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5419: 				 &homeserver($uname,$udom));
1.605     matthew  5420:             my @listing_results;
                   5421:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5422:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5423: 				  &homeserver($uname,$udom));
1.605     matthew  5424:                 @listing_results = split(/:/,$listing);
                   5425:             } else {
                   5426:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5427:             }
                   5428:             return @listing_results;
1.253     stredwic 5429:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5430:             my %allusers;
                   5431:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5432:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5433:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5434: 					 $udom, $tryserver);
1.605     matthew  5435:                     my @listing_results;
                   5436:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5437:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5438: 					  $udom, $tryserver);
1.605     matthew  5439:                         @listing_results = split(/:/,$listing);
                   5440:                     } else {
                   5441:                         @listing_results =
                   5442:                             map { &unescape($_); } split(/:/,$listing);
                   5443:                     }
                   5444:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5445:                         $listing_results[0] ne 'empty'       &&
                   5446:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5447:                         foreach my $line (@listing_results) {
                   5448:                             my ($entry) = split(/&/,$line,2);
                   5449:                             $allusers{$entry} = 1;
1.253     stredwic 5450:                         }
                   5451:                     }
1.191     harris41 5452:                 }
1.253     stredwic 5453:             }
                   5454:             my $alluserstr='';
1.800     albertel 5455:             foreach my $user (sort(keys(%allusers))) {
                   5456:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5457:             }
                   5458:             $alluserstr=~s/:$//;
                   5459:             return split(/:/,$alluserstr);
                   5460:         } else {
1.800     albertel 5461:             return ('missing user name');
1.253     stredwic 5462:         }
                   5463:     } elsif(!defined($alternateDirectoryRoot)) {
                   5464:         my $tryserver;
                   5465:         my %alldom=();
1.800     albertel 5466:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5467:             $alldom{$hostdom{$tryserver}}=1;
                   5468:         }
                   5469:         my $alldomstr='';
1.800     albertel 5470:         foreach my $domain (sort(keys(%alldom))) {
                   5471:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5472:         }
                   5473:         $alldomstr=~s/:$//;
                   5474:         return split(/:/,$alldomstr);       
                   5475:     } else {
1.800     albertel 5476:         return ('missing domain');
1.275     stredwic 5477:     }
                   5478: }
                   5479: 
                   5480: # --------------------------------------------- GetFileTimestamp
                   5481: # This function utilizes dirlist and returns the date stamp for
                   5482: # when it was last modified.  It will also return an error of -1
                   5483: # if an error occurs
                   5484: 
1.410     matthew  5485: ##
                   5486: ## FIXME: This subroutine assumes its caller knows something about the
                   5487: ## directory structure of the home server for the student ($root).
                   5488: ## Not a good assumption to make.  Since this is for looking up files
                   5489: ## in user directories, the full path should be constructed by lond, not
                   5490: ## whatever machine we request data from.
                   5491: ##
1.275     stredwic 5492: sub GetFileTimestamp {
                   5493:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5494:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5495:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5496:     my $subdir=$studentName.'__';
                   5497:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5498:     my $proname="$studentDomain/$subdir/$studentName";
                   5499:     $proname .= '/'.$filename;
1.375     matthew  5500:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5501:                                               $studentName, $root);
1.275     stredwic 5502:     my @stats = split('&', $fileStat);
                   5503:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5504:         # @stats contains first the filename, then the stat output
                   5505:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5506:     } else {
                   5507:         return -1;
1.253     stredwic 5508:     }
1.26      www      5509: }
                   5510: 
1.712     albertel 5511: sub stat_file {
                   5512:     my ($uri) = @_;
1.787     albertel 5513:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5514: 
1.712     albertel 5515:     my ($udom,$uname,$file,$dir);
                   5516:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5517: 	($udom,$uname,$file) =
1.811     albertel 5518: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5519: 	$file = 'userfiles/'.$file;
1.740     www      5520: 	$dir = &propath($udom,$uname);
1.712     albertel 5521:     }
                   5522:     if ($uri =~ m-^/res/-) {
                   5523: 	($udom,$uname) = 
1.807     albertel 5524: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5525: 	$file = $uri;
                   5526:     }
                   5527: 
                   5528:     if (!$udom || !$uname || !$file) {
                   5529: 	# unable to handle the uri
                   5530: 	return ();
                   5531:     }
                   5532: 
                   5533:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5534:     my @stats = split('&', $result);
1.721     banghart 5535:     
1.712     albertel 5536:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5537: 	shift(@stats); #filename is first
                   5538: 	return @stats;
                   5539:     }
                   5540:     return ();
                   5541: }
                   5542: 
1.26      www      5543: # -------------------------------------------------------- Value of a Condition
                   5544: 
1.713     albertel 5545: # gets the value of a specific preevaluated condition
                   5546: #    stored in the string  $env{user.state.<cid>}
                   5547: # or looks up a condition reference in the bighash and if if hasn't
                   5548: # already been evaluated recurses into docondval to get the value of
                   5549: # the condition, then memoizing it to 
                   5550: #   $env{user.state.<cid>.<condition>}
1.40      www      5551: sub directcondval {
                   5552:     my $number=shift;
1.620     albertel 5553:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5554: 	&Apache::lonuserstate::evalstate();
                   5555:     }
1.713     albertel 5556:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5557: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5558:     } elsif ($number =~ /^_/) {
                   5559: 	my $sub_condition;
                   5560: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5561: 		&GDBM_READER(),0640)) {
                   5562: 	    $sub_condition=$bighash{'conditions'.$number};
                   5563: 	    untie(%bighash);
                   5564: 	}
                   5565: 	my $value = &docondval($sub_condition);
                   5566: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5567: 	return $value;
                   5568:     }
1.620     albertel 5569:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5570:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5571:     } else {
                   5572:        return 2;
                   5573:     }
                   5574: }
                   5575: 
1.713     albertel 5576: # get the collection of conditions for this resource
1.26      www      5577: sub condval {
                   5578:     my $condidx=shift;
1.54      www      5579:     my $allpathcond='';
1.713     albertel 5580:     foreach my $cond (split(/\|/,$condidx)) {
                   5581: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5582: 	    $allpathcond.=
                   5583: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5584: 	}
1.191     harris41 5585:     }
1.54      www      5586:     $allpathcond=~s/\|$//;
1.713     albertel 5587:     return &docondval($allpathcond);
                   5588: }
                   5589: 
                   5590: #evaluates an expression of conditions
                   5591: sub docondval {
                   5592:     my ($allpathcond) = @_;
                   5593:     my $result=0;
                   5594:     if ($env{'request.course.id'}
                   5595: 	&& defined($allpathcond)) {
                   5596: 	my $operand='|';
                   5597: 	my @stack;
                   5598: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5599: 	    if ($chunk eq '(') {
                   5600: 		push @stack,($operand,$result);
                   5601: 	    } elsif ($chunk eq ')') {
                   5602: 		my $before=pop @stack;
                   5603: 		if (pop @stack eq '&') {
                   5604: 		    $result=$result>$before?$before:$result;
                   5605: 		} else {
                   5606: 		    $result=$result>$before?$result:$before;
                   5607: 		}
                   5608: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5609: 		$operand=$chunk;
                   5610: 	    } else {
                   5611: 		my $new=directcondval($chunk);
                   5612: 		if ($operand eq '&') {
                   5613: 		    $result=$result>$new?$new:$result;
                   5614: 		} else {
                   5615: 		    $result=$result>$new?$result:$new;
                   5616: 		}
                   5617: 	    }
                   5618: 	}
1.26      www      5619:     }
                   5620:     return $result;
1.421     albertel 5621: }
                   5622: 
                   5623: # ---------------------------------------------------- Devalidate courseresdata
                   5624: 
                   5625: sub devalidatecourseresdata {
                   5626:     my ($coursenum,$coursedomain)=@_;
                   5627:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5628:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5629: }
                   5630: 
1.763     www      5631: 
1.200     www      5632: # --------------------------------------------------- Course Resourcedata Query
                   5633: 
1.624     albertel 5634: sub get_courseresdata {
                   5635:     my ($coursenum,$coursedomain)=@_;
1.200     www      5636:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5637:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5638:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5639:     my %dumpreply;
1.417     albertel 5640:     unless (defined($cached)) {
1.624     albertel 5641: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5642: 	$result=\%dumpreply;
1.251     albertel 5643: 	my ($tmp) = keys(%dumpreply);
                   5644: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5645: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5646: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5647: 	    return $tmp;
1.416     albertel 5648: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5649: 	    $result=undef;
1.599     albertel 5650: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5651: 	}
                   5652:     }
1.624     albertel 5653:     return $result;
                   5654: }
                   5655: 
1.633     albertel 5656: sub devalidateuserresdata {
                   5657:     my ($uname,$udom)=@_;
                   5658:     my $hashid="$udom:$uname";
                   5659:     &devalidate_cache_new('userres',$hashid);
                   5660: }
                   5661: 
1.624     albertel 5662: sub get_userresdata {
                   5663:     my ($uname,$udom)=@_;
                   5664:     #most student don\'t have any data set, check if there is some data
                   5665:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5666: 
                   5667:     my $hashid="$udom:$uname";
                   5668:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5669:     if (!defined($cached)) {
                   5670: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5671: 	$result=\%resourcedata;
                   5672: 	&do_cache_new('userres',$hashid,$result,600);
                   5673:     }
                   5674:     my ($tmp)=keys(%$result);
                   5675:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5676: 	return $result;
                   5677:     }
                   5678:     #error 2 occurs when the .db doesn't exist
                   5679:     if ($tmp!~/error: 2 /) {
1.672     albertel 5680: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5681: 		 " Trying to get resource data for ".
                   5682: 		 $uname." at ".$udom.": ".
                   5683: 		 $tmp."</font>");
                   5684:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5685: 	#&EXT_cache_set($udom,$uname);
                   5686: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5687: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5688:     }
                   5689:     return $tmp;
                   5690: }
                   5691: 
                   5692: sub resdata {
                   5693:     my ($name,$domain,$type,@which)=@_;
                   5694:     my $result;
                   5695:     if ($type eq 'course') {
                   5696: 	$result=&get_courseresdata($name,$domain);
                   5697:     } elsif ($type eq 'user') {
                   5698: 	$result=&get_userresdata($name,$domain);
                   5699:     }
                   5700:     if (!ref($result)) { return $result; }    
1.251     albertel 5701:     foreach my $item (@which) {
1.417     albertel 5702: 	if (defined($result->{$item})) {
                   5703: 	    return $result->{$item};
1.251     albertel 5704: 	}
1.250     albertel 5705:     }
1.291     albertel 5706:     return undef;
1.200     www      5707: }
                   5708: 
1.379     matthew  5709: #
                   5710: # EXT resource caching routines
                   5711: #
                   5712: 
                   5713: sub clear_EXT_cache_status {
1.383     albertel 5714:     &delenv('cache.EXT.');
1.379     matthew  5715: }
                   5716: 
                   5717: sub EXT_cache_status {
                   5718:     my ($target_domain,$target_user) = @_;
1.383     albertel 5719:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5720:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5721:         # We know already the user has no data
                   5722:         return 1;
                   5723:     } else {
                   5724:         return 0;
                   5725:     }
                   5726: }
                   5727: 
                   5728: sub EXT_cache_set {
                   5729:     my ($target_domain,$target_user) = @_;
1.383     albertel 5730:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5731:     #&appenv($cachename => time);
1.379     matthew  5732: }
                   5733: 
1.28      www      5734: # --------------------------------------------------------- Value of a Variable
1.58      www      5735: sub EXT {
1.715     albertel 5736: 
1.395     albertel 5737:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5738:     unless ($varname) { return ''; }
1.218     albertel 5739:     #get real user name/domain, courseid and symb
                   5740:     my $courseid;
1.359     albertel 5741:     my $publicuser;
1.427     www      5742:     if ($symbparm) {
                   5743: 	$symbparm=&get_symb_from_alias($symbparm);
                   5744:     }
1.218     albertel 5745:     if (!($uname && $udom)) {
1.790     albertel 5746:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5747:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5748:     } else {
1.620     albertel 5749: 	$courseid=$env{'request.course.id'};
1.218     albertel 5750:     }
1.48      www      5751:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5752:     my $rest;
1.320     albertel 5753:     if (defined($therest[0])) {
1.48      www      5754:        $rest=join('.',@therest);
                   5755:     } else {
                   5756:        $rest='';
                   5757:     }
1.320     albertel 5758: 
1.57      www      5759:     my $qualifierrest=$qualifier;
                   5760:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5761:     my $spacequalifierrest=$space;
                   5762:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5763:     if ($realm eq 'user') {
1.48      www      5764: # --------------------------------------------------------------- user.resource
                   5765: 	if ($space eq 'resource') {
1.651     albertel 5766: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5767: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5768: 		 &&
1.744     albertel 5769: 		 ($symbparm eq &symbread()) ) {	
                   5770: 		# if we are in the middle of processing the resource the
                   5771: 		# get the value we are planning on committing
                   5772:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5773:                     return $Apache::lonhomework::results{$qualifierrest};
                   5774:                 } else {
                   5775:                     return $Apache::lonhomework::history{$qualifierrest};
                   5776:                 }
1.335     albertel 5777: 	    } else {
1.359     albertel 5778: 		my %restored;
1.620     albertel 5779: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5780: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5781: 		} else {
                   5782: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5783: 		}
1.335     albertel 5784: 		return $restored{$qualifierrest};
                   5785: 	    }
1.48      www      5786: # ----------------------------------------------------------------- user.access
                   5787:         } elsif ($space eq 'access') {
1.218     albertel 5788: 	    # FIXME - not supporting calls for a specific user
1.48      www      5789:             return &allowed($qualifier,$rest);
                   5790: # ------------------------------------------ user.preferences, user.environment
                   5791:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5792: 	    if (($uname eq $env{'user.name'}) &&
                   5793: 		($udom eq $env{'user.domain'})) {
                   5794: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5795: 	    } else {
1.359     albertel 5796: 		my %returnhash;
                   5797: 		if (!$publicuser) {
                   5798: 		    %returnhash=&userenvironment($udom,$uname,
                   5799: 						 $qualifierrest);
                   5800: 		}
1.218     albertel 5801: 		return $returnhash{$qualifierrest};
                   5802: 	    }
1.48      www      5803: # ----------------------------------------------------------------- user.course
                   5804:         } elsif ($space eq 'course') {
1.218     albertel 5805: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5806:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5807: # ------------------------------------------------------------------- user.role
                   5808:         } elsif ($space eq 'role') {
1.218     albertel 5809: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5810:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5811:             if ($qualifier eq 'value') {
                   5812: 		return $role;
                   5813:             } elsif ($qualifier eq 'extent') {
                   5814:                 return $where;
                   5815:             }
                   5816: # ----------------------------------------------------------------- user.domain
                   5817:         } elsif ($space eq 'domain') {
1.218     albertel 5818:             return $udom;
1.48      www      5819: # ------------------------------------------------------------------- user.name
                   5820:         } elsif ($space eq 'name') {
1.218     albertel 5821:             return $uname;
1.48      www      5822: # ---------------------------------------------------- Any other user namespace
1.29      www      5823:         } else {
1.359     albertel 5824: 	    my %reply;
                   5825: 	    if (!$publicuser) {
                   5826: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5827: 	    }
                   5828: 	    return $reply{$qualifierrest};
1.48      www      5829:         }
1.236     www      5830:     } elsif ($realm eq 'query') {
                   5831: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5832:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5833: 						[$spacequalifierrest]);
1.620     albertel 5834: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5835:    } elsif ($realm eq 'request') {
1.48      www      5836: # ------------------------------------------------------------- request.browser
                   5837:         if ($space eq 'browser') {
1.430     www      5838: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5839: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5840: 		    return 1;
                   5841: 		} else {
                   5842: 		    return 0;
                   5843: 		}
                   5844: 	    } else {
1.620     albertel 5845: 		return $env{'browser.'.$qualifier};
1.430     www      5846: 	    }
1.57      www      5847: # ------------------------------------------------------------ request.filename
                   5848:         } else {
1.620     albertel 5849:             return $env{'request.'.$spacequalifierrest};
1.29      www      5850:         }
1.28      www      5851:     } elsif ($realm eq 'course') {
1.48      www      5852: # ---------------------------------------------------------- course.description
1.620     albertel 5853:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5854:     } elsif ($realm eq 'resource') {
1.165     www      5855: 
1.620     albertel 5856: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5857: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5858: 	}
1.693     albertel 5859: 
                   5860: 	if ($space eq 'title') {
                   5861: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5862: 	    return &gettitle($symbparm);
                   5863: 	}
                   5864: 	
                   5865: 	if ($space eq 'map') {
                   5866: 	    my ($map) = &decode_symb($symbparm);
                   5867: 	    return &symbread($map);
                   5868: 	}
                   5869: 
                   5870: 	my ($section, $group, @groups);
1.593     albertel 5871: 	my ($courselevelm,$courselevel);
1.539     albertel 5872: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5873: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5874: 
1.218     albertel 5875: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5876: 
1.60      www      5877: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5878: 	    my $symbp=$symbparm;
1.735     albertel 5879: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5880: 
                   5881: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5882: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5883: 
1.620     albertel 5884: 	    if (($env{'user.name'} eq $uname) &&
                   5885: 		($env{'user.domain'} eq $udom)) {
                   5886: 		$section=$env{'request.course.sec'};
1.733     raeburn  5887:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5888:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5889: 	    } else {
1.539     albertel 5890: 		if (! defined($usection)) {
1.551     albertel 5891: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5892: 		} else {
                   5893: 		    $section = $usection;
                   5894: 		}
1.733     raeburn  5895:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5896: 	    }
                   5897: 
                   5898: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5899: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5900: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5901: 
1.593     albertel 5902: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5903: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5904: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5905: 
1.60      www      5906: # ----------------------------------------------------------- first, check user
1.624     albertel 5907: 
                   5908: 	    my $userreply=&resdata($uname,$udom,'user',
                   5909: 				       ($courselevelr,$courselevelm,
                   5910: 					$courselevel));
                   5911: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5912: 
1.594     albertel 5913: # ------------------------------------------------ second, check some of course
1.684     raeburn  5914:             my $coursereply;
1.691     raeburn  5915:             if (@groups > 0) {
                   5916:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5917:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5918:                 if (defined($coursereply)) { return $coursereply; }
                   5919:             }
1.96      www      5920: 
1.684     raeburn  5921: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5922: 				     $env{'course.'.$courseid.'.domain'},
                   5923: 				     'course',
                   5924: 				     ($seclevelr,$seclevelm,$seclevel,
                   5925: 				      $courselevelr));
1.287     albertel 5926: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5927: 
1.60      www      5928: # ------------------------------------------------------ third, check map parms
1.218     albertel 5929: 	    my %parmhash=();
                   5930: 	    my $thisparm='';
                   5931: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5932: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5933: 		    &GDBM_READER(),0640)) {
1.218     albertel 5934: 		$thisparm=$parmhash{$symbparm};
                   5935: 		untie(%parmhash);
                   5936: 	    }
                   5937: 	    if ($thisparm) { return $thisparm; }
                   5938: 	}
1.594     albertel 5939: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5940: 
1.218     albertel 5941: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5942: 	my $filename;
                   5943: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5944: 	if ($symbparm) {
1.409     www      5945: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5946: 	} else {
1.620     albertel 5947: 	    $filename=$env{'request.filename'};
1.282     albertel 5948: 	}
                   5949: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5950: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5951: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5952: 	if (defined($metadata)) { return $metadata; }
1.142     www      5953: 
1.594     albertel 5954: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5955: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5956: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5957: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5958: 				     $env{'course.'.$courseid.'.domain'},
                   5959: 				     'course',
                   5960: 				     ($courselevelm,$courselevel));
1.593     albertel 5961: 	    if (defined($coursereply)) { return $coursereply; }
                   5962: 	}
1.145     www      5963: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5964: 	unless ($space eq '0') {
1.336     albertel 5965: 	    my @parts=split(/_/,$space);
                   5966: 	    my $id=pop(@parts);
                   5967: 	    my $part=join('_',@parts);
                   5968: 	    if ($part eq '') { $part='0'; }
                   5969: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5970: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5971: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5972: 	}
1.395     albertel 5973: 	if ($recurse) { return undef; }
                   5974: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5975: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5976: 
1.48      www      5977: # ---------------------------------------------------- Any other user namespace
                   5978:     } elsif ($realm eq 'environment') {
                   5979: # ----------------------------------------------------------------- environment
1.620     albertel 5980: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5981: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5982: 	} else {
1.770     albertel 5983: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5984: 		return '';
                   5985: 	    }
1.219     albertel 5986: 	    my %returnhash=&userenvironment($udom,$uname,
                   5987: 					    $spacequalifierrest);
                   5988: 	    return $returnhash{$spacequalifierrest};
                   5989: 	}
1.28      www      5990:     } elsif ($realm eq 'system') {
1.48      www      5991: # ----------------------------------------------------------------- system.time
                   5992: 	if ($space eq 'time') {
                   5993: 	    return time;
                   5994:         }
1.696     albertel 5995:     } elsif ($realm eq 'server') {
                   5996: # ----------------------------------------------------------------- system.time
                   5997: 	if ($space eq 'name') {
                   5998: 	    return $ENV{'SERVER_NAME'};
                   5999:         }
1.28      www      6000:     }
1.48      www      6001:     return '';
1.61      www      6002: }
                   6003: 
1.691     raeburn  6004: sub check_group_parms {
                   6005:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6006:     my @groupitems = ();
                   6007:     my $resultitem;
                   6008:     my @levels = ($symbparm,$mapparm,$what);
                   6009:     foreach my $group (@{$groups}) {
                   6010:         foreach my $level (@levels) {
                   6011:              my $item = $courseid.'.['.$group.'].'.$level;
                   6012:              push(@groupitems,$item);
                   6013:         }
                   6014:     }
                   6015:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6016:                             $env{'course.'.$courseid.'.domain'},
                   6017:                                      'course',@groupitems);
                   6018:     return $coursereply;
                   6019: }
                   6020: 
                   6021: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6022:     my ($courseid,@groups) = @_;
                   6023:     @groups = sort(@groups);
1.691     raeburn  6024:     return @groups;
                   6025: }
                   6026: 
1.395     albertel 6027: sub packages_tab_default {
                   6028:     my ($uri,$varname)=@_;
                   6029:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6030: 
                   6031:     my (@extension,@specifics,$do_default);
                   6032:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6033: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6034: 	if ($pack_type eq 'default') {
                   6035: 	    $do_default=1;
                   6036: 	} elsif ($pack_type eq 'extension') {
                   6037: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6038: 	} else {
                   6039: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6040: 	}
                   6041:     }
                   6042:     # first look for a package that matches the requested part id
                   6043:     foreach my $package (@specifics) {
                   6044: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6045: 	next if ($pack_part ne $part);
                   6046: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6047: 	    return $packagetab{"$pack_type&$name&default"};
                   6048: 	}
                   6049:     }
                   6050:     # look for any possible matching non extension_ package
                   6051:     foreach my $package (@specifics) {
                   6052: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6053: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6054: 	    return $packagetab{"$pack_type&$name&default"};
                   6055: 	}
1.585     albertel 6056: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6057: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6058: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6059: 	}
                   6060:     }
1.738     albertel 6061:     # look for any posible extension_ match
                   6062:     foreach my $package (@extension) {
                   6063: 	my ($package,$pack_type)=@{$package};
                   6064: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6065: 	    return $packagetab{"$pack_type&$name&default"};
                   6066: 	}
                   6067: 	if (defined($packagetab{$package."&$name&default"})) {
                   6068: 	    return $packagetab{$package."&$name&default"};
                   6069: 	}
                   6070:     }
                   6071:     # look for a global default setting
                   6072:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6073: 	return $packagetab{"default&$name&default"};
                   6074:     }
1.395     albertel 6075:     return undef;
                   6076: }
                   6077: 
1.334     albertel 6078: sub add_prefix_and_part {
                   6079:     my ($prefix,$part)=@_;
                   6080:     my $keyroot;
                   6081:     if (defined($prefix) && $prefix !~ /^__/) {
                   6082: 	# prefix that has a part already
                   6083: 	$keyroot=$prefix;
                   6084:     } elsif (defined($prefix)) {
                   6085: 	# prefix that is missing a part
                   6086: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6087:     } else {
                   6088: 	# no prefix at all
                   6089: 	if (defined($part)) { $keyroot='_'.$part; }
                   6090:     }
                   6091:     return $keyroot;
                   6092: }
                   6093: 
1.71      www      6094: # ---------------------------------------------------------------- Get metadata
                   6095: 
1.599     albertel 6096: my %metaentry;
1.71      www      6097: sub metadata {
1.176     www      6098:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6099:     $uri=&declutter($uri);
1.288     albertel 6100:     # if it is a non metadata possible uri return quickly
1.529     albertel 6101:     if (($uri eq '') || 
                   6102: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6103: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6104:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6105: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6106: 	return undef;
1.288     albertel 6107:     }
1.73      www      6108:     my $filename=$uri;
                   6109:     $uri=~s/\.meta$//;
1.172     www      6110: #
                   6111: # Is the metadata already cached?
1.177     www      6112: # Look at timestamp of caching
1.172     www      6113: # Everything is cached by the main uri, libraries are never directly cached
                   6114: #
1.428     albertel 6115:     if (!defined($liburi)) {
1.599     albertel 6116: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6117: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6118:     }
                   6119:     {
1.172     www      6120: #
                   6121: # Is this a recursive call for a library?
                   6122: #
1.599     albertel 6123: #	if (! exists($metacache{$uri})) {
                   6124: #	    $metacache{$uri}={};
                   6125: #	}
1.171     www      6126:         if ($liburi) {
                   6127: 	    $liburi=&declutter($liburi);
                   6128:             $filename=$liburi;
1.401     bowersj2 6129:         } else {
1.599     albertel 6130: 	    &devalidate_cache_new('meta',$uri);
                   6131: 	    undef(%metaentry);
1.401     bowersj2 6132: 	}
1.140     www      6133:         my %metathesekeys=();
1.73      www      6134:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6135: 	my $metastring;
1.768     albertel 6136: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6137: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6138: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6139: 	    $metastring=&getfile($file);
1.489     albertel 6140: 	}
1.208     albertel 6141:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6142:         my $token;
1.140     www      6143:         undef %metathesekeys;
1.71      www      6144:         while ($token=$parser->get_token) {
1.339     albertel 6145: 	    if ($token->[0] eq 'S') {
                   6146: 		if (defined($token->[2]->{'package'})) {
1.172     www      6147: #
                   6148: # This is a package - get package info
                   6149: #
1.339     albertel 6150: 		    my $package=$token->[2]->{'package'};
                   6151: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6152: 		    if (defined($token->[2]->{'id'})) { 
                   6153: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6154: 		    }
1.599     albertel 6155: 		    if ($metaentry{':packages'}) {
                   6156: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6157: 		    } else {
1.599     albertel 6158: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6159: 		    }
1.736     albertel 6160: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6161: 			my $part=$keyroot;
                   6162: 			$part=~s/^\_//;
1.736     albertel 6163: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6164: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6165: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6166: 			    # ignore package.tab specified default values
                   6167:                             # here &package_tab_default() will fetch those
                   6168: 			    if ($subp eq 'default') { next; }
1.736     albertel 6169: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6170: 			    my $unikey;
                   6171: 			    if ($pack =~ /_0$/) {
                   6172: 				$unikey='parameter_0_'.$name;
                   6173: 				$part=0;
                   6174: 			    } else {
                   6175: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6176: 			    }
1.339     albertel 6177: 			    if ($subp eq 'display') {
                   6178: 				$value.=' [Part: '.$part.']';
                   6179: 			    }
1.599     albertel 6180: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6181: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6182: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6183: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6184: 			    }
1.599     albertel 6185: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6186: 				$metaentry{':'.$unikey}=
                   6187: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6188: 			    }
1.339     albertel 6189: 			}
                   6190: 		    }
                   6191: 		} else {
1.172     www      6192: #
                   6193: # This is not a package - some other kind of start tag
1.339     albertel 6194: #
                   6195: 		    my $entry=$token->[1];
                   6196: 		    my $unikey;
                   6197: 		    if ($entry eq 'import') {
                   6198: 			$unikey='';
                   6199: 		    } else {
                   6200: 			$unikey=$entry;
                   6201: 		    }
                   6202: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6203: 
                   6204: 		    if (defined($token->[2]->{'id'})) { 
                   6205: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6206: 		    }
1.175     www      6207: 
1.339     albertel 6208: 		    if ($entry eq 'import') {
1.175     www      6209: #
                   6210: # Importing a library here
1.339     albertel 6211: #
                   6212: 			if ($depthcount<20) {
                   6213: 			    my $location=$parser->get_text('/import');
                   6214: 			    my $dir=$filename;
                   6215: 			    $dir=~s|[^/]*$||;
                   6216: 			    $location=&filelocation($dir,$location);
1.736     albertel 6217: 			    my $metadata = 
                   6218: 				&metadata($uri,'keys', $location,$unikey,
                   6219: 					  $depthcount+1);
                   6220: 			    foreach my $meta (split(',',$metadata)) {
                   6221: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6222: 				$metathesekeys{$meta}=1;
1.339     albertel 6223: 			    }
                   6224: 			}
                   6225: 		    } else { 
                   6226: 			
                   6227: 			if (defined($token->[2]->{'name'})) { 
                   6228: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6229: 			}
                   6230: 			$metathesekeys{$unikey}=1;
1.736     albertel 6231: 			foreach my $param (@{$token->[3]}) {
                   6232: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6233: 				$token->[2]->{$param};
1.339     albertel 6234: 			}
                   6235: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6236: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6237: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6238: 		 # only ws inside the tag, and not in default, so use default
                   6239: 		 # as value
1.599     albertel 6240: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6241: 			} else {
1.321     albertel 6242: 		  # either something interesting inside the tag or default
                   6243:                   # uninteresting
1.599     albertel 6244: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6245: 			}
1.172     www      6246: # end of not-a-package not-a-library import
1.339     albertel 6247: 		    }
1.172     www      6248: # end of not-a-package start tag
1.339     albertel 6249: 		}
1.172     www      6250: # the next is the end of "start tag"
1.339     albertel 6251: 	    }
                   6252: 	}
1.483     albertel 6253: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6254: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6255: 	    #no specific packages #how's our extension
                   6256: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6257: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6258: 					 \%metathesekeys);
                   6259: 	}
1.599     albertel 6260: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6261: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6262: 		#no specific packages well let's get default then
                   6263: 		if ($key!~/^default&/) { next; }
1.488     albertel 6264: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6265: 					     \%metathesekeys);
                   6266: 	    }
                   6267: 	}
1.338     www      6268: # are there custom rights to evaluate
1.599     albertel 6269: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6270: 
1.338     www      6271:     #
                   6272:     # Importing a rights file here
1.339     albertel 6273:     #
                   6274: 	    unless ($depthcount) {
1.599     albertel 6275: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6276: 		my $dir=$filename;
                   6277: 		$dir=~s|[^/]*$||;
                   6278: 		$location=&filelocation($dir,$location);
1.736     albertel 6279: 		my $rights_metadata =
                   6280: 		    &metadata($uri,'keys',$location,'_rights',
                   6281: 			      $depthcount+1);
                   6282: 		foreach my $rights (split(',',$rights_metadata)) {
                   6283: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6284: 		    $metathesekeys{$rights}=1;
1.339     albertel 6285: 		}
                   6286: 	    }
                   6287: 	}
1.737     albertel 6288: 	# uniqifiy package listing
                   6289: 	my %seen;
                   6290: 	my @uniq_packages =
                   6291: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6292: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6293: 
                   6294: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6295: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6296: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6297: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6298: # this is the end of "was not already recently cached
1.71      www      6299:     }
1.599     albertel 6300:     return $metaentry{':'.$what};
1.261     albertel 6301: }
                   6302: 
1.488     albertel 6303: sub metadata_create_package_def {
1.483     albertel 6304:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6305:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6306:     if ($subp eq 'default') { next; }
                   6307:     
1.599     albertel 6308:     if (defined($metaentry{':packages'})) {
                   6309: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6310:     } else {
1.599     albertel 6311: 	$metaentry{':packages'}=$package;
1.483     albertel 6312:     }
                   6313:     my $value=$packagetab{$key};
                   6314:     my $unikey;
                   6315:     $unikey='parameter_0_'.$name;
1.599     albertel 6316:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6317:     $$metathesekeys{$unikey}=1;
1.599     albertel 6318:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6319: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6320:     }
1.599     albertel 6321:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6322: 	$metaentry{':'.$unikey}=
                   6323: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6324:     }
                   6325: }
                   6326: 
1.261     albertel 6327: sub metadata_generate_part0 {
                   6328:     my ($metadata,$metacache,$uri) = @_;
                   6329:     my %allnames;
1.737     albertel 6330:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6331: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6332: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6333: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6334: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6335: 	    $allnames{$name}=$part;
                   6336: 	  }
                   6337: 	}
                   6338:     }
                   6339:     foreach my $name (keys(%allnames)) {
                   6340:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6341:       my $key=":parameter_0_$name";
1.261     albertel 6342:       $$metacache{"$key.part"}='0';
                   6343:       $$metacache{"$key.name"}=$name;
1.428     albertel 6344:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6345: 					   $allnames{$name}.'_'.$name.
                   6346: 					   '.type'};
1.428     albertel 6347:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6348: 			     '.display'};
1.644     www      6349:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6350:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6351:       $$metacache{"$key.display"}=$olddis;
                   6352:     }
1.71      www      6353: }
                   6354: 
1.764     albertel 6355: # ------------------------------------------------------ Devalidate title cache
                   6356: 
                   6357: sub devalidate_title_cache {
                   6358:     my ($url)=@_;
                   6359:     if (!$env{'request.course.id'}) { return; }
                   6360:     my $symb=&symbread($url);
                   6361:     if (!$symb) { return; }
                   6362:     my $key=$env{'request.course.id'}."\0".$symb;
                   6363:     &devalidate_cache_new('title',$key);
                   6364: }
                   6365: 
1.301     www      6366: # ------------------------------------------------- Get the title of a resource
                   6367: 
                   6368: sub gettitle {
                   6369:     my $urlsymb=shift;
                   6370:     my $symb=&symbread($urlsymb);
1.534     albertel 6371:     if ($symb) {
1.620     albertel 6372: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6373: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6374: 	if (defined($cached)) { 
                   6375: 	    return $result;
                   6376: 	}
1.534     albertel 6377: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6378: 	my $title='';
                   6379: 	my %bighash;
1.620     albertel 6380: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6381: 		&GDBM_READER(),0640)) {
                   6382: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6383: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6384: 	    untie %bighash;
                   6385: 	}
                   6386: 	$title=~s/\&colon\;/\:/gs;
                   6387: 	if ($title) {
1.599     albertel 6388: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6389: 	}
                   6390: 	$urlsymb=$url;
                   6391:     }
                   6392:     my $title=&metadata($urlsymb,'title');
                   6393:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6394:     return $title;
1.301     www      6395: }
1.613     albertel 6396: 
1.614     albertel 6397: sub get_slot {
                   6398:     my ($which,$cnum,$cdom)=@_;
                   6399:     if (!$cnum || !$cdom) {
1.790     albertel 6400: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6401: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6402: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6403:     }
1.703     albertel 6404:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6405:     my %slotinfo;
                   6406:     if (exists($remembered{$key})) {
                   6407: 	$slotinfo{$which} = $remembered{$key};
                   6408:     } else {
                   6409: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6410: 	&Apache::lonhomework::showhash(%slotinfo);
                   6411: 	my ($tmp)=keys(%slotinfo);
                   6412: 	if ($tmp=~/^error:/) { return (); }
                   6413: 	$remembered{$key} = $slotinfo{$which};
                   6414:     }
1.616     albertel 6415:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6416: 	return %{$slotinfo{$which}};
                   6417:     }
                   6418:     return $slotinfo{$which};
1.614     albertel 6419: }
1.31      www      6420: # ------------------------------------------------- Update symbolic store links
                   6421: 
                   6422: sub symblist {
                   6423:     my ($mapname,%newhash)=@_;
1.438     www      6424:     $mapname=&deversion(&declutter($mapname));
1.31      www      6425:     my %hash;
1.620     albertel 6426:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6427:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6428:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6429: 	    foreach my $url (keys %newhash) {
                   6430: 		next if ($url eq 'last_known'
                   6431: 			 && $env{'form.no_update_last_known'});
                   6432: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6433: 						    $newhash{$url}->[1],
                   6434: 						    $newhash{$url}->[0]);
1.191     harris41 6435:             }
1.31      www      6436:             if (untie(%hash)) {
                   6437: 		return 'ok';
                   6438:             }
                   6439:         }
                   6440:     }
                   6441:     return 'error';
1.212     www      6442: }
                   6443: 
                   6444: # --------------------------------------------------------------- Verify a symb
                   6445: 
                   6446: sub symbverify {
1.510     www      6447:     my ($symb,$thisurl)=@_;
                   6448:     my $thisfn=$thisurl;
1.439     www      6449:     $thisfn=&declutter($thisfn);
1.215     www      6450: # direct jump to resource in page or to a sequence - will construct own symbs
                   6451:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6452: # check URL part
1.409     www      6453:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6454: 
1.431     www      6455:     unless ($url eq $thisfn) { return 0; }
1.213     www      6456: 
1.216     www      6457:     $symb=&symbclean($symb);
1.510     www      6458:     $thisurl=&deversion($thisurl);
1.439     www      6459:     $thisfn=&deversion($thisfn);
1.213     www      6460: 
                   6461:     my %bighash;
                   6462:     my $okay=0;
1.431     www      6463: 
1.620     albertel 6464:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6465:                             &GDBM_READER(),0640)) {
1.510     www      6466:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6467:         unless ($ids) { 
1.510     www      6468:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6469:         }
                   6470:         if ($ids) {
                   6471: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6472: 	    foreach my $id (split(/\,/,$ids)) {
                   6473: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6474:                if (
                   6475:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6476:    eq $symb) { 
1.620     albertel 6477: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6478: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6479: 		       $okay=1; 
                   6480: 		   }
                   6481: 	       }
1.216     www      6482: 	   }
                   6483:         }
1.213     www      6484: 	untie(%bighash);
                   6485:     }
                   6486:     return $okay;
1.31      www      6487: }
                   6488: 
1.210     www      6489: # --------------------------------------------------------------- Clean-up symb
                   6490: 
                   6491: sub symbclean {
                   6492:     my $symb=shift;
1.568     albertel 6493:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6494: # remove version from map
                   6495:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6496: 
1.210     www      6497: # remove version from URL
                   6498:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6499: 
1.507     www      6500: # remove wrapper
                   6501: 
1.510     www      6502:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6503:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6504:     return $symb;
1.409     www      6505: }
                   6506: 
                   6507: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6508: 
                   6509: sub encode_symb {
                   6510:     my ($map,$resid,$url)=@_;
                   6511:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6512: }
1.409     www      6513: 
                   6514: sub decode_symb {
1.568     albertel 6515:     my $symb=shift;
                   6516:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6517:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6518:     return (&fixversion($map),$resid,&fixversion($url));
                   6519: }
                   6520: 
                   6521: sub fixversion {
                   6522:     my $fn=shift;
1.609     banghart 6523:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6524:     my %bighash;
                   6525:     my $uri=&clutter($fn);
1.620     albertel 6526:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6527: # is this cached?
1.599     albertel 6528:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6529:     if (defined($cached)) { return $result; }
                   6530: # unfortunately not cached, or expired
1.620     albertel 6531:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6532: 	    &GDBM_READER(),0640)) {
                   6533:  	if ($bighash{'version_'.$uri}) {
                   6534:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6535:  	    unless (($version eq 'mostrecent') || 
                   6536: 		    ($version==&getversion($uri))) {
1.440     www      6537:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6538:  	    }
                   6539:  	}
                   6540:  	untie %bighash;
1.413     www      6541:     }
1.599     albertel 6542:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6543: }
                   6544: 
                   6545: sub deversion {
                   6546:     my $url=shift;
                   6547:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6548:     return $url;
1.210     www      6549: }
                   6550: 
1.31      www      6551: # ------------------------------------------------------ Return symb list entry
                   6552: 
                   6553: sub symbread {
1.249     www      6554:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6555:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6556:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6557: # no filename provided? try from environment
1.44      www      6558:     unless ($thisfn) {
1.620     albertel 6559:         if ($env{'request.symb'}) {
                   6560: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6561: 	}
1.620     albertel 6562: 	$thisfn=$env{'request.filename'};
1.44      www      6563:     }
1.569     albertel 6564:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6565: # is that filename actually a symb? Verify, clean, and return
                   6566:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6567: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6568: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6569: 	}
1.242     www      6570:     }
1.44      www      6571:     $thisfn=declutter($thisfn);
1.31      www      6572:     my %hash;
1.37      www      6573:     my %bighash;
                   6574:     my $syval='';
1.620     albertel 6575:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6576:         my $targetfn = $thisfn;
1.609     banghart 6577:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6578:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6579:         }
1.687     albertel 6580: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6581: 	    $targetfn=$1;
                   6582: 	}
1.620     albertel 6583:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6584:                       &GDBM_READER(),0640)) {
1.481     raeburn  6585: 	    $syval=$hash{$targetfn};
1.37      www      6586:             untie(%hash);
                   6587:         }
                   6588: # ---------------------------------------------------------- There was an entry
                   6589:         if ($syval) {
1.601     albertel 6590: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6591: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6592: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6593: 		    #return $env{$cache_str}='';
1.601     albertel 6594: 		#}    
                   6595: 		#$syval.=$1;
                   6596: 	    #}
1.37      www      6597:         } else {
                   6598: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6599:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6600:                             &GDBM_READER(),0640)) {
1.37      www      6601: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6602:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6603:               unless ($ids) { 
                   6604:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6605:               }
                   6606:               unless ($ids) {
                   6607: # alias?
                   6608: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6609:               }
1.37      www      6610:               if ($ids) {
                   6611: # ------------------------------------------------------------------- Has ID(s)
                   6612:                  my @possibilities=split(/\,/,$ids);
1.39      www      6613:                  if ($#possibilities==0) {
                   6614: # ----------------------------------------------- There is only one possibility
1.37      www      6615: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6616: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6617: 						    $resid,$thisfn);
1.249     www      6618:                  } elsif (!$donotrecurse) {
1.39      www      6619: # ------------------------------------------ There is more than one possibility
                   6620:                      my $realpossible=0;
1.800     albertel 6621:                      foreach my $id (@possibilities) {
                   6622: 			 my $file=$bighash{'src_'.$id};
1.39      www      6623:                          if (&allowed('bre',$file)) {
1.800     albertel 6624:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6625:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6626: 				$realpossible++;
1.626     albertel 6627:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6628: 						    $resid,$thisfn);
1.39      www      6629:                             }
                   6630: 			 }
1.191     harris41 6631:                      }
1.39      www      6632: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6633:                  } else {
                   6634:                      $syval='';
1.37      www      6635:                  }
                   6636: 	      }
                   6637:               untie(%bighash)
1.481     raeburn  6638:            }
1.31      www      6639:         }
1.62      www      6640:         if ($syval) {
1.620     albertel 6641: 	    return $env{$cache_str}=$syval;
1.62      www      6642:         }
1.31      www      6643:     }
1.44      www      6644:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6645:     return $env{$cache_str}='';
1.31      www      6646: }
                   6647: 
                   6648: # ---------------------------------------------------------- Return random seed
                   6649: 
1.32      www      6650: sub numval {
                   6651:     my $txt=shift;
                   6652:     $txt=~tr/A-J/0-9/;
                   6653:     $txt=~tr/a-j/0-9/;
                   6654:     $txt=~tr/K-T/0-9/;
                   6655:     $txt=~tr/k-t/0-9/;
                   6656:     $txt=~tr/U-Z/0-5/;
                   6657:     $txt=~tr/u-z/0-5/;
                   6658:     $txt=~s/\D//g;
1.564     albertel 6659:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6660:     return int($txt);
1.368     albertel 6661: }
                   6662: 
1.484     albertel 6663: sub numval2 {
                   6664:     my $txt=shift;
                   6665:     $txt=~tr/A-J/0-9/;
                   6666:     $txt=~tr/a-j/0-9/;
                   6667:     $txt=~tr/K-T/0-9/;
                   6668:     $txt=~tr/k-t/0-9/;
                   6669:     $txt=~tr/U-Z/0-5/;
                   6670:     $txt=~tr/u-z/0-5/;
                   6671:     $txt=~s/\D//g;
                   6672:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6673:     my $total;
                   6674:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6675:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6676:     return int($total);
                   6677: }
                   6678: 
1.575     albertel 6679: sub numval3 {
                   6680:     use integer;
                   6681:     my $txt=shift;
                   6682:     $txt=~tr/A-J/0-9/;
                   6683:     $txt=~tr/a-j/0-9/;
                   6684:     $txt=~tr/K-T/0-9/;
                   6685:     $txt=~tr/k-t/0-9/;
                   6686:     $txt=~tr/U-Z/0-5/;
                   6687:     $txt=~tr/u-z/0-5/;
                   6688:     $txt=~s/\D//g;
                   6689:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6690:     my $total;
                   6691:     foreach my $val (@txts) { $total+=$val; }
                   6692:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6693:     return $total;
                   6694: }
                   6695: 
1.675     albertel 6696: sub digest {
                   6697:     my ($data)=@_;
                   6698:     my $digest=&Digest::MD5::md5($data);
                   6699:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6700:     my ($e,$f);
                   6701:     {
                   6702:         use integer;
                   6703:         $e=($a+$b);
                   6704:         $f=($c+$d);
                   6705:         if ($_64bit) {
                   6706:             $e=(($e<<32)>>32);
                   6707:             $f=(($f<<32)>>32);
                   6708:         }
                   6709:     }
                   6710:     if (wantarray) {
                   6711: 	return ($e,$f);
                   6712:     } else {
                   6713: 	my $g;
                   6714: 	{
                   6715: 	    use integer;
                   6716: 	    $g=($e+$f);
                   6717: 	    if ($_64bit) {
                   6718: 		$g=(($g<<32)>>32);
                   6719: 	    }
                   6720: 	}
                   6721: 	return $g;
                   6722:     }
                   6723: }
                   6724: 
1.368     albertel 6725: sub latest_rnd_algorithm_id {
1.675     albertel 6726:     return '64bit5';
1.366     albertel 6727: }
1.32      www      6728: 
1.503     albertel 6729: sub get_rand_alg {
                   6730:     my ($courseid)=@_;
1.790     albertel 6731:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6732:     if ($courseid) {
1.620     albertel 6733: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6734:     }
                   6735:     return &latest_rnd_algorithm_id();
                   6736: }
                   6737: 
1.562     albertel 6738: sub validCODE {
                   6739:     my ($CODE)=@_;
                   6740:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6741:     return 0;
                   6742: }
                   6743: 
1.491     albertel 6744: sub getCODE {
1.620     albertel 6745:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6746:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6747: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6748: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6749: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6750:     }
                   6751:     return undef;
                   6752: }
                   6753: 
1.31      www      6754: sub rndseed {
1.155     albertel 6755:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6756: 
1.790     albertel 6757:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6758:     if (!$symb) {
1.366     albertel 6759: 	unless ($symb=$wsymb) { return time; }
                   6760:     }
                   6761:     if (!$courseid) { $courseid=$wcourseid; }
                   6762:     if (!$domain) { $domain=$wdomain; }
                   6763:     if (!$username) { $username=$wusername }
1.503     albertel 6764:     my $which=&get_rand_alg();
1.803     albertel 6765: 
1.491     albertel 6766:     if (defined(&getCODE())) {
1.675     albertel 6767: 	if ($which eq '64bit5') {
                   6768: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6769: 	} elsif ($which eq '64bit4') {
1.575     albertel 6770: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6771: 	} else {
                   6772: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6773: 	}
1.675     albertel 6774:     } elsif ($which eq '64bit5') {
                   6775: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6776:     } elsif ($which eq '64bit4') {
                   6777: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6778:     } elsif ($which eq '64bit3') {
                   6779: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6780:     } elsif ($which eq '64bit2') {
                   6781: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6782:     } elsif ($which eq '64bit') {
                   6783: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6784:     }
                   6785:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6786: }
                   6787: 
                   6788: sub rndseed_32bit {
                   6789:     my ($symb,$courseid,$domain,$username)=@_;
                   6790:     {
                   6791: 	use integer;
                   6792: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6793: 	my $symbseed=numval($symb) << 22;
                   6794: 	my $namechck=unpack("%32C*",$username) << 17;
                   6795: 	my $nameseed=numval($username) << 12;
                   6796: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6797: 	my $courseseed=unpack("%32C*",$courseid);
                   6798: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6799: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6800: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6801: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6802: 	return $num;
                   6803:     }
                   6804: }
                   6805: 
                   6806: sub rndseed_64bit {
                   6807:     my ($symb,$courseid,$domain,$username)=@_;
                   6808:     {
                   6809: 	use integer;
                   6810: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6811: 	my $symbseed=numval($symb) << 10;
                   6812: 	my $namechck=unpack("%32S*",$username);
                   6813: 	
                   6814: 	my $nameseed=numval($username) << 21;
                   6815: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6816: 	my $courseseed=unpack("%32S*",$courseid);
                   6817: 	
                   6818: 	my $num1=$symbchck+$symbseed+$namechck;
                   6819: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6820: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6821: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6822: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6823: 	return "$num1,$num2";
1.155     albertel 6824:     }
1.366     albertel 6825: }
                   6826: 
1.443     albertel 6827: sub rndseed_64bit2 {
                   6828:     my ($symb,$courseid,$domain,$username)=@_;
                   6829:     {
                   6830: 	use integer;
                   6831: 	# strings need to be an even # of cahracters long, it it is odd the
                   6832:         # last characters gets thrown away
                   6833: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6834: 	my $symbseed=numval($symb) << 10;
                   6835: 	my $namechck=unpack("%32S*",$username.' ');
                   6836: 	
                   6837: 	my $nameseed=numval($username) << 21;
1.501     albertel 6838: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6839: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6840: 	
                   6841: 	my $num1=$symbchck+$symbseed+$namechck;
                   6842: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6843: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6844: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6845: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6846: 	return "$num1,$num2";
                   6847:     }
                   6848: }
                   6849: 
                   6850: sub rndseed_64bit3 {
                   6851:     my ($symb,$courseid,$domain,$username)=@_;
                   6852:     {
                   6853: 	use integer;
                   6854: 	# strings need to be an even # of cahracters long, it it is odd the
                   6855:         # last characters gets thrown away
                   6856: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6857: 	my $symbseed=numval2($symb) << 10;
                   6858: 	my $namechck=unpack("%32S*",$username.' ');
                   6859: 	
                   6860: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6861: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6862: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6863: 	
                   6864: 	my $num1=$symbchck+$symbseed+$namechck;
                   6865: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6866: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6867: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6868: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6869: 	
1.503     albertel 6870: 	return "$num1:$num2";
1.443     albertel 6871:     }
                   6872: }
                   6873: 
1.575     albertel 6874: sub rndseed_64bit4 {
                   6875:     my ($symb,$courseid,$domain,$username)=@_;
                   6876:     {
                   6877: 	use integer;
                   6878: 	# strings need to be an even # of cahracters long, it it is odd the
                   6879:         # last characters gets thrown away
                   6880: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6881: 	my $symbseed=numval3($symb) << 10;
                   6882: 	my $namechck=unpack("%32S*",$username.' ');
                   6883: 	
                   6884: 	my $nameseed=numval3($username) << 21;
                   6885: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6886: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6887: 	
                   6888: 	my $num1=$symbchck+$symbseed+$namechck;
                   6889: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6890: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6891: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6892: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6893: 	
                   6894: 	return "$num1:$num2";
                   6895:     }
                   6896: }
                   6897: 
1.675     albertel 6898: sub rndseed_64bit5 {
                   6899:     my ($symb,$courseid,$domain,$username)=@_;
                   6900:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6901:     return "$num1:$num2";
                   6902: }
                   6903: 
1.366     albertel 6904: sub rndseed_CODE_64bit {
                   6905:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6906:     {
1.366     albertel 6907: 	use integer;
1.443     albertel 6908: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6909: 	my $symbseed=numval2($symb);
1.491     albertel 6910: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6911: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6912: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6913: 	my $num1=$symbseed+$CODEchck;
                   6914: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6915: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6916: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6917: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6918: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6919: 	return "$num1:$num2";
1.366     albertel 6920:     }
                   6921: }
                   6922: 
1.575     albertel 6923: sub rndseed_CODE_64bit4 {
                   6924:     my ($symb,$courseid,$domain,$username)=@_;
                   6925:     {
                   6926: 	use integer;
                   6927: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6928: 	my $symbseed=numval3($symb);
                   6929: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6930: 	my $CODEseed=numval3(&getCODE());
                   6931: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6932: 	my $num1=$symbseed+$CODEchck;
                   6933: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6934: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6935: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6936: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6937: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6938: 	return "$num1:$num2";
                   6939:     }
                   6940: }
                   6941: 
1.675     albertel 6942: sub rndseed_CODE_64bit5 {
                   6943:     my ($symb,$courseid,$domain,$username)=@_;
                   6944:     my $code = &getCODE();
                   6945:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6946:     return "$num1:$num2";
                   6947: }
                   6948: 
1.366     albertel 6949: sub setup_random_from_rndseed {
                   6950:     my ($rndseed)=@_;
1.503     albertel 6951:     if ($rndseed =~/([,:])/) {
                   6952: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6953: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6954:     } else {
                   6955: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6956:     }
1.36      albertel 6957: }
                   6958: 
1.474     albertel 6959: sub latest_receipt_algorithm_id {
                   6960:     return 'receipt2';
                   6961: }
                   6962: 
1.480     www      6963: sub recunique {
                   6964:     my $fucourseid=shift;
                   6965:     my $unique;
1.620     albertel 6966:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6967: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6968:     } else {
                   6969: 	$unique=$perlvar{'lonReceipt'};
                   6970:     }
                   6971:     return unpack("%32C*",$unique);
                   6972: }
                   6973: 
                   6974: sub recprefix {
                   6975:     my $fucourseid=shift;
                   6976:     my $prefix;
1.620     albertel 6977:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6978: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6979:     } else {
                   6980: 	$prefix=$perlvar{'lonHostID'};
                   6981:     }
                   6982:     return unpack("%32C*",$prefix);
                   6983: }
                   6984: 
1.76      www      6985: sub ireceipt {
1.474     albertel 6986:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6987:     my $cuname=unpack("%32C*",$funame);
                   6988:     my $cudom=unpack("%32C*",$fudom);
                   6989:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6990:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6991:     my $cunique=&recunique($fucourseid);
1.474     albertel 6992:     my $cpart=unpack("%32S*",$part);
1.480     www      6993:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6994:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6995: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6996: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6997: 			       
                   6998: 	$return.= ($cunique%$cuname+
                   6999: 		   $cunique%$cudom+
                   7000: 		   $cusymb%$cuname+
                   7001: 		   $cusymb%$cudom+
                   7002: 		   $cucourseid%$cuname+
                   7003: 		   $cucourseid%$cudom+
                   7004: 		   $cpart%$cuname+
                   7005: 		   $cpart%$cudom);
                   7006:     } else {
                   7007: 	$return.= ($cunique%$cuname+
                   7008: 		   $cunique%$cudom+
                   7009: 		   $cusymb%$cuname+
                   7010: 		   $cusymb%$cudom+
                   7011: 		   $cucourseid%$cuname+
                   7012: 		   $cucourseid%$cudom);
                   7013:     }
                   7014:     return $return;
1.76      www      7015: }
                   7016: 
                   7017: sub receipt {
1.474     albertel 7018:     my ($part)=@_;
1.790     albertel 7019:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7020:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7021: }
1.260     ng       7022: 
1.790     albertel 7023: sub whichuser {
                   7024:     my ($passedsymb)=@_;
                   7025:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7026:     if (defined($env{'form.grade_symb'})) {
                   7027: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7028: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7029: 	if (!$allowed &&
                   7030: 	    exists($env{'request.course.sec'}) &&
                   7031: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7032: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7033: 			      '/'.$env{'request.course.sec'});
                   7034: 	}
                   7035: 	if ($allowed) {
                   7036: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7037: 	    $courseid=$tmp_courseid;
                   7038: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7039: 	    ($name)=&get_env_multiple('form.grade_username');
                   7040: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7041: 	}
                   7042:     }
                   7043:     if (!$passedsymb) {
                   7044: 	$symb=&symbread();
                   7045:     } else {
                   7046: 	$symb=$passedsymb;
                   7047:     }
                   7048:     $courseid=$env{'request.course.id'};
                   7049:     $domain=$env{'user.domain'};
                   7050:     $name=$env{'user.name'};
                   7051:     if ($name eq 'public' && $domain eq 'public') {
                   7052: 	if (!defined($env{'form.username'})) {
                   7053: 	    $env{'form.username'}.=time.rand(10000000);
                   7054: 	}
                   7055: 	$name.=$env{'form.username'};
                   7056:     }
                   7057:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7058: 
                   7059: }
                   7060: 
1.36      albertel 7061: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7062: # returns either the contents of the file or 
                   7063: # -1 if the file doesn't exist
1.481     raeburn  7064: #
                   7065: # if the target is a file that was uploaded via DOCS, 
                   7066: # a check will be made to see if a current copy exists on the local server,
                   7067: # if it does this will be served, otherwise a copy will be retrieved from
                   7068: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7069: # the local server.   
1.472     albertel 7070: 
1.36      albertel 7071: sub getfile {
1.538     albertel 7072:     my ($file) = @_;
1.609     banghart 7073:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7074:     &repcopy($file);
                   7075:     return &readfile($file);
                   7076: }
                   7077: 
                   7078: sub repcopy_userfile {
                   7079:     my ($file)=@_;
1.609     banghart 7080:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7081:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7082:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7083: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7084:     my ($info,$rtncode);
                   7085:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7086:     if (-e "$file") {
                   7087: 	my @fileinfo = stat($file);
                   7088: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7089: 	if ($lwpresp ne 'ok') {
                   7090: 	    if ($rtncode eq '404') {
1.538     albertel 7091: 		unlink($file);
1.482     albertel 7092: 	    }
1.517     albertel 7093: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7094: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7095: 	    #my $response=$ua->request($request);
                   7096: 	    #if ($response->is_success()) {
                   7097: 	#	return $response->content;
                   7098: 	#    } else {
                   7099: 	#	return -1;
                   7100: 	#    }
1.482     albertel 7101: 	    return -1;
                   7102: 	}
                   7103: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7104: 	    return 'ok';
1.482     albertel 7105: 	}
                   7106: 	$info = '';
1.538     albertel 7107: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7108: 	if ($lwpresp ne 'ok') {
                   7109: 	    return -1;
                   7110: 	}
                   7111:     } else {
1.538     albertel 7112: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7113: 	if ($lwpresp ne 'ok') {
1.517     albertel 7114: 	    my $ua=new LWP::UserAgent;
1.538     albertel 7115: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7116: 	    my $response=$ua->request($request);
                   7117: 	    if ($response->is_success()) {
1.538     albertel 7118: 		$info=$response->content;
1.517     albertel 7119: 	    } else {
                   7120: 		return -1;
                   7121: 	    }
1.482     albertel 7122: 	}
                   7123: 	my @parts = ($cdom,$cnum); 
                   7124: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7125: 	    push @parts, split(/\//,$1);
1.518     albertel 7126: 	}
1.538     albertel 7127: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7128: 	foreach my $part (@parts) {
                   7129: 	    $path .= '/'.$part;
                   7130: 	    if (!-e $path) {
                   7131: 		mkdir($path,0770);
                   7132: 	    }
                   7133: 	}
                   7134:     }
1.538     albertel 7135:     open(FILE,">$file");
1.482     albertel 7136:     print FILE $info;
                   7137:     close(FILE);
1.607     raeburn  7138:     return 'ok';
1.481     raeburn  7139: }
                   7140: 
1.517     albertel 7141: sub tokenwrapper {
                   7142:     my $uri=shift;
1.552     albertel 7143:     $uri=~s|^http\://([^/]+)||;
                   7144:     $uri=~s|^/||;
1.620     albertel 7145:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7146:     my $token=$1;
1.552     albertel 7147:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7148:     if ($udom && $uname && $file) {
                   7149: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7150:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7151:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7152:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7153:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7154:     } else {
                   7155:         return '/adm/notfound.html';
                   7156:     }
                   7157: }
                   7158: 
1.481     raeburn  7159: sub getuploaded {
                   7160:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7161:     $uri=~s/^\///;
                   7162:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7163:     my $ua=new LWP::UserAgent;
                   7164:     my $request=new HTTP::Request($reqtype,$uri);
                   7165:     my $response=$ua->request($request);
                   7166:     $$rtncode = $response->code;
1.482     albertel 7167:     if (! $response->is_success()) {
                   7168: 	return 'failed';
                   7169:     }      
                   7170:     if ($reqtype eq 'HEAD') {
1.486     www      7171: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7172:     } elsif ($reqtype eq 'GET') {
                   7173: 	$$info = $response->content;
1.472     albertel 7174:     }
1.482     albertel 7175:     return 'ok';
1.36      albertel 7176: }
                   7177: 
1.481     raeburn  7178: sub readfile {
                   7179:     my $file = shift;
                   7180:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7181:     my $fh;
                   7182:     open($fh,"<$file");
                   7183:     my $a='';
1.800     albertel 7184:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7185:     return $a;
                   7186: }
                   7187: 
1.36      albertel 7188: sub filelocation {
1.590     banghart 7189:     my ($dir,$file) = @_;
                   7190:     my $location;
                   7191:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7192: 
                   7193:     if ($file =~ m-^/adm/-) {
                   7194: 	$file=~s-^/adm/wrapper/-/-;
                   7195: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7196:     }
1.590     banghart 7197:     if ($file=~m:^/~:) { # is a contruction space reference
                   7198:         $location = $file;
                   7199:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7200:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7201: 	# is a correct contruction space reference
                   7202:         $location = $file;
1.609     banghart 7203:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7204:         my ($udom,$uname,$filename)=
1.811     albertel 7205:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7206:         my $home=&homeserver($uname,$udom);
                   7207:         my $is_me=0;
                   7208:         my @ids=&current_machine_ids();
                   7209:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7210:         if ($is_me) {
1.740     www      7211:   	    $location=&propath($udom,$uname).
1.590     banghart 7212:   	      '/userfiles/'.$filename;
                   7213:         } else {
                   7214:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7215:   	      $udom.'/'.$uname.'/'.$filename;
                   7216:         }
                   7217:     } else {
                   7218:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7219:         $file=~s:^/res/:/:;
                   7220:         if ( !( $file =~ m:^/:) ) {
                   7221:             $location = $dir. '/'.$file;
                   7222:         } else {
                   7223:             $location = '/home/httpd/html/res'.$file;
                   7224:         }
1.59      albertel 7225:     }
1.590     banghart 7226:     $location=~s://+:/:g; # remove duplicate /
                   7227:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7228:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7229:     return $location;
1.46      www      7230: }
1.36      albertel 7231: 
1.46      www      7232: sub hreflocation {
                   7233:     my ($dir,$file)=@_;
1.460     albertel 7234:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7235: 	$file=filelocation($dir,$file);
1.700     albertel 7236:     } elsif ($file=~m-^/adm/-) {
                   7237: 	$file=~s-^/adm/wrapper/-/-;
                   7238: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7239:     }
                   7240:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7241: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7242:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7243: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7244:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7245: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7246: 	    -/uploaded/$1/$2/-x;
1.46      www      7247:     }
1.462     albertel 7248:     return $file;
1.465     albertel 7249: }
                   7250: 
                   7251: sub current_machine_domains {
                   7252:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7253:     my @domains;
                   7254:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7255: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7256: 	if ($hostname eq $name) {
                   7257: 	    push(@domains,$hostdom{$id});
                   7258: 	}
                   7259:     }
                   7260:     return @domains;
                   7261: }
                   7262: 
                   7263: sub current_machine_ids {
                   7264:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7265:     my @ids;
                   7266:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7267: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7268: 	if ($hostname eq $name) {
                   7269: 	    push(@ids,$id);
                   7270: 	}
                   7271:     }
                   7272:     return @ids;
1.31      www      7273: }
                   7274: 
                   7275: # ------------------------------------------------------------- Declutters URLs
                   7276: 
                   7277: sub declutter {
                   7278:     my $thisfn=shift;
1.569     albertel 7279:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7280:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7281:     $thisfn=~s/^\///;
1.697     albertel 7282:     $thisfn=~s|^adm/wrapper/||;
                   7283:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7284:     $thisfn=~s/^res\///;
1.235     www      7285:     $thisfn=~s/\?.+$//;
1.268     www      7286:     return $thisfn;
                   7287: }
                   7288: 
                   7289: # ------------------------------------------------------------- Clutter up URLs
                   7290: 
                   7291: sub clutter {
                   7292:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7293:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7294:        $thisfn='/res'.$thisfn; 
                   7295:     }
1.694     albertel 7296:     if ($thisfn !~m|/adm|) {
1.695     albertel 7297: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7298: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7299: 	} else {
                   7300: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7301: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7302: 	    if ($embstyle eq 'ssi'
                   7303: 		|| ($embstyle eq 'hdn')
                   7304: 		|| ($embstyle eq 'rat')
                   7305: 		|| ($embstyle eq 'prv')
                   7306: 		|| ($embstyle eq 'ign')) {
                   7307: 		#do nothing with these
                   7308: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7309: 		|| ($embstyle eq 'emb')
                   7310: 		|| ($embstyle eq 'wrp')) {
                   7311: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7312: 	    } elsif ($embstyle eq 'unk'
                   7313: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7314: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7315: 	    } else {
1.718     www      7316: #		&logthis("Got a blank emb style");
1.695     albertel 7317: 	    }
1.694     albertel 7318: 	}
                   7319:     }
1.31      www      7320:     return $thisfn;
1.12      www      7321: }
                   7322: 
1.787     albertel 7323: sub clutter_with_no_wrapper {
                   7324:     my $uri = &clutter(shift);
                   7325:     if ($uri =~ m-^/adm/-) {
                   7326: 	$uri =~ s-^/adm/wrapper/-/-;
                   7327: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7328:     }
                   7329:     return $uri;
                   7330: }
                   7331: 
1.557     albertel 7332: sub freeze_escape {
                   7333:     my ($value)=@_;
                   7334:     if (ref($value)) {
                   7335: 	$value=&nfreeze($value);
                   7336: 	return '__FROZEN__'.&escape($value);
                   7337:     }
                   7338:     return &escape($value);
                   7339: }
                   7340: 
1.11      www      7341: 
1.557     albertel 7342: sub thaw_unescape {
                   7343:     my ($value)=@_;
                   7344:     if ($value =~ /^__FROZEN__/) {
                   7345: 	substr($value,0,10,undef);
                   7346: 	$value=&unescape($value);
                   7347: 	return &thaw($value);
                   7348:     }
                   7349:     return &unescape($value);
                   7350: }
                   7351: 
1.436     albertel 7352: sub correct_line_ends {
                   7353:     my ($result)=@_;
                   7354:     $$result =~s/\r\n/\n/mg;
                   7355:     $$result =~s/\r/\n/mg;
1.415     albertel 7356: }
1.1       albertel 7357: # ================================================================ Main Program
                   7358: 
1.184     www      7359: sub goodbye {
1.204     albertel 7360:    &logthis("Starting Shut down");
1.443     albertel 7361: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7362:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7363: #converted
1.599     albertel 7364: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7365:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7366: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7367: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7368: #1.1 only
1.599     albertel 7369: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7370: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7371: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7372: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7373:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7374:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7375:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7376:    &flushcourselogs();
                   7377:    &logthis("Shutting down");
                   7378: }
                   7379: 
1.179     www      7380: BEGIN {
1.228     harris41 7381: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7382:     unless ($readit) {
1.217     harris41 7383: {
1.781     raeburn  7384:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7385:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7386: }
1.1       albertel 7387: 
1.327     albertel 7388: # ------------------------------------------------------------ Read domain file
                   7389: {
                   7390:     %domaindescription = ();
                   7391:     %domain_auth_def = ();
                   7392:     %domain_auth_arg_def = ();
1.448     albertel 7393:     my $fh;
                   7394:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7395: 	while (my $line = <$fh>) {
                   7396:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7397: #           next if /^\#/;
1.801     foxr     7398:            chomp $line;
1.403     www      7399:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7400: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7401: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7402:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7403: 	   $domaindescription{$domain}=$domain_description;
                   7404: 	   $domain_lang_def{$domain}=$def_lang;
                   7405: 	   $domain_city{$domain}=$city;
                   7406: 	   $domain_longi{$domain}=$longi;
                   7407: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7408:            $domain_primary{$domain}=$primary;
1.403     www      7409: 
1.448     albertel 7410:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7411: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7412: 	}
1.327     albertel 7413:     }
1.448     albertel 7414:     close ($fh);
1.327     albertel 7415: }
                   7416: 
                   7417: 
1.1       albertel 7418: # ------------------------------------------------------------- Read hosts file
                   7419: {
1.448     albertel 7420:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7421: 
                   7422:     while (my $configline=<$config>) {
1.303     matthew  7423:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7424:        chomp($configline);
1.595     albertel 7425:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7426:        $name=~s/\s//g;
1.595     albertel 7427:        if ($id && $domain && $role && $name) {
1.252     albertel 7428: 	 $hostname{$id}=$name;
                   7429: 	 $hostdom{$id}=$domain;
                   7430: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7431:        }
1.1       albertel 7432:     }
1.448     albertel 7433:     close($config);
1.619     albertel 7434:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7435:     #&get_iphost();
1.1       albertel 7436: }
                   7437: 
1.598     albertel 7438: sub get_iphost {
                   7439:     if (%iphost) { return %iphost; }
1.653     albertel 7440:     my %name_to_ip;
1.598     albertel 7441:     foreach my $id (keys(%hostname)) {
                   7442: 	my $name=$hostname{$id};
1.653     albertel 7443: 	my $ip;
                   7444: 	if (!exists($name_to_ip{$name})) {
                   7445: 	    $ip = gethostbyname($name);
                   7446: 	    if (!$ip || length($ip) ne 4) {
                   7447: 		&logthis("Skipping host $id name $name no IP found\n");
                   7448: 		next;
                   7449: 	    }
                   7450: 	    $ip=inet_ntoa($ip);
                   7451: 	    $name_to_ip{$name} = $ip;
                   7452: 	} else {
                   7453: 	    $ip = $name_to_ip{$name};
1.598     albertel 7454: 	}
                   7455: 	push(@{$iphost{$ip}},$id);
                   7456:     }
                   7457:     return %iphost;
                   7458: }
                   7459: 
1.1       albertel 7460: # ------------------------------------------------------ Read spare server file
                   7461: {
1.448     albertel 7462:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7463: 
                   7464:     while (my $configline=<$config>) {
                   7465:        chomp($configline);
1.284     matthew  7466:        if ($configline) {
1.784     albertel 7467: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7468: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7469: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7470:        }
                   7471:     }
1.448     albertel 7472:     close($config);
1.1       albertel 7473: }
1.11      www      7474: # ------------------------------------------------------------ Read permissions
                   7475: {
1.448     albertel 7476:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7477: 
                   7478:     while (my $configline=<$config>) {
1.448     albertel 7479: 	chomp($configline);
                   7480: 	if ($configline) {
                   7481: 	    my ($role,$perm)=split(/ /,$configline);
                   7482: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7483: 	}
1.11      www      7484:     }
1.448     albertel 7485:     close($config);
1.11      www      7486: }
                   7487: 
                   7488: # -------------------------------------------- Read plain texts for permissions
                   7489: {
1.448     albertel 7490:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7491: 
                   7492:     while (my $configline=<$config>) {
1.448     albertel 7493: 	chomp($configline);
                   7494: 	if ($configline) {
1.742     raeburn  7495: 	    my ($short,@plain)=split(/:/,$configline);
                   7496:             %{$prp{$short}} = ();
                   7497: 	    if (@plain > 0) {
                   7498:                 $prp{$short}{'std'} = $plain[0];
                   7499:                 for (my $i=1; $i<@plain; $i++) {
                   7500:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7501:                 }
                   7502:             }
1.448     albertel 7503: 	}
1.135     www      7504:     }
1.448     albertel 7505:     close($config);
1.135     www      7506: }
                   7507: 
                   7508: # ---------------------------------------------------------- Read package table
                   7509: {
1.448     albertel 7510:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7511: 
                   7512:     while (my $configline=<$config>) {
1.483     albertel 7513: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7514: 	chomp($configline);
                   7515: 	my ($short,$plain)=split(/:/,$configline);
                   7516: 	my ($pack,$name)=split(/\&/,$short);
                   7517: 	if ($plain ne '') {
                   7518: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7519: 	    $packagetab{$short}=$plain; 
                   7520: 	}
1.11      www      7521:     }
1.448     albertel 7522:     close($config);
1.329     matthew  7523: }
                   7524: 
                   7525: # ------------- set up temporary directory
                   7526: {
                   7527:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7528: 
1.11      www      7529: }
                   7530: 
1.794     albertel 7531: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7532: 				'compress_threshold'=> 20_000,
                   7533:  			        });
1.185     www      7534: 
1.281     www      7535: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7536: $dumpcount=0;
1.22      www      7537: 
1.163     harris41 7538: &logtouch();
1.672     albertel 7539: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7540: $readit=1;
1.564     albertel 7541:     {
                   7542: 	use integer;
                   7543: 	my $test=(2**32)+1;
1.568     albertel 7544: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7545: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7546:     }
1.195     www      7547: }
1.1       albertel 7548: }
1.179     www      7549: 
1.1       albertel 7550: 1;
1.191     harris41 7551: __END__
                   7552: 
1.243     albertel 7553: =pod
                   7554: 
1.191     harris41 7555: =head1 NAME
                   7556: 
1.243     albertel 7557: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7558: 
                   7559: =head1 SYNOPSIS
                   7560: 
1.243     albertel 7561: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7562: 
                   7563:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7564: 
1.243     albertel 7565: Common parameters:
                   7566: 
                   7567: =over 4
                   7568: 
                   7569: =item *
                   7570: 
                   7571: $uname : an internal username (if $cname expecting a course Id specifically)
                   7572: 
                   7573: =item *
                   7574: 
                   7575: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7576: 
                   7577: =item *
                   7578: 
                   7579: $symb : a resource instance identifier
                   7580: 
                   7581: =item *
                   7582: 
                   7583: $namespace : the name of a .db file that contains the data needed or
                   7584: being set.
                   7585: 
                   7586: =back
                   7587: 
1.394     bowersj2 7588: =head1 OVERVIEW
1.191     harris41 7589: 
1.394     bowersj2 7590: lonnet provides subroutines which interact with the
                   7591: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7592: about classes, users, and resources.
1.243     albertel 7593: 
                   7594: For many of these objects you can also use this to store data about
                   7595: them or modify them in various ways.
1.191     harris41 7596: 
1.394     bowersj2 7597: =head2 Symbs
1.191     harris41 7598: 
1.394     bowersj2 7599: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7600: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7601: map, the resource number of the resource in the map, and the URL of
                   7602: the resource itself. The latter is somewhat redundant, but might help
                   7603: if maps change.
                   7604: 
                   7605: An example is
                   7606: 
                   7607:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7608: 
                   7609: The respective map entry is
                   7610: 
                   7611:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7612:   title="Problem 2">
                   7613:  </resource>
                   7614: 
                   7615: Symbs are used by the random number generator, as well as to store and
                   7616: restore data specific to a certain instance of for example a problem.
                   7617: 
                   7618: =head2 Storing And Retrieving Data
                   7619: 
                   7620: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7621: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7622: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7623: is is the non-critical message twin of cstore. These functions are for
                   7624: handlers to store a perl hash to a user's permanent data space in an
                   7625: easy manner, and to retrieve it again on another call. It is expected
                   7626: that a handler would use this once at the beginning to retrieve data,
                   7627: and then again once at the end to send only the new data back.
                   7628: 
                   7629: The data is stored in the user's data directory on the user's
                   7630: homeserver under the ID of the course.
                   7631: 
                   7632: The hash that is returned by restore will have all of the previous
                   7633: value for all of the elements of the hash.
                   7634: 
                   7635: Example:
                   7636: 
                   7637:  #creating a hash
                   7638:  my %hash;
                   7639:  $hash{'foo'}='bar';
                   7640: 
                   7641:  #storing it
                   7642:  &Apache::lonnet::cstore(\%hash);
                   7643: 
                   7644:  #changing a value
                   7645:  $hash{'foo'}='notbar';
                   7646: 
                   7647:  #adding a new value
                   7648:  $hash{'bar'}='foo';
                   7649:  &Apache::lonnet::cstore(\%hash);
                   7650: 
                   7651:  #retrieving the hash
                   7652:  my %history=&Apache::lonnet::restore();
                   7653: 
                   7654:  #print the hash
                   7655:  foreach my $key (sort(keys(%history))) {
                   7656:    print("\%history{$key} = $history{$key}");
                   7657:  }
                   7658: 
                   7659: Will print out:
1.191     harris41 7660: 
1.394     bowersj2 7661:  %history{1:foo} = bar
                   7662:  %history{1:keys} = foo:timestamp
                   7663:  %history{1:timestamp} = 990455579
                   7664:  %history{2:bar} = foo
                   7665:  %history{2:foo} = notbar
                   7666:  %history{2:keys} = foo:bar:timestamp
                   7667:  %history{2:timestamp} = 990455580
                   7668:  %history{bar} = foo
                   7669:  %history{foo} = notbar
                   7670:  %history{timestamp} = 990455580
                   7671:  %history{version} = 2
                   7672: 
                   7673: Note that the special hash entries C<keys>, C<version> and
                   7674: C<timestamp> were added to the hash. C<version> will be equal to the
                   7675: total number of versions of the data that have been stored. The
                   7676: C<timestamp> attribute will be the UNIX time the hash was
                   7677: stored. C<keys> is available in every historical section to list which
                   7678: keys were added or changed at a specific historical revision of a
                   7679: hash.
                   7680: 
                   7681: B<Warning>: do not store the hash that restore returns directly. This
                   7682: will cause a mess since it will restore the historical keys as if the
                   7683: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7684: 
1.394     bowersj2 7685: Calling convention:
1.191     harris41 7686: 
1.394     bowersj2 7687:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7688:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7689: 
1.394     bowersj2 7690: For more detailed information, see lonnet specific documentation.
1.191     harris41 7691: 
1.394     bowersj2 7692: =head1 RETURN MESSAGES
1.191     harris41 7693: 
1.394     bowersj2 7694: =over 4
1.191     harris41 7695: 
1.394     bowersj2 7696: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7697: 
1.394     bowersj2 7698: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7699: when the connection is brought back up
1.191     harris41 7700: 
1.394     bowersj2 7701: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7702: for later delivery
1.191     harris41 7703: 
1.394     bowersj2 7704: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7705: 
1.394     bowersj2 7706: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7707: that was requested
1.191     harris41 7708: 
1.243     albertel 7709: =back
1.191     harris41 7710: 
1.243     albertel 7711: =head1 PUBLIC SUBROUTINES
1.191     harris41 7712: 
1.243     albertel 7713: =head2 Session Environment Functions
1.191     harris41 7714: 
1.243     albertel 7715: =over 4
1.191     harris41 7716: 
1.394     bowersj2 7717: =item * 
                   7718: X<appenv()>
                   7719: B<appenv(%hash)>: the value of %hash is written to
                   7720: the user envirnoment file, and will be restored for each access this
1.620     albertel 7721: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7722: process
1.191     harris41 7723: 
                   7724: =item *
1.394     bowersj2 7725: X<delenv()>
                   7726: B<delenv($regexp)>: removes all items from the session
                   7727: environment file that matches the regular expression in $regexp. The
1.620     albertel 7728: values are also delted from the current processes %env.
1.191     harris41 7729: 
1.795     albertel 7730: =item * get_env_multiple($name) 
                   7731: 
                   7732: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7733: values may be defined and end up as an array ref.
                   7734: 
                   7735: returns an array of values
                   7736: 
1.243     albertel 7737: =back
                   7738: 
                   7739: =head2 User Information
1.191     harris41 7740: 
1.243     albertel 7741: =over 4
1.191     harris41 7742: 
                   7743: =item *
1.394     bowersj2 7744: X<queryauthenticate()>
                   7745: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7746: authentication scheme
                   7747: 
                   7748: =item *
1.394     bowersj2 7749: X<authenticate()>
                   7750: B<authenticate($uname,$upass,$udom)>: try to
                   7751: authenticate user from domain's lib servers (first use the current
                   7752: one). C<$upass> should be the users password.
1.191     harris41 7753: 
                   7754: =item *
1.394     bowersj2 7755: X<homeserver()>
                   7756: B<homeserver($uname,$udom)>: find the server which has
                   7757: the user's directory and files (there must be only one), this caches
                   7758: the answer, and also caches if there is a borken connection.
1.191     harris41 7759: 
                   7760: =item *
1.394     bowersj2 7761: X<idget()>
                   7762: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7763: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7764: username, and only 1 username per ID in a specific domain) (returns
                   7765: hash: id=>name,id=>name)
1.191     harris41 7766: 
                   7767: =item *
1.394     bowersj2 7768: X<idrget()>
                   7769: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7770: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7771: 
                   7772: =item *
1.394     bowersj2 7773: X<idput()>
                   7774: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7775: 
                   7776: =item *
1.394     bowersj2 7777: X<rolesinit()>
                   7778: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7779: 
                   7780: =item *
1.551     albertel 7781: X<getsection()>
                   7782: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7783: course $cname, return section name/number or '' for "not in course"
                   7784: and '-1' for "no section"
                   7785: 
                   7786: =item *
1.394     bowersj2 7787: X<userenvironment()>
                   7788: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7789: passed in @what from the requested user's environment, returns a hash
                   7790: 
                   7791: =back
                   7792: 
                   7793: =head2 User Roles
                   7794: 
                   7795: =over 4
                   7796: 
                   7797: =item *
                   7798: 
1.810     raeburn  7799: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7800:  F: full access
                   7801:  U,I,K: authentication modes (cxx only)
                   7802:  '': forbidden
                   7803:  1: user needs to choose course
                   7804:  2: browse allowed
1.766     albertel 7805:  A: passphrase authentication needed
1.243     albertel 7806: 
                   7807: =item *
                   7808: 
                   7809: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7810: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7811: and course level
                   7812: 
                   7813: =item *
                   7814: 
                   7815: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7816: explanation of a user role term
                   7817: 
                   7818: =back
                   7819: 
                   7820: =head2 User Modification
                   7821: 
                   7822: =over 4
                   7823: 
                   7824: =item *
                   7825: 
                   7826: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7827: user for the level given by URL.  Optional start and end dates (leave empty
                   7828: string or zero for "no date")
1.191     harris41 7829: 
                   7830: =item *
                   7831: 
1.243     albertel 7832: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7833: change a users, password, possible return values are: ok,
                   7834: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7835: refused
1.191     harris41 7836: 
                   7837: =item *
                   7838: 
1.243     albertel 7839: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7840: 
                   7841: =item *
                   7842: 
1.243     albertel 7843: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7844: modify user
1.191     harris41 7845: 
                   7846: =item *
                   7847: 
1.286     matthew  7848: modifystudent
                   7849: 
                   7850: modify a students enrollment and identification information.
                   7851: The course id is resolved based on the current users environment.  
                   7852: This means the envoking user must be a course coordinator or otherwise
                   7853: associated with a course.
                   7854: 
1.297     matthew  7855: This call is essentially a wrapper for lonnet::modifyuser and
                   7856: lonnet::modify_student_enrollment
1.286     matthew  7857: 
                   7858: Inputs: 
                   7859: 
                   7860: =over 4
                   7861: 
                   7862: =item B<$udom> Students loncapa domain
                   7863: 
                   7864: =item B<$uname> Students loncapa login name
                   7865: 
                   7866: =item B<$uid> Students id/student number
                   7867: 
                   7868: =item B<$umode> Students authentication mode
                   7869: 
                   7870: =item B<$upass> Students password
                   7871: 
                   7872: =item B<$first> Students first name
                   7873: 
                   7874: =item B<$middle> Students middle name
                   7875: 
                   7876: =item B<$last> Students last name
                   7877: 
                   7878: =item B<$gene> Students generation
                   7879: 
                   7880: =item B<$usec> Students section in course
                   7881: 
                   7882: =item B<$end> Unix time of the roles expiration
                   7883: 
                   7884: =item B<$start> Unix time of the roles start date
                   7885: 
                   7886: =item B<$forceid> If defined, allow $uid to be changed
                   7887: 
                   7888: =item B<$desiredhome> server to use as home server for student
                   7889: 
                   7890: =back
1.297     matthew  7891: 
                   7892: =item *
                   7893: 
                   7894: modify_student_enrollment
                   7895: 
                   7896: Change a students enrollment status in a class.  The environment variable
                   7897: 'role.request.course' must be defined for this function to proceed.
                   7898: 
                   7899: Inputs:
                   7900: 
                   7901: =over 4
                   7902: 
                   7903: =item $udom, students domain
                   7904: 
                   7905: =item $uname, students name
                   7906: 
                   7907: =item $uid, students user id
                   7908: 
                   7909: =item $first, students first name
                   7910: 
                   7911: =item $middle
                   7912: 
                   7913: =item $last
                   7914: 
                   7915: =item $gene
                   7916: 
                   7917: =item $usec
                   7918: 
                   7919: =item $end
                   7920: 
                   7921: =item $start
                   7922: 
                   7923: =back
                   7924: 
1.191     harris41 7925: 
                   7926: =item *
                   7927: 
1.243     albertel 7928: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7929: custom role; give a custom role to a user for the level given by URL.  Specify
                   7930: name and domain of role author, and role name
1.191     harris41 7931: 
                   7932: =item *
                   7933: 
1.243     albertel 7934: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7935: 
                   7936: =item *
                   7937: 
1.243     albertel 7938: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7939: 
                   7940: =back
                   7941: 
                   7942: =head2 Course Infomation
                   7943: 
                   7944: =over 4
1.191     harris41 7945: 
                   7946: =item *
                   7947: 
1.631     albertel 7948: coursedescription($courseid) : returns a hash of information about the
                   7949: specified course id, including all environment settings for the
                   7950: course, the description of the course will be in the hash under the
                   7951: key 'description'
1.191     harris41 7952: 
                   7953: =item *
                   7954: 
1.624     albertel 7955: resdata($name,$domain,$type,@which) : request for current parameter
                   7956: setting for a specific $type, where $type is either 'course' or 'user',
                   7957: @what should be a list of parameters to ask about. This routine caches
                   7958: answers for 5 minutes.
1.243     albertel 7959: 
                   7960: =back
                   7961: 
                   7962: =head2 Course Modification
                   7963: 
                   7964: =over 4
1.191     harris41 7965: 
                   7966: =item *
                   7967: 
1.243     albertel 7968: writecoursepref($courseid,%prefs) : write preferences (environment
                   7969: database) for a course
1.191     harris41 7970: 
                   7971: =item *
                   7972: 
1.243     albertel 7973: createcourse($udom,$description,$url) : make/modify course
                   7974: 
                   7975: =back
                   7976: 
                   7977: =head2 Resource Subroutines
                   7978: 
                   7979: =over 4
1.191     harris41 7980: 
                   7981: =item *
                   7982: 
1.243     albertel 7983: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7984: 
                   7985: =item *
                   7986: 
1.243     albertel 7987: repcopy($filename) : subscribes to the requested file, and attempts to
                   7988: replicate from the owning library server, Might return
1.607     raeburn  7989: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7990: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7991: resource. Expects the local filesystem pathname
                   7992: (/home/httpd/html/res/....)
                   7993: 
                   7994: =back
                   7995: 
                   7996: =head2 Resource Information
                   7997: 
                   7998: =over 4
1.191     harris41 7999: 
                   8000: =item *
                   8001: 
1.243     albertel 8002: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8003: a vairety of different possible values, $varname should be a request
                   8004: string, and the other parameters can be used to specify who and what
                   8005: one is asking about.
                   8006: 
                   8007: Possible values for $varname are environment.lastname (or other item
                   8008: from the envirnment hash), user.name (or someother aspect about the
                   8009: user), resource.0.maxtries (or some other part and parameter of a
                   8010: resource)
1.204     albertel 8011: 
                   8012: =item *
                   8013: 
1.243     albertel 8014: directcondval($number) : get current value of a condition; reads from a state
                   8015: string
1.204     albertel 8016: 
                   8017: =item *
                   8018: 
1.243     albertel 8019: condval($condidx) : value of condition index based on state
1.204     albertel 8020: 
                   8021: =item *
                   8022: 
1.243     albertel 8023: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8024: resource's metadata, $what should be either a specific key, or either
                   8025: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8026: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8027: 
                   8028: this function automatically caches all requests
1.191     harris41 8029: 
                   8030: =item *
                   8031: 
1.243     albertel 8032: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8033: network of library servers; returns file handle of where SQL and regex results
                   8034: will be stored for query
1.191     harris41 8035: 
                   8036: =item *
                   8037: 
1.243     albertel 8038: symbread($filename) : return symbolic list entry (filename argument optional);
                   8039: returns the data handle
1.191     harris41 8040: 
                   8041: =item *
                   8042: 
1.243     albertel 8043: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8044: a possible symb for the URL in $thisfn, and if is an encryypted
                   8045: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8046: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8047: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8048: 
1.191     harris41 8049: 
                   8050: =item *
                   8051: 
1.243     albertel 8052: symbclean($symb) : removes versions numbers from a symb, returns the
                   8053: cleaned symb
1.191     harris41 8054: 
                   8055: =item *
                   8056: 
1.243     albertel 8057: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8058: course map, user must be in a course for it to work.
1.191     harris41 8059: 
                   8060: =item *
                   8061: 
1.243     albertel 8062: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8063: 
                   8064: =item *
                   8065: 
1.243     albertel 8066: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8067: a random seed, all arguments are optional, if they aren't sent it uses the
                   8068: environment to derive them. Note: if symb isn't sent and it can't get one
                   8069: from &symbread it will use the current time as its return value
1.191     harris41 8070: 
                   8071: =item *
                   8072: 
1.243     albertel 8073: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8074: unfakeable, receipt
1.191     harris41 8075: 
                   8076: =item *
                   8077: 
1.620     albertel 8078: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8079: 
                   8080: =item *
                   8081: 
1.243     albertel 8082: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8083: 
                   8084: =item *
                   8085: 
1.243     albertel 8086: 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 8087: 
                   8088: =item *
                   8089: 
1.243     albertel 8090: 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 8091: 
                   8092: =item *
                   8093: 
1.243     albertel 8094: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8095: 
                   8096: =item *
                   8097: 
1.243     albertel 8098: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8099: forcing spreadsheet to reevaluate the resource scores next time.
                   8100: 
                   8101: =back
                   8102: 
                   8103: =head2 Storing/Retreiving Data
                   8104: 
                   8105: =over 4
1.191     harris41 8106: 
                   8107: =item *
                   8108: 
1.243     albertel 8109: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8110: for this url; hashref needs to be given and should be a \%hashname; the
                   8111: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8112: be derived from the env
1.191     harris41 8113: 
                   8114: =item *
                   8115: 
1.243     albertel 8116: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8117: uses critical subroutine
1.191     harris41 8118: 
                   8119: =item *
                   8120: 
1.243     albertel 8121: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8122: all args are optional
1.191     harris41 8123: 
                   8124: =item *
                   8125: 
1.717     albertel 8126: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8127: dumps the complete (or key matching regexp) namespace into a hash
                   8128: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8129: normally &store()ed into
                   8130: 
                   8131: $range should be either an integer '100' (give me the first 100
                   8132:                                            matching records)
                   8133:               or be  two integers sperated by a - with no spaces
                   8134:                  '30-50' (give me the 30th through the 50th matching
                   8135:                           records)
                   8136: 
                   8137: 
                   8138: =item *
                   8139: 
                   8140: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8141: replaces a &store() version of data with a replacement set of data
                   8142: for a particular resource in a namespace passed in the $storehash hash 
                   8143: reference
                   8144: 
                   8145: =item *
                   8146: 
1.243     albertel 8147: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8148: works very similar to store/cstore, but all data is stored in a
                   8149: temporary location and can be reset using tmpreset, $storehash should
                   8150: be a hash reference, returns nothing on success
1.191     harris41 8151: 
                   8152: =item *
                   8153: 
1.243     albertel 8154: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8155: similar to restore, but all data is stored in a temporary location and
                   8156: can be reset using tmpreset. Returns a hash of values on success,
                   8157: error string otherwise.
1.191     harris41 8158: 
                   8159: =item *
                   8160: 
1.243     albertel 8161: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8162: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8163: 
                   8164: =item *
                   8165: 
1.243     albertel 8166: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8167: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8168: 
                   8169: =item *
                   8170: 
1.243     albertel 8171: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8172: namesp ($udom and $uname are optional)
1.191     harris41 8173: 
                   8174: =item *
                   8175: 
1.702     albertel 8176: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8177: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8178: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8179: 
1.702     albertel 8180: $range should be either an integer '100' (give me the first 100
                   8181:                                            matching records)
                   8182:               or be  two integers sperated by a - with no spaces
                   8183:                  '30-50' (give me the 30th through the 50th matching
                   8184:                           records)
1.449     matthew  8185: =item *
                   8186: 
                   8187: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8188: $store can be a scalar, an array reference, or if the amount to be 
                   8189: incremented is > 1, a hash reference.
                   8190: 
                   8191: ($udom and $uname are optional)
1.191     harris41 8192: 
                   8193: =item *
                   8194: 
1.243     albertel 8195: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8196: ($udom and $uname are optional)
1.191     harris41 8197: 
                   8198: =item *
                   8199: 
1.243     albertel 8200: cput($namespace,$storehash,$udom,$uname) : critical put
                   8201: ($udom and $uname are optional)
1.191     harris41 8202: 
                   8203: =item *
                   8204: 
1.748     albertel 8205: newput($namespace,$storehash,$udom,$uname) :
                   8206: 
                   8207: Attempts to store the items in the $storehash, but only if they don't
                   8208: currently exist, if this succeeds you can be certain that you have 
                   8209: successfully created a new key value pair in the $namespace db.
                   8210: 
                   8211: 
                   8212: Args:
                   8213:  $namespace: name of database to store values to
                   8214:  $storehash: hashref to store to the db
                   8215:  $udom: (optional) domain of user containing the db
                   8216:  $uname: (optional) name of user caontaining the db
                   8217: 
                   8218: Returns:
                   8219:  'ok' -> succeeded in storing all keys of $storehash
                   8220:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8221:                         least <key> already existed in the db (other
                   8222:                         requested keys may also already exist)
                   8223:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8224:  'con_lost' -> unable to contact request server
                   8225:  'refused' -> action was not allowed by remote machine
                   8226: 
                   8227: 
                   8228: =item *
                   8229: 
1.243     albertel 8230: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8231: reference filled in from namesp (encrypts the return communication)
                   8232: ($udom and $uname are optional)
1.191     harris41 8233: 
                   8234: =item *
                   8235: 
1.243     albertel 8236: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8237: critical subroutine
                   8238: 
1.806     raeburn  8239: =item *
                   8240: 
                   8241: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8242: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8243: 
                   8244: =item *
                   8245: 
                   8246: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8247: 
1.243     albertel 8248: =back
                   8249: 
                   8250: =head2 Network Status Functions
                   8251: 
                   8252: =over 4
1.191     harris41 8253: 
                   8254: =item *
                   8255: 
                   8256: dirlist($uri) : return directory list based on URI
                   8257: 
                   8258: =item *
                   8259: 
1.243     albertel 8260: spareserver() : find server with least workload from spare.tab
                   8261: 
                   8262: =back
                   8263: 
                   8264: =head2 Apache Request
                   8265: 
                   8266: =over 4
1.191     harris41 8267: 
                   8268: =item *
                   8269: 
1.243     albertel 8270: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8271: localhost, posts hash
                   8272: 
                   8273: =back
                   8274: 
                   8275: =head2 Data to String to Data
                   8276: 
                   8277: =over 4
1.191     harris41 8278: 
                   8279: =item *
                   8280: 
1.243     albertel 8281: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8282: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8283: 
                   8284: =item *
                   8285: 
1.243     albertel 8286: hashref2str($hashref) : convert a hashref into a string complete with
                   8287: escaping and '=' and '&' separators, supports elements that are
                   8288: arrayrefs and hashrefs
1.191     harris41 8289: 
                   8290: =item *
                   8291: 
1.243     albertel 8292: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8293: with escaping and '&' separators, supports elements that are arrayrefs
                   8294: and hashrefs
1.191     harris41 8295: 
                   8296: =item *
                   8297: 
1.243     albertel 8298: str2hash($string) : convert string to hash using unescaping and
                   8299: splitting on '=' and '&', supports elements that are arrayrefs and
                   8300: hashrefs
1.191     harris41 8301: 
                   8302: =item *
                   8303: 
1.243     albertel 8304: str2array($string) : convert string to hash using unescaping and
                   8305: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8306: 
                   8307: =back
                   8308: 
                   8309: =head2 Logging Routines
                   8310: 
                   8311: =over 4
                   8312: 
                   8313: These routines allow one to make log messages in the lonnet.log and
                   8314: lonnet.perm logfiles.
1.191     harris41 8315: 
                   8316: =item *
                   8317: 
1.243     albertel 8318: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8319: 
                   8320: =item *
                   8321: 
1.243     albertel 8322: logthis() : append message to the normal lonnet.log file, it gets
                   8323: preiodically rolled over and deleted.
1.191     harris41 8324: 
                   8325: =item *
                   8326: 
1.243     albertel 8327: logperm() : append a permanent message to lonnet.perm.log, this log
                   8328: file never gets deleted by any automated portion of the system, only
                   8329: messages of critical importance should go in here.
                   8330: 
                   8331: =back
                   8332: 
                   8333: =head2 General File Helper Routines
                   8334: 
                   8335: =over 4
1.191     harris41 8336: 
                   8337: =item *
                   8338: 
1.481     raeburn  8339: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8340: (a) files in /uploaded
                   8341:   (i) If a local copy of the file exists - 
                   8342:       compares modification date of local copy with last-modified date for 
                   8343:       definitive version stored on home server for course. If local copy is 
                   8344:       stale, requests a new version from the home server and stores it. 
                   8345:       If the original has been removed from the home server, then local copy 
                   8346:       is unlinked.
                   8347:   (ii) If local copy does not exist -
                   8348:       requests the file from the home server and stores it. 
                   8349:   
                   8350:   If $caller is 'uploadrep':  
                   8351:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8352:     for request for files originally uploaded via DOCS. 
                   8353:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8354:   
                   8355:   Otherwise:
                   8356:      This indicates a call from the content generation phase of the request.
                   8357:      -  returns the entire contents of the file or -1.
                   8358:      
                   8359: (b) files in /res
                   8360:    - returns the entire contents of a file or -1; 
                   8361:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8362: 
1.712     albertel 8363: 
                   8364: =item *
                   8365: 
                   8366: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8367:                   reference
                   8368: 
                   8369: returns either a stat() list of data about the file or an empty list
                   8370: if the file doesn't exist or couldn't find out about it (connection
                   8371: problems or user unknown)
                   8372: 
1.191     harris41 8373: =item *
                   8374: 
1.243     albertel 8375: filelocation($dir,$file) : returns file system location of a file
                   8376: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8377: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8378: and a file of ../bob will become /a/bob)
1.191     harris41 8379: 
                   8380: =item *
                   8381: 
                   8382: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8383: filelocation except for hrefs
                   8384: 
                   8385: =item *
                   8386: 
                   8387: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8388: 
1.243     albertel 8389: =back
                   8390: 
1.608     albertel 8391: =head2 Usererfile file routines (/uploaded*)
                   8392: 
                   8393: =over 4
                   8394: 
                   8395: =item *
                   8396: 
                   8397: userfileupload(): main rotine for putting a file in a user or course's
                   8398:                   filespace, arguments are,
                   8399: 
1.620     albertel 8400:  formname - required - this is the name of the element in $env where the
1.608     albertel 8401:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8402:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8403:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8404:  coursedoc - if true, store the file in the course of the active role
                   8405:              of the current user
                   8406:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8407:          if undefined, it will be placed in "unknown"
                   8408: 
                   8409:  (This routine calls clean_filename() to remove any dangerous
                   8410:  characters from the filename, and then calls finuserfileupload() to
                   8411:  complete the transaction)
                   8412: 
                   8413:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8414:  and /adm/notfound.html if unsuccessful
                   8415: 
                   8416: =item *
                   8417: 
                   8418: clean_filename(): routine for cleaing a filename up for storage in
                   8419:                  userfile space, argument is:
                   8420: 
                   8421:  filename - proposed filename
                   8422: 
                   8423: returns: the new clean filename
                   8424: 
                   8425: =item *
                   8426: 
                   8427: finishuserfileupload(): routine that creaes and sends the file to
                   8428: userspace, probably shouldn't be called directly
                   8429: 
                   8430:   docuname: username or courseid of destination for the file
                   8431:   docudom: domain of user/course of destination for the file
                   8432:   formname: same as for userfileupload()
                   8433:   fname: filename (inculding subdirectories) for the file
                   8434: 
                   8435:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8436:  and /adm/notfound.html if unsuccessful
                   8437: 
                   8438: =item *
                   8439: 
                   8440: renameuserfile(): renames an existing userfile to a new name
                   8441: 
                   8442:   Args:
                   8443:    docuname: username or courseid of destination for the file
                   8444:    docudom: domain of user/course of destination for the file
                   8445:    old: current file name (including any subdirs under userfiles)
                   8446:    new: desired file name (including any subdirs under userfiles)
                   8447: 
                   8448: =item *
                   8449: 
                   8450: mkdiruserfile(): creates a directory is a userfiles dir
                   8451: 
                   8452:   Args:
                   8453:    docuname: username or courseid of destination for the file
                   8454:    docudom: domain of user/course of destination for the file
                   8455:    dir: dir to create (including any subdirs under userfiles)
                   8456: 
                   8457: =item *
                   8458: 
                   8459: removeuserfile(): removes a file that exists in userfiles
                   8460: 
                   8461:   Args:
                   8462:    docuname: username or courseid of destination for the file
                   8463:    docudom: domain of user/course of destination for the file
                   8464:    fname: filname to delete (including any subdirs under userfiles)
                   8465: 
                   8466: =item *
                   8467: 
                   8468: removeuploadedurl(): convience function for removeuserfile()
                   8469: 
                   8470:   Args:
                   8471:    url:  a full /uploaded/... url to delete
                   8472: 
1.747     albertel 8473: =item * 
                   8474: 
                   8475: get_portfile_permissions():
                   8476:   Args:
                   8477:     domain: domain of user or course contain the portfolio files
                   8478:     user: name of user or num of course contain the portfolio files
                   8479:   Returns:
                   8480:     hashref of a dump of the proper file_permissions.db
                   8481:    
                   8482: 
                   8483: =item * 
                   8484: 
                   8485: get_access_controls():
                   8486: 
                   8487: Args:
                   8488:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8489:   group: (optional) the group you want the files associated with
                   8490:   file: (optional) the file you want access info on
                   8491: 
                   8492: Returns:
1.749     raeburn  8493:     a hash (keys are file names) of hashes containing
                   8494:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8495:         values are XML containing access control settings (see below) 
1.747     albertel 8496: 
                   8497: Internal notes:
                   8498: 
1.749     raeburn  8499:  access controls are stored in file_permissions.db as key=value pairs.
                   8500:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8501:         where scope -> public,guest,course,group,domains or users.
                   8502:               end -> UNIX time for end of access (0 -> no end date)
                   8503:               start -> UNIX time for start of access
                   8504: 
                   8505:     value -> XML description of access control
                   8506:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8507:             <start></start>
                   8508:             <end></end>
                   8509: 
                   8510:             <password></password>  for scope type = guest
                   8511: 
                   8512:             <domain></domain>     for scope type = course or group
                   8513:             <number></number>
                   8514:             <roles id="">
                   8515:              <role></role>
                   8516:              <access></access>
                   8517:              <section></section>
                   8518:              <group></group>
                   8519:             </roles>
                   8520: 
                   8521:             <dom></dom>         for scope type = domains
                   8522: 
                   8523:             <users>             for scope type = users
                   8524:              <user>
                   8525:               <uname></uname>
                   8526:               <udom></udom>
                   8527:              </user>
                   8528:             </users>
                   8529:            </scope> 
                   8530:               
                   8531:  Access data is also aggregated for each file in an additional key=value pair:
                   8532:  key -> path to file/file_name\0accesscontrol 
                   8533:  value -> reference to hash
                   8534:           hash contains key = value pairs
                   8535:           where key = uniqueID:scope_end_start
                   8536:                 value = UNIX time record was last updated
                   8537: 
                   8538:           Used to improve speed of look-ups of access controls for each file.  
                   8539:  
                   8540:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8541: 
                   8542: modify_access_controls():
                   8543: 
                   8544: Modifies access controls for a portfolio file
                   8545: Args
                   8546: 1. file name
                   8547: 2. reference to hash of required changes,
                   8548: 3. domain
                   8549: 4. username
                   8550:   where domain,username are the domain of the portfolio owner 
                   8551:   (either a user or a course) 
                   8552: 
                   8553: Returns:
                   8554: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8555: 2. result of deletions ('ok' or 'error', with error message).
                   8556: 3. reference to hash of any new or updated access controls.
                   8557: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8558:    key = integer (inbound ID)
                   8559:    value = uniqueID  
1.747     albertel 8560: 
1.608     albertel 8561: =back
                   8562: 
1.243     albertel 8563: =head2 HTTP Helper Routines
                   8564: 
                   8565: =over 4
                   8566: 
1.191     harris41 8567: =item *
                   8568: 
                   8569: escape() : unpack non-word characters into CGI-compatible hex codes
                   8570: 
                   8571: =item *
                   8572: 
                   8573: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8574: 
1.243     albertel 8575: =back
                   8576: 
                   8577: =head1 PRIVATE SUBROUTINES
                   8578: 
                   8579: =head2 Underlying communication routines (Shouldn't call)
                   8580: 
                   8581: =over 4
                   8582: 
                   8583: =item *
                   8584: 
                   8585: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8586: 
                   8587: =item *
                   8588: 
                   8589: reply() : uses subreply to send a message to remote machine, logs all failures
                   8590: 
                   8591: =item *
                   8592: 
                   8593: critical() : passes a critical message to another server; if cannot
                   8594: get through then place message in connection buffer directory and
                   8595: returns con_delayed, if incapable of saving message, returns
                   8596: con_failed
                   8597: 
                   8598: =item *
                   8599: 
                   8600: reconlonc() : tries to reconnect lonc client processes.
                   8601: 
                   8602: =back
                   8603: 
                   8604: =head2 Resource Access Logging
                   8605: 
                   8606: =over 4
                   8607: 
                   8608: =item *
                   8609: 
                   8610: flushcourselogs() : flush (save) buffer logs and access logs
                   8611: 
                   8612: =item *
                   8613: 
                   8614: courselog($what) : save message for course in hash
                   8615: 
                   8616: =item *
                   8617: 
                   8618: courseacclog($what) : save message for course using &courselog().  Perform
                   8619: special processing for specific resource types (problems, exams, quizzes, etc).
                   8620: 
1.191     harris41 8621: =item *
                   8622: 
                   8623: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8624: as a PerlChildExitHandler
1.243     albertel 8625: 
                   8626: =back
                   8627: 
                   8628: =head2 Other
                   8629: 
                   8630: =over 4
                   8631: 
                   8632: =item *
                   8633: 
                   8634: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8635: 
                   8636: =back
                   8637: 
                   8638: =cut

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