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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.816   ! raeburn     4: # $Id: lonnet.pm,v 1.815 2006/12/28 17:36:51 albertel 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.800     albertel  923:     foreach my $line (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    924: 					&homeserver($unam,$udom)))) {
                    925:         my ($key,$value)=split(/\=/,$line,2);
1.298     matthew   926:         $key=&unescape($key);
1.479     albertel  927:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   928:         my $section=$1;
                    929:         if ($key eq $courseid.'_st') { $section=''; }
                    930:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    931:         my $now=time;
1.548     albertel  932:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   933:             $Expired{$end}=$section;
                    934:             next;
                    935:         }
1.548     albertel  936:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   937:             $Pending{$start}=$section;
                    938:             next;
                    939:         }
1.599     albertel  940:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   941:     }
                    942:     #
                    943:     # Presumedly there will be few matching roles from the above
                    944:     # loop and the sorting time will be negligible.
                    945:     if (scalar(keys(%Pending))) {
                    946:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  947:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   948:     } 
                    949:     if (scalar(keys(%Expired))) {
                    950:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    951:         my $time = pop(@sorted);
1.599     albertel  952:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   953:     }
1.599     albertel  954:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   955: }
1.70      www       956: 
1.599     albertel  957: sub save_cache {
                    958:     &purge_remembered();
1.722     albertel  959:     #&Apache::loncommon::validate_page();
1.620     albertel  960:     undef(%env);
1.780     albertel  961:     undef($env_loaded);
1.599     albertel  962: }
1.452     albertel  963: 
1.599     albertel  964: my $to_remember=-1;
                    965: my %remembered;
                    966: my %accessed;
                    967: my $kicks=0;
                    968: my $hits=0;
                    969: sub devalidate_cache_new {
                    970:     my ($name,$id,$debug) = @_;
                    971:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    972:     $id=&escape($name.':'.$id);
                    973:     $memcache->delete($id);
                    974:     delete($remembered{$id});
                    975:     delete($accessed{$id});
                    976: }
                    977: 
                    978: sub is_cached_new {
                    979:     my ($name,$id,$debug) = @_;
                    980:     $id=&escape($name.':'.$id);
                    981:     if (exists($remembered{$id})) {
                    982: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    983: 	$accessed{$id}=[&gettimeofday()];
                    984: 	$hits++;
                    985: 	return ($remembered{$id},1);
                    986:     }
                    987:     my $value = $memcache->get($id);
                    988:     if (!(defined($value))) {
                    989: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  990: 	return (undef,undef);
1.416     albertel  991:     }
1.599     albertel  992:     if ($value eq '__undef__') {
                    993: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    994: 	$value=undef;
                    995:     }
                    996:     &make_room($id,$value,$debug);
                    997:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    998:     return ($value,1);
                    999: }
                   1000: 
                   1001: sub do_cache_new {
                   1002:     my ($name,$id,$value,$time,$debug) = @_;
                   1003:     $id=&escape($name.':'.$id);
                   1004:     my $setvalue=$value;
                   1005:     if (!defined($setvalue)) {
                   1006: 	$setvalue='__undef__';
                   1007:     }
1.623     albertel 1008:     if (!defined($time) ) {
                   1009: 	$time=600;
                   1010:     }
1.599     albertel 1011:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1012:     $memcache->set($id,$setvalue,$time);
                   1013:     # need to make a copy of $value
                   1014:     #&make_room($id,$value,$debug);
1.599     albertel 1015:     return $value;
                   1016: }
                   1017: 
                   1018: sub make_room {
                   1019:     my ($id,$value,$debug)=@_;
                   1020:     $remembered{$id}=$value;
                   1021:     if ($to_remember<0) { return; }
                   1022:     $accessed{$id}=[&gettimeofday()];
                   1023:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1024:     my $to_kick;
                   1025:     my $max_time=0;
                   1026:     foreach my $other (keys(%accessed)) {
                   1027: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1028: 	    $to_kick=$other;
                   1029: 	    $max_time=&tv_interval($accessed{$other});
                   1030: 	}
                   1031:     }
                   1032:     delete($remembered{$to_kick});
                   1033:     delete($accessed{$to_kick});
                   1034:     $kicks++;
                   1035:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1036:     return;
                   1037: }
                   1038: 
1.599     albertel 1039: sub purge_remembered {
1.604     albertel 1040:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1041:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1042:     undef(%remembered);
                   1043:     undef(%accessed);
1.428     albertel 1044: }
1.70      www      1045: # ------------------------------------- Read an entry from a user's environment
                   1046: 
                   1047: sub userenvironment {
                   1048:     my ($udom,$unam,@what)=@_;
                   1049:     my %returnhash=();
                   1050:     my @answer=split(/\&/,
                   1051:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1052:                       &homeserver($unam,$udom)));
                   1053:     my $i;
                   1054:     for ($i=0;$i<=$#what;$i++) {
                   1055: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1056:     }
                   1057:     return %returnhash;
1.1       albertel 1058: }
                   1059: 
1.617     albertel 1060: # ---------------------------------------------------------- Get a studentphoto
                   1061: sub studentphoto {
                   1062:     my ($udom,$unam,$ext) = @_;
                   1063:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1064:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1065:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1066:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1067:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1068:             } else {
                   1069:                 my ($result,$perm_reqd)=
1.707     albertel 1070: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1071:                 if ($result eq 'ok') {
                   1072:                     if (!($perm_reqd eq 'yes')) {
                   1073:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1074:                     }
                   1075:                 }
                   1076:             }
                   1077:         }
                   1078:     } else {
                   1079:         my ($result,$perm_reqd) = 
1.707     albertel 1080: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1081:         if ($result eq 'ok') {
                   1082:             if (!($perm_reqd eq 'yes')) {
                   1083:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1084:             }
                   1085:         }
                   1086:     }
                   1087:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1088: }
                   1089: 
                   1090: sub retrievestudentphoto {
                   1091:     my ($udom,$unam,$ext,$type) = @_;
                   1092:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1093:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1094:     if ($ret eq 'ok') {
                   1095:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1096:         if ($type eq 'thumbnail') {
                   1097:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1098:         }
                   1099:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1100:         return $tokenurl;
                   1101:     } else {
                   1102:         if ($type eq 'thumbnail') {
                   1103:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1104:         } else { 
                   1105:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1106:         }
1.617     albertel 1107:     }
                   1108: }
                   1109: 
1.263     www      1110: # -------------------------------------------------------------------- New chat
                   1111: 
                   1112: sub chatsend {
1.724     raeburn  1113:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1114:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1115:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1116:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1117:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1118: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1119: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1120: }
                   1121: 
                   1122: # ------------------------------------------ Find current version of a resource
                   1123: 
                   1124: sub getversion {
                   1125:     my $fname=&clutter(shift);
                   1126:     unless ($fname=~/^\/res\//) { return -1; }
                   1127:     return &currentversion(&filelocation('',$fname));
                   1128: }
                   1129: 
                   1130: sub currentversion {
                   1131:     my $fname=shift;
1.599     albertel 1132:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1133:     if (defined($cached)) { return $result; }
1.292     www      1134:     my $author=$fname;
                   1135:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1136:     my ($udom,$uname)=split(/\//,$author);
                   1137:     my $home=homeserver($uname,$udom);
                   1138:     if ($home eq 'no_host') { 
                   1139:         return -1; 
                   1140:     }
                   1141:     my $answer=reply("currentversion:$fname",$home);
                   1142:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1143: 	return -1;
                   1144:     }
1.599     albertel 1145:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1146: }
                   1147: 
1.1       albertel 1148: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1149: 
1.1       albertel 1150: sub subscribe {
                   1151:     my $fname=shift;
1.761     raeburn  1152:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1153:     $fname=~s/[\n\r]//g;
1.1       albertel 1154:     my $author=$fname;
                   1155:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1156:     my ($udom,$uname)=split(/\//,$author);
                   1157:     my $home=homeserver($uname,$udom);
1.335     albertel 1158:     if ($home eq 'no_host') {
                   1159:         return 'not_found';
1.1       albertel 1160:     }
                   1161:     my $answer=reply("sub:$fname",$home);
1.64      www      1162:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1163: 	$answer.=' by '.$home;
                   1164:     }
1.1       albertel 1165:     return $answer;
                   1166: }
                   1167:     
1.8       www      1168: # -------------------------------------------------------------- Replicate file
                   1169: 
                   1170: sub repcopy {
                   1171:     my $filename=shift;
1.23      www      1172:     $filename=~s/\/+/\//g;
1.607     raeburn  1173:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1174:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1175:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1176: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1177: 	return &repcopy_userfile($filename);
                   1178:     }
1.532     albertel 1179:     $filename=~s/[\n\r]//g;
1.8       www      1180:     my $transname="$filename.in.transfer";
1.607     raeburn  1181:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1182:     my $remoteurl=subscribe($filename);
1.64      www      1183:     if ($remoteurl =~ /^con_lost by/) {
                   1184: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1185:            return 'unavailable';
1.8       www      1186:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1187: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1188: 	   return 'not_found';
1.64      www      1189:     } elsif ($remoteurl =~ /^rejected by/) {
                   1190: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1191:            return 'forbidden';
1.20      www      1192:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1193:            return 'ok';
1.8       www      1194:     } else {
1.290     www      1195:         my $author=$filename;
                   1196:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1197:         my ($udom,$uname)=split(/\//,$author);
                   1198:         my $home=homeserver($uname,$udom);
                   1199:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1200:            my @parts=split(/\//,$filename);
                   1201:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1202:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1203:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1204: 	       return 'bad_request';
1.8       www      1205:            }
                   1206:            my $count;
                   1207:            for ($count=5;$count<$#parts;$count++) {
                   1208:                $path.="/$parts[$count]";
                   1209:                if ((-e $path)!=1) {
                   1210: 		   mkdir($path,0777);
                   1211:                }
                   1212:            }
                   1213:            my $ua=new LWP::UserAgent;
                   1214:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1215:            my $response=$ua->request($request,$transname);
                   1216:            if ($response->is_error()) {
                   1217: 	       unlink($transname);
                   1218:                my $message=$response->status_line;
1.672     albertel 1219:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1220:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1221:                return 'unavailable';
1.8       www      1222:            } else {
1.16      www      1223: 	       if ($remoteurl!~/\.meta$/) {
                   1224:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1225:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1226:                   if ($mresponse->is_error()) {
                   1227: 		      unlink($filename.'.meta');
                   1228:                       &logthis(
1.672     albertel 1229:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1230:                   }
                   1231: 	       }
1.8       www      1232:                rename($transname,$filename);
1.607     raeburn  1233:                return 'ok';
1.8       www      1234:            }
1.290     www      1235:        }
1.8       www      1236:     }
1.330     www      1237: }
                   1238: 
                   1239: # ------------------------------------------------ Get server side include body
                   1240: sub ssi_body {
1.381     albertel 1241:     my ($filelink,%form)=@_;
1.606     matthew  1242:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1243:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1244:     }
1.330     www      1245:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1246:                                      &ssi($filelink,%form));
1.778     albertel 1247:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1248:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1249:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1250:     return $output;
1.8       www      1251: }
                   1252: 
1.15      www      1253: # --------------------------------------------------------- Server Side Include
                   1254: 
1.782     albertel 1255: sub absolute_url {
                   1256:     my ($host_name) = @_;
                   1257:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1258:     if ($host_name eq '') {
                   1259: 	$host_name = $ENV{'SERVER_NAME'};
                   1260:     }
                   1261:     return $protocol.$host_name;
                   1262: }
                   1263: 
1.15      www      1264: sub ssi {
                   1265: 
1.23      www      1266:     my ($fn,%form)=@_;
1.15      www      1267: 
                   1268:     my $ua=new LWP::UserAgent;
1.23      www      1269:     
                   1270:     my $request;
1.711     albertel 1271: 
                   1272:     $form{'no_update_last_known'}=1;
                   1273: 
1.23      www      1274:     if (%form) {
1.782     albertel 1275:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1276:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1277:     } else {
1.782     albertel 1278:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1279:     }
                   1280: 
1.15      www      1281:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1282:     my $response=$ua->request($request);
                   1283: 
1.324     www      1284:     return $response->content;
                   1285: }
                   1286: 
                   1287: sub externalssi {
                   1288:     my ($url)=@_;
                   1289:     my $ua=new LWP::UserAgent;
                   1290:     my $request=new HTTP::Request('GET',$url);
                   1291:     my $response=$ua->request($request);
1.15      www      1292:     return $response->content;
                   1293: }
1.254     www      1294: 
1.492     albertel 1295: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1296: 
                   1297: sub allowuploaded {
                   1298:     my ($srcurl,$url)=@_;
                   1299:     $url=&clutter(&declutter($url));
                   1300:     my $dir=$url;
                   1301:     $dir=~s/\/[^\/]+$//;
                   1302:     my %httpref=();
                   1303:     my $httpurl=&hreflocation('',$url);
                   1304:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1305:     &Apache::lonnet::appenv(%httpref);
1.254     www      1306: }
1.477     raeburn  1307: 
1.478     albertel 1308: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1309: # input: action, courseID, current domain, intended
1.637     raeburn  1310: #        path to file, source of file, instruction to parse file for objects,
                   1311: #        ref to hash for embedded objects,
                   1312: #        ref to hash for codebase of java objects.
                   1313: #
1.485     raeburn  1314: # output: url to file (if action was uploaddoc), 
                   1315: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1316: #
1.478     albertel 1317: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1318: # course.
1.477     raeburn  1319: #
1.478     albertel 1320: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1321: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1322: #          course's home server.
1.477     raeburn  1323: #
1.478     albertel 1324: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1325: #          be copied from $source (current location) to 
                   1326: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1327: #         and will then be copied to
                   1328: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1329: #         course's home server.
1.485     raeburn  1330: #
1.481     raeburn  1331: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1332: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1333: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1334: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1335: #         in course's home server.
1.637     raeburn  1336: #
1.477     raeburn  1337: 
                   1338: sub process_coursefile {
1.638     albertel 1339:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1340:     my $fetchresult;
1.638     albertel 1341:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1342:     if ($action eq 'propagate') {
1.638     albertel 1343:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1344: 			     $home);
1.481     raeburn  1345:     } else {
1.477     raeburn  1346:         my $fpath = '';
                   1347:         my $fname = $file;
1.478     albertel 1348:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1349:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1350:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1351:         if ($action eq 'copy') {
                   1352:             if ($source eq '') {
                   1353:                 $fetchresult = 'no source file';
                   1354:                 return $fetchresult;
                   1355:             } else {
                   1356:                 my $destination = $filepath.'/'.$fname;
                   1357:                 rename($source,$destination);
                   1358:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1359:                                  $home);
1.481     raeburn  1360:             }
                   1361:         } elsif ($action eq 'uploaddoc') {
                   1362:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1363:             print $fh $env{'form.'.$source};
1.481     raeburn  1364:             close($fh);
1.637     raeburn  1365:             if ($parser eq 'parse') {
                   1366:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1367:                 unless ($parse_result eq 'ok') {
                   1368:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1369:                 }
                   1370:             }
1.477     raeburn  1371:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1372:                                  $home);
1.481     raeburn  1373:             if ($fetchresult eq 'ok') {
                   1374:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1375:             } else {
                   1376:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1377:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1378:                 return '/adm/notfound.html';
                   1379:             }
1.477     raeburn  1380:         }
                   1381:     }
1.485     raeburn  1382:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1383:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1384:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1385:     }
                   1386:     return $fetchresult;
                   1387: }
                   1388: 
1.637     raeburn  1389: sub build_filepath {
                   1390:     my ($fpath) = @_;
                   1391:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1392:     unless ($fpath eq '') {
                   1393:         my @parts=split('/',$fpath);
                   1394:         foreach my $part (@parts) {
                   1395:             $filepath.= '/'.$part;
                   1396:             if ((-e $filepath)!=1) {
                   1397:                 mkdir($filepath,0777);
                   1398:             }
                   1399:         }
                   1400:     }
                   1401:     return $filepath;
                   1402: }
                   1403: 
                   1404: sub store_edited_file {
1.638     albertel 1405:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1406:     my $file = $primary_url;
                   1407:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1408:     my $fpath = '';
                   1409:     my $fname = $file;
                   1410:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1411:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1412:     my $filepath = &build_filepath($fpath);
                   1413:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1414:     print $fh $content;
                   1415:     close($fh);
1.638     albertel 1416:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1417:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1418: 			  $home);
1.637     raeburn  1419:     if ($$fetchresult eq 'ok') {
                   1420:         return '/uploaded/'.$fpath.'/'.$fname;
                   1421:     } else {
1.638     albertel 1422:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1423: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1424:         return '/adm/notfound.html';
                   1425:     }
                   1426: }
                   1427: 
1.531     albertel 1428: sub clean_filename {
                   1429:     my ($fname)=@_;
1.315     www      1430: # Replace Windows backslashes by forward slashes
1.257     www      1431:     $fname=~s/\\/\//g;
1.315     www      1432: # Get rid of everything but the actual filename
1.257     www      1433:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1434: # Replace spaces by underscores
                   1435:     $fname=~s/\s+/\_/g;
                   1436: # Replace all other weird characters by nothing
1.317     www      1437:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1438: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1439: # numbers
                   1440:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1441:     return $fname;
                   1442: }
                   1443: 
1.608     albertel 1444: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1445: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1446: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1447: #        $coursedoc - if true up to the current course
                   1448: #                     if false
                   1449: #        $subdir - directory in userfile to store the file into
                   1450: #        $parser, $allfiles, $codebase - unknown
                   1451: #
                   1452: # output: url of file in userspace, or error: <message> 
                   1453: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1454: 
                   1455: 
1.531     albertel 1456: sub userfileupload {
1.719     banghart 1457:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1458:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1459:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1460:     $fname=&clean_filename($fname);
1.315     www      1461: # See if there is anything left
1.257     www      1462:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1463:     chop($env{'form.'.$formname});
1.523     raeburn  1464:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1465:         my $now = time;
                   1466:         my $filepath = 'tmp/helprequests/'.$now;
                   1467:         my @parts=split(/\//,$filepath);
                   1468:         my $fullpath = $perlvar{'lonDaemons'};
                   1469:         for (my $i=0;$i<@parts;$i++) {
                   1470:             $fullpath .= '/'.$parts[$i];
                   1471:             if ((-e $fullpath)!=1) {
                   1472:                 mkdir($fullpath,0777);
                   1473:             }
                   1474:         }
                   1475:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1476:         print $fh $env{'form.'.$formname};
1.523     raeburn  1477:         close($fh);
1.741     raeburn  1478:         return $fullpath.'/'.$fname;
                   1479:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1480:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1481:                        '_'.$env{'user.domain'}.'/pending';
                   1482:         my @parts=split(/\//,$filepath);
                   1483:         my $fullpath = $perlvar{'lonDaemons'};
                   1484:         for (my $i=0;$i<@parts;$i++) {
                   1485:             $fullpath .= '/'.$parts[$i];
                   1486:             if ((-e $fullpath)!=1) {
                   1487:                 mkdir($fullpath,0777);
                   1488:             }
                   1489:         }
                   1490:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1491:         print $fh $env{'form.'.$formname};
                   1492:         close($fh);
                   1493:         return $fullpath.'/'.$fname;
1.523     raeburn  1494:     }
1.719     banghart 1495:     
1.258     www      1496: # Create the directory if not present
1.493     albertel 1497:     $fname="$subdir/$fname";
1.259     www      1498:     if ($coursedoc) {
1.638     albertel 1499: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1500: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1501:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1502:             return &finishuserfileupload($docuname,$docudom,
                   1503: 					 $formname,$fname,$parser,$allfiles,
                   1504: 					 $codebase);
1.481     raeburn  1505:         } else {
1.620     albertel 1506:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1507:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1508: 				       $fname,$formname,$parser,
                   1509: 				       $allfiles,$codebase);
1.481     raeburn  1510:         }
1.719     banghart 1511:     } elsif (defined($destuname)) {
                   1512:         my $docuname=$destuname;
                   1513:         my $docudom=$destudom;
                   1514: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1515: 				     $fname,$parser,$allfiles,$codebase);
                   1516:         
1.259     www      1517:     } else {
1.638     albertel 1518:         my $docuname=$env{'user.name'};
                   1519:         my $docudom=$env{'user.domain'};
1.714     raeburn  1520:         if (exists($env{'form.group'})) {
                   1521:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1522:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1523:         }
1.638     albertel 1524: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1525: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1526:     }
1.271     www      1527: }
                   1528: 
                   1529: sub finishuserfileupload {
1.638     albertel 1530:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1531:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1532:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1533:     my ($fnamepath,$file);
                   1534:     $file=$fname;
                   1535:     if ($fname=~m|/|) {
                   1536:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1537: 	$path.=$fnamepath.'/';
                   1538:     }
1.259     www      1539:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1540:     my $count;
                   1541:     for ($count=4;$count<=$#parts;$count++) {
                   1542:         $filepath.="/$parts[$count]";
                   1543:         if ((-e $filepath)!=1) {
                   1544: 	    mkdir($filepath,0777);
                   1545:         }
                   1546:     }
                   1547: # Save the file
                   1548:     {
1.701     albertel 1549: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1550: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1551: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1552: 	    return '/adm/notfound.html';
                   1553: 	}
                   1554: 	if (!print FH ($env{'form.'.$formname})) {
                   1555: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1556: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1557: 	    return '/adm/notfound.html';
                   1558: 	}
1.570     albertel 1559: 	close(FH);
1.258     www      1560:     }
1.637     raeburn  1561:     if ($parser eq 'parse') {
1.638     albertel 1562:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1563: 						   $codebase);
1.637     raeburn  1564:         unless ($parse_result eq 'ok') {
1.638     albertel 1565:             &logthis('Failed to parse '.$filepath.$file.
                   1566: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1567:         }
                   1568:     }
1.259     www      1569: # Notify homeserver to grep it
                   1570: #
1.638     albertel 1571:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1572:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1573:     if ($fetchresult eq 'ok') {
1.259     www      1574: #
1.258     www      1575: # Return the URL to it
1.494     albertel 1576:         return '/uploaded/'.$path.$file;
1.263     www      1577:     } else {
1.494     albertel 1578:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1579: 		 ': '.$fetchresult);
1.263     www      1580:         return '/adm/notfound.html';
                   1581:     }    
1.493     albertel 1582: }
                   1583: 
1.637     raeburn  1584: sub extract_embedded_items {
1.648     raeburn  1585:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1586:     my @state = ();
                   1587:     my %javafiles = (
                   1588:                       codebase => '',
                   1589:                       code => '',
                   1590:                       archive => ''
                   1591:                     );
                   1592:     my %mediafiles = (
                   1593:                       src => '',
                   1594:                       movie => '',
                   1595:                      );
1.648     raeburn  1596:     my $p;
                   1597:     if ($content) {
                   1598:         $p = HTML::LCParser->new($content);
                   1599:     } else {
                   1600:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1601:     }
1.641     albertel 1602:     while (my $t=$p->get_token()) {
1.640     albertel 1603: 	if ($t->[0] eq 'S') {
                   1604: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1605: 	    push (@state, $tagname);
1.648     raeburn  1606:             if (lc($tagname) eq 'allow') {
                   1607:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1608:             }
1.640     albertel 1609: 	    if (lc($tagname) eq 'img') {
                   1610: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1611: 	    }
1.645     raeburn  1612:             if (lc($tagname) eq 'script') {
                   1613:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1614:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1615:                 } else {
                   1616:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1617:                 }
                   1618:             }
                   1619:             if (lc($tagname) eq 'link') {
                   1620:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1621:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1622:                 }
                   1623:             }
1.640     albertel 1624: 	    if (lc($tagname) eq 'object' ||
                   1625: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1626: 		foreach my $item (keys(%javafiles)) {
                   1627: 		    $javafiles{$item} = '';
                   1628: 		}
                   1629: 	    }
                   1630: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1631: 		my $name = lc($attr->{'name'});
                   1632: 		foreach my $item (keys(%javafiles)) {
                   1633: 		    if ($name eq $item) {
                   1634: 			$javafiles{$item} = $attr->{'value'};
                   1635: 			last;
                   1636: 		    }
                   1637: 		}
                   1638: 		foreach my $item (keys(%mediafiles)) {
                   1639: 		    if ($name eq $item) {
                   1640: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1641: 			last;
                   1642: 		    }
                   1643: 		}
                   1644: 	    }
                   1645: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1646: 		foreach my $item (keys(%javafiles)) {
                   1647: 		    if ($attr->{$item}) {
                   1648: 			$javafiles{$item} = $attr->{$item};
                   1649: 			last;
                   1650: 		    }
                   1651: 		}
                   1652: 		foreach my $item (keys(%mediafiles)) {
                   1653: 		    if ($attr->{$item}) {
                   1654: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1655: 			last;
                   1656: 		    }
                   1657: 		}
                   1658: 	    }
                   1659: 	} elsif ($t->[0] eq 'E') {
                   1660: 	    my ($tagname) = ($t->[1]);
                   1661: 	    if ($javafiles{'codebase'} ne '') {
                   1662: 		$javafiles{'codebase'} .= '/';
                   1663: 	    }  
                   1664: 	    if (lc($tagname) eq 'applet' ||
                   1665: 		lc($tagname) eq 'object' ||
                   1666: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1667: 		) {
                   1668: 		foreach my $item (keys(%javafiles)) {
                   1669: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1670: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1671: 			&add_filetype($allfiles,$file,$item);
                   1672: 		    }
                   1673: 		}
                   1674: 	    } 
                   1675: 	    pop @state;
                   1676: 	}
                   1677:     }
1.637     raeburn  1678:     return 'ok';
                   1679: }
                   1680: 
1.639     albertel 1681: sub add_filetype {
                   1682:     my ($allfiles,$file,$type)=@_;
                   1683:     if (exists($allfiles->{$file})) {
                   1684: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1685: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1686: 	}
                   1687:     } else {
                   1688: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1689:     }
                   1690: }
                   1691: 
1.493     albertel 1692: sub removeuploadedurl {
                   1693:     my ($url)=@_;
                   1694:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1695:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1696: }
                   1697: 
                   1698: sub removeuserfile {
                   1699:     my ($docuname,$docudom,$fname)=@_;
                   1700:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1701:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1702:     if ($result eq 'ok') {
                   1703:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1704:             my $metafile = $fname.'.meta';
                   1705:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
                   1706:         }
                   1707:     }
                   1708:     return $result;
1.257     www      1709: }
1.15      www      1710: 
1.530     albertel 1711: sub mkdiruserfile {
                   1712:     my ($docuname,$docudom,$dir)=@_;
                   1713:     my $home=&homeserver($docuname,$docudom);
                   1714:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1715: }
                   1716: 
1.531     albertel 1717: sub renameuserfile {
                   1718:     my ($docuname,$docudom,$old,$new)=@_;
                   1719:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1720:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1721:                         &escape("$old").':'.&escape("$new"),$home);
                   1722:     if ($result eq 'ok') {
                   1723:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1724:             my $oldmeta = $old.'.meta';
                   1725:             my $newmeta = $new.'.meta';
                   1726:             my $metaresult = 
                   1727:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
                   1728:         }
                   1729:     }
                   1730:     return $result;
1.531     albertel 1731: }
                   1732: 
1.14      www      1733: # ------------------------------------------------------------------------- Log
                   1734: 
                   1735: sub log {
                   1736:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1737:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1738: }
                   1739: 
                   1740: # ------------------------------------------------------------------ Course Log
1.352     www      1741: #
                   1742: # This routine flushes several buffers of non-mission-critical nature
                   1743: #
1.157     www      1744: 
                   1745: sub flushcourselogs {
1.352     www      1746:     &logthis('Flushing log buffers');
                   1747: #
                   1748: # course logs
                   1749: # This is a log of all transactions in a course, which can be used
                   1750: # for data mining purposes
                   1751: #
                   1752: # It also collects the courseid database, which lists last transaction
                   1753: # times and course titles for all courseids
                   1754: #
                   1755:     my %courseidbuffer=();
1.800     albertel 1756:     foreach my $crsid (keys %courselogs) {
1.352     www      1757:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1758: 		          &escape($courselogs{$crsid}),
                   1759: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1760: 	    delete $courselogs{$crsid};
                   1761:         } else {
                   1762:             &logthis('Failed to flush log buffer for '.$crsid);
                   1763:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1764:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1765:                         " exceeded maximum size, deleting.</font>");
                   1766:                delete $courselogs{$crsid};
                   1767:             }
1.352     www      1768:         }
                   1769:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1770:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1771: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1772:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1773:         } else {
                   1774:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1775: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1776:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1777:         }
1.191     harris41 1778:     }
1.352     www      1779: #
                   1780: # Write course id database (reverse lookup) to homeserver of courses 
                   1781: # Is used in pickcourse
                   1782: #
1.800     albertel 1783:     foreach my $crsid (keys(%courseidbuffer)) {
                   1784:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1785:     }
                   1786: #
                   1787: # File accesses
                   1788: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1789: #
1.449     matthew  1790:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1791:         if ($entry =~ /___count$/) {
                   1792:             my ($dom,$name);
1.807     albertel 1793:             ($dom,$name,undef)=
1.811     albertel 1794: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1795:             if (! defined($dom) || $dom eq '' || 
                   1796:                 ! defined($name) || $name eq '') {
1.620     albertel 1797:                 my $cid = $env{'request.course.id'};
                   1798:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1799:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1800:             }
1.450     matthew  1801:             my $value = $accesshash{$entry};
                   1802:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1803:             my %temphash=($url => $value);
1.449     matthew  1804:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1805:             if ($result eq 'ok') {
                   1806:                 delete $accesshash{$entry};
                   1807:             } elsif ($result eq 'unknown_cmd') {
                   1808:                 # Target server has old code running on it.
1.450     matthew  1809:                 my %temphash=($entry => $value);
1.449     matthew  1810:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1811:                     delete $accesshash{$entry};
                   1812:                 }
                   1813:             }
                   1814:         } else {
1.811     albertel 1815:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1816:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1817:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1818:                 delete $accesshash{$entry};
                   1819:             }
1.185     www      1820:         }
1.191     harris41 1821:     }
1.352     www      1822: #
                   1823: # Roles
                   1824: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1825: #
1.800     albertel 1826:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1827:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1828: 	    split(/\:/,$entry);
                   1829:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1830:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1831:                 $rudom,$runame) eq 'ok') {
                   1832: 	    delete $userrolehash{$entry};
                   1833:         }
                   1834:     }
1.662     raeburn  1835: #
                   1836: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1837: #
                   1838:     my %domrolebuffer = ();
                   1839:     foreach my $entry (keys %domainrolehash) {
                   1840:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1841:         if ($domrolebuffer{$rudom}) {
                   1842:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1843:                       '='.&escape($domainrolehash{$entry});
                   1844:         } else {
                   1845:             $domrolebuffer{$rudom}.=&escape($entry).
                   1846:                       '='.&escape($domainrolehash{$entry});
                   1847:         }
                   1848:         delete $domainrolehash{$entry};
                   1849:     }
                   1850:     foreach my $dom (keys(%domrolebuffer)) {
                   1851:         foreach my $tryserver (keys %libserv) {
                   1852:             if ($hostdom{$tryserver} eq $dom) {
                   1853:                 unless (&reply('domroleput:'.$dom.':'.
                   1854:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1855:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1856:                 }
                   1857:             }
                   1858:         }
                   1859:     }
1.186     www      1860:     $dumpcount++;
1.157     www      1861: }
                   1862: 
                   1863: sub courselog {
                   1864:     my $what=shift;
1.158     www      1865:     $what=time.':'.$what;
1.620     albertel 1866:     unless ($env{'request.course.id'}) { return ''; }
                   1867:     $coursedombuf{$env{'request.course.id'}}=
                   1868:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1869:     $coursenumbuf{$env{'request.course.id'}}=
                   1870:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1871:     $coursehombuf{$env{'request.course.id'}}=
                   1872:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1873:     $coursedescrbuf{$env{'request.course.id'}}=
                   1874:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1875:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1876:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1877:     $courseownerbuf{$env{'request.course.id'}}=
                   1878:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1879:     $coursetypebuf{$env{'request.course.id'}}=
                   1880:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1881:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1882: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1883:     } else {
1.620     albertel 1884: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1885:     }
1.620     albertel 1886:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1887: 	&flushcourselogs();
                   1888:     }
1.158     www      1889: }
                   1890: 
                   1891: sub courseacclog {
                   1892:     my $fnsymb=shift;
1.620     albertel 1893:     unless ($env{'request.course.id'}) { return ''; }
                   1894:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1895:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1896:         $what.=':POST';
1.583     matthew  1897:         # FIXME: Probably ought to escape things....
1.800     albertel 1898: 	foreach my $key (keys(%env)) {
                   1899:             if ($key=~/^form\.(.*)/) {
                   1900: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1901:             }
1.191     harris41 1902:         }
1.583     matthew  1903:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1904:         # FIXME: We should not be depending on a form parameter that someone
                   1905:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1906:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1907:             $what.= ':POST';
                   1908:             # FIXME: Probably ought to escape things....
                   1909:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1910:                                  'crsdiscuss') {
1.620     albertel 1911:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1912:             }
                   1913:         }
1.158     www      1914:     }
                   1915:     &courselog($what);
1.149     www      1916: }
                   1917: 
1.185     www      1918: sub countacc {
                   1919:     my $url=&declutter(shift);
1.458     matthew  1920:     return if (! defined($url) || $url eq '');
1.620     albertel 1921:     unless ($env{'request.course.id'}) { return ''; }
                   1922:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1923:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1924:     $accesshash{$key}++;
1.185     www      1925: }
1.349     www      1926: 
1.361     www      1927: sub linklog {
                   1928:     my ($from,$to)=@_;
                   1929:     $from=&declutter($from);
                   1930:     $to=&declutter($to);
                   1931:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1932:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1933: }
                   1934:   
1.349     www      1935: sub userrolelog {
                   1936:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1937:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1938:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1939:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1940:         ($trole=~/^ta/)) {
1.350     www      1941:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1942:        $userrolehash
                   1943:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1944:                     =$tend.':'.$tstart;
1.662     raeburn  1945:     }
                   1946:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1947:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1948:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1949:         ($trole=~/^sc/)) {
                   1950:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1951:        $domainrolehash
                   1952:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1953:                     = $tend.':'.$tstart;
                   1954:     }
1.351     www      1955: }
                   1956: 
                   1957: sub get_course_adv_roles {
                   1958:     my $cid=shift;
1.620     albertel 1959:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1960:     my %coursehash=&coursedescription($cid);
1.470     www      1961:     my %nothide=();
1.800     albertel 1962:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1963: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      1964:     }
1.351     www      1965:     my %returnhash=();
                   1966:     my %dumphash=
                   1967:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1968:     my $now=time;
1.800     albertel 1969:     foreach my $entry (keys %dumphash) {
                   1970: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      1971:         if (($tstart) && ($tstart<0)) { next; }
                   1972:         if (($tend) && ($tend<$now)) { next; }
                   1973:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1974:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 1975: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1976: 	if ((&privileged($username,$domain)) && 
                   1977: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1978: 	if ($role eq 'cr') { next; }
1.351     www      1979:         my $key=&plaintext($role);
                   1980:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1981:         if ($returnhash{$key}) {
                   1982: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1983:         } else {
                   1984:             $returnhash{$key}=$username.':'.$domain;
                   1985:         }
1.400     www      1986:      }
                   1987:     return %returnhash;
                   1988: }
                   1989: 
                   1990: sub get_my_roles {
                   1991:     my ($uname,$udom)=@_;
1.620     albertel 1992:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1993:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1994:     my %dumphash=
                   1995:             &dump('nohist_userroles',$udom,$uname);
                   1996:     my %returnhash=();
                   1997:     my $now=time;
1.800     albertel 1998:     foreach my $entry (keys(%dumphash)) {
                   1999: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2000:         if (($tstart) && ($tstart<0)) { next; }
                   2001:         if (($tend) && ($tend<$now)) { next; }
                   2002:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2003:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2004: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2005:      }
                   2006:     return %returnhash;
1.399     www      2007: }
                   2008: 
                   2009: # ----------------------------------------------------- Frontpage Announcements
                   2010: #
                   2011: #
                   2012: 
                   2013: sub postannounce {
                   2014:     my ($server,$text)=@_;
                   2015:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2016:     unless ($text=~/\w/) { $text=''; }
                   2017:     return &reply('setannounce:'.&escape($text),$server);
                   2018: }
                   2019: 
                   2020: sub getannounce {
1.448     albertel 2021: 
                   2022:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2023: 	my $announcement='';
1.800     albertel 2024: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2025: 	close($fh);
1.399     www      2026: 	if ($announcement=~/\w/) { 
                   2027: 	    return 
                   2028:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2029:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2030: 	} else {
                   2031: 	    return '';
                   2032: 	}
                   2033:     } else {
                   2034: 	return '';
                   2035:     }
1.351     www      2036: }
1.353     www      2037: 
                   2038: # ---------------------------------------------------------- Course ID routines
                   2039: # Deal with domain's nohist_courseid.db files
                   2040: #
                   2041: 
                   2042: sub courseidput {
                   2043:     my ($domain,$what,$coursehome)=@_;
                   2044:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2045: }
                   2046: 
                   2047: sub courseiddump {
1.791     raeburn  2048:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2049:     my %returnhash=();
1.355     www      2050:     unless ($domfilter) { $domfilter=''; }
1.353     www      2051:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2052:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2053: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2054: 	        foreach my $line (
1.506     raeburn  2055:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2056: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2057:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2058:                                $tryserver))) {
1.800     albertel 2059: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2060:                     if (($key) && ($value)) {
1.516     raeburn  2061: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2062:                     }
1.353     www      2063:                 }
                   2064:             }
                   2065:         }
                   2066:     }
                   2067:     return %returnhash;
                   2068: }
                   2069: 
1.658     raeburn  2070: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2071: 
                   2072: sub dcmailput {
1.685     raeburn  2073:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2074:     my $status = &Apache::lonnet::critical(
1.740     www      2075:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2076:        &escape($message),$server);
1.662     raeburn  2077:     return $status;
                   2078: }
                   2079: 
1.658     raeburn  2080: sub dcmaildump {
                   2081:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2082:     my %returnhash=();
                   2083:     if (exists($domain_primary{$dom})) {
                   2084:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2085:                                                          &escape($enddate).':';
                   2086: 	my @esc_senders=map { &escape($_)} @$senders;
                   2087: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2088: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2089:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2090:             if (($key) && ($value)) {
                   2091:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2092:             }
                   2093:         }
                   2094:     }
                   2095:     return %returnhash;
                   2096: }
1.662     raeburn  2097: # ---------------------------------------------------------- Domain roles
                   2098: 
                   2099: sub get_domain_roles {
                   2100:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2101:     if (undef($startdate) || $startdate eq '') {
                   2102:         $startdate = '.';
                   2103:     }
                   2104:     if (undef($enddate) || $enddate eq '') {
                   2105:         $enddate = '.';
                   2106:     }
                   2107:     my $rolelist = join(':',@{$roles});
                   2108:     my %personnel = ();
                   2109:     foreach my $tryserver (keys(%libserv)) {
                   2110:         if ($hostdom{$tryserver} eq $dom) {
                   2111:             %{$personnel{$tryserver}}=();
1.800     albertel 2112:             foreach my $line (
1.662     raeburn  2113:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2114:                    &escape($startdate).':'.&escape($enddate).':'.
                   2115:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2116:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2117:                 if (($key) && ($value)) {
                   2118:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2119:                 }
                   2120:             }
                   2121:         }
                   2122:     }
                   2123:     return %personnel;
                   2124: }
1.658     raeburn  2125: 
1.149     www      2126: # ----------------------------------------------------------- Check out an item
                   2127: 
1.504     albertel 2128: sub get_first_access {
                   2129:     my ($type,$argsymb)=@_;
1.790     albertel 2130:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2131:     if ($argsymb) { $symb=$argsymb; }
                   2132:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2133:     if ($type eq 'map') {
                   2134: 	$res=&symbread($map);
                   2135:     } else {
                   2136: 	$res=$symb;
                   2137:     }
                   2138:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2139:     return $times{"$courseid\0$res"};
1.504     albertel 2140: }
                   2141: 
                   2142: sub set_first_access {
                   2143:     my ($type)=@_;
1.790     albertel 2144:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2145:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2146:     if ($type eq 'map') {
                   2147: 	$res=&symbread($map);
                   2148:     } else {
                   2149: 	$res=$symb;
                   2150:     }
                   2151:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2152:     if (!$firstaccess) {
1.588     albertel 2153: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2154:     }
                   2155:     return 'already_set';
1.504     albertel 2156: }
                   2157: 
1.149     www      2158: sub checkout {
                   2159:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2160:     my $now=time;
                   2161:     my $lonhost=$perlvar{'lonHostID'};
                   2162:     my $infostr=&escape(
1.234     www      2163:                  'CHECKOUTTOKEN&'.
1.149     www      2164:                  $tuname.'&'.
                   2165:                  $tudom.'&'.
                   2166:                  $tcrsid.'&'.
                   2167:                  $symb.'&'.
                   2168: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2169:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2170:     if ($token=~/^error\:/) { 
1.672     albertel 2171:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2172:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2173:                  "</font>");
                   2174:         return ''; 
                   2175:     }
                   2176: 
1.149     www      2177:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2178:     $token=~tr/a-z/A-Z/;
                   2179: 
1.153     www      2180:     my %infohash=('resource.0.outtoken' => $token,
                   2181:                   'resource.0.checkouttime' => $now,
                   2182:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2183: 
                   2184:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2185:        return '';
1.151     www      2186:     } else {
1.672     albertel 2187:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2188:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2189:                  "</font>");
1.149     www      2190:     }    
                   2191: 
                   2192:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2193:                          &escape('Checkout '.$infostr.' - '.
                   2194:                                                  $token)) ne 'ok') {
                   2195: 	return '';
1.151     www      2196:     } else {
1.672     albertel 2197:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2198:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2199:                  "</font>");
1.149     www      2200:     }
1.151     www      2201:     return $token;
1.149     www      2202: }
                   2203: 
                   2204: # ------------------------------------------------------------ Check in an item
                   2205: 
                   2206: sub checkin {
                   2207:     my $token=shift;
1.150     www      2208:     my $now=time;
                   2209:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2210:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2211:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2212:     $dtoken=~s/\W/\_/g;
1.234     www      2213:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2214:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2215: 
1.154     www      2216:     unless (($tuname) && ($tudom)) {
                   2217:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2218:         return '';
                   2219:     }
                   2220:     
                   2221:     unless (&allowed('mgr',$tcrsid)) {
                   2222:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2223:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2224:         return '';
                   2225:     }
                   2226: 
1.153     www      2227:     my %infohash=('resource.0.intoken' => $token,
                   2228:                   'resource.0.checkintime' => $now,
                   2229:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2230: 
                   2231:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2232:        return '';
                   2233:     }    
                   2234: 
                   2235:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2236:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2237: 	return '';
                   2238:     }
                   2239: 
                   2240:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2241: }
                   2242: 
                   2243: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2244: 
                   2245: sub expirespread {
                   2246:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2247:     my $cid=$env{'request.course.id'}; 
1.110     www      2248:     if ($cid) {
                   2249:        my $now=time;
                   2250:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2251:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2252:                             $env{'course.'.$cid.'.num'}.
1.110     www      2253: 	        	    ':nohist_expirationdates:'.
                   2254:                             &escape($key).'='.$now,
1.620     albertel 2255:                             $env{'course.'.$cid.'.home'})
1.110     www      2256:     }
                   2257:     return 'ok';
1.14      www      2258: }
                   2259: 
1.109     www      2260: # ----------------------------------------------------- Devalidate Spreadsheets
                   2261: 
                   2262: sub devalidate {
1.325     www      2263:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2264:     my $cid=$env{'request.course.id'}; 
1.109     www      2265:     if ($cid) {
1.391     matthew  2266:         # delete the stored spreadsheets for
                   2267:         # - the student level sheet of this user in course's homespace
                   2268:         # - the assessment level sheet for this resource 
                   2269:         #   for this user in user's homespace
1.553     albertel 2270: 	# - current conditional state info
1.325     www      2271: 	my $key=$uname.':'.$udom.':';
1.109     www      2272:         my $status=
1.299     matthew  2273: 	    &del('nohist_calculatedsheets',
1.391     matthew  2274: 		 [$key.'studentcalc:'],
1.620     albertel 2275: 		 $env{'course.'.$cid.'.domain'},
                   2276: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2277: 		.' '.
                   2278: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2279: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2280:         unless ($status eq 'ok ok') {
                   2281:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2282:                     $uname.' at '.$udom.' for '.
1.109     www      2283: 		    $symb.': '.$status);
1.133     albertel 2284:         }
1.553     albertel 2285: 	&delenv('user.state.'.$cid);
1.109     www      2286:     }
                   2287: }
                   2288: 
1.265     albertel 2289: sub get_scalar {
                   2290:     my ($string,$end) = @_;
                   2291:     my $value;
                   2292:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2293: 	$value = $1;
                   2294:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2295: 	$value = $1;
                   2296:     }
                   2297:     return &unescape($value);
                   2298: }
                   2299: 
                   2300: sub array2str {
                   2301:   my (@array) = @_;
                   2302:   my $result=&arrayref2str(\@array);
                   2303:   $result=~s/^__ARRAY_REF__//;
                   2304:   $result=~s/__END_ARRAY_REF__$//;
                   2305:   return $result;
                   2306: }
                   2307: 
1.204     albertel 2308: sub arrayref2str {
                   2309:   my ($arrayref) = @_;
1.265     albertel 2310:   my $result='__ARRAY_REF__';
1.204     albertel 2311:   foreach my $elem (@$arrayref) {
1.265     albertel 2312:     if(ref($elem) eq 'ARRAY') {
                   2313:       $result.=&arrayref2str($elem).'&';
                   2314:     } elsif(ref($elem) eq 'HASH') {
                   2315:       $result.=&hashref2str($elem).'&';
                   2316:     } elsif(ref($elem)) {
                   2317:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2318:     } else {
                   2319:       $result.=&escape($elem).'&';
                   2320:     }
                   2321:   }
                   2322:   $result=~s/\&$//;
1.265     albertel 2323:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2324:   return $result;
                   2325: }
                   2326: 
1.168     albertel 2327: sub hash2str {
1.204     albertel 2328:   my (%hash) = @_;
                   2329:   my $result=&hashref2str(\%hash);
1.265     albertel 2330:   $result=~s/^__HASH_REF__//;
                   2331:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2332:   return $result;
                   2333: }
                   2334: 
                   2335: sub hashref2str {
                   2336:   my ($hashref)=@_;
1.265     albertel 2337:   my $result='__HASH_REF__';
1.800     albertel 2338:   foreach my $key (sort(keys(%$hashref))) {
                   2339:     if (ref($key) eq 'ARRAY') {
                   2340:       $result.=&arrayref2str($key).'=';
                   2341:     } elsif (ref($key) eq 'HASH') {
                   2342:       $result.=&hashref2str($key).'=';
                   2343:     } elsif (ref($key)) {
1.265     albertel 2344:       $result.='=';
1.800     albertel 2345:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2346:     } else {
1.800     albertel 2347: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2348:     }
                   2349: 
1.800     albertel 2350:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2351:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2352:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2353:       $result.=&hashref2str($hashref->{$key}).'&';
                   2354:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2355:        $result.='&';
1.800     albertel 2356:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2357:     } else {
1.800     albertel 2358:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2359:     }
                   2360:   }
1.168     albertel 2361:   $result=~s/\&$//;
1.265     albertel 2362:   $result .= '__END_HASH_REF__';
1.168     albertel 2363:   return $result;
                   2364: }
                   2365: 
                   2366: sub str2hash {
1.265     albertel 2367:     my ($string)=@_;
                   2368:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2369:     return %$hash;
                   2370: }
                   2371: 
                   2372: sub str2hashref {
1.168     albertel 2373:   my ($string) = @_;
1.265     albertel 2374: 
                   2375:   my %hash;
                   2376: 
                   2377:   if($string !~ /^__HASH_REF__/) {
                   2378:       if (! ($string eq '' || !defined($string))) {
                   2379: 	  $hash{'error'}='Not hash reference';
                   2380:       }
                   2381:       return (\%hash, $string);
                   2382:   }
                   2383: 
                   2384:   $string =~ s/^__HASH_REF__//;
                   2385: 
                   2386:   while($string !~ /^__END_HASH_REF__/) {
                   2387:       #key
                   2388:       my $key='';
                   2389:       if($string =~ /^__HASH_REF__/) {
                   2390:           ($key, $string)=&str2hashref($string);
                   2391:           if(defined($key->{'error'})) {
                   2392:               $hash{'error'}='Bad data';
                   2393:               return (\%hash, $string);
                   2394:           }
                   2395:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2396:           ($key, $string)=&str2arrayref($string);
                   2397:           if($key->[0] eq 'Array reference error') {
                   2398:               $hash{'error'}='Bad data';
                   2399:               return (\%hash, $string);
                   2400:           }
                   2401:       } else {
                   2402:           $string =~ s/^(.*?)=//;
1.267     albertel 2403: 	  $key=&unescape($1);
1.265     albertel 2404:       }
                   2405:       $string =~ s/^=//;
                   2406: 
                   2407:       #value
                   2408:       my $value='';
                   2409:       if($string =~ /^__HASH_REF__/) {
                   2410:           ($value, $string)=&str2hashref($string);
                   2411:           if(defined($value->{'error'})) {
                   2412:               $hash{'error'}='Bad data';
                   2413:               return (\%hash, $string);
                   2414:           }
                   2415:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2416:           ($value, $string)=&str2arrayref($string);
                   2417:           if($value->[0] eq 'Array reference error') {
                   2418:               $hash{'error'}='Bad data';
                   2419:               return (\%hash, $string);
                   2420:           }
                   2421:       } else {
                   2422: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2423:       }
                   2424:       $string =~ s/^&//;
                   2425: 
                   2426:       $hash{$key}=$value;
1.204     albertel 2427:   }
1.265     albertel 2428: 
                   2429:   $string =~ s/^__END_HASH_REF__//;
                   2430: 
                   2431:   return (\%hash, $string);
1.204     albertel 2432: }
                   2433: 
                   2434: sub str2array {
1.265     albertel 2435:     my ($string)=@_;
                   2436:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2437:     return @$array;
                   2438: }
                   2439: 
                   2440: sub str2arrayref {
1.204     albertel 2441:   my ($string) = @_;
1.265     albertel 2442:   my @array;
                   2443: 
                   2444:   if($string !~ /^__ARRAY_REF__/) {
                   2445:       if (! ($string eq '' || !defined($string))) {
                   2446: 	  $array[0]='Array reference error';
                   2447:       }
                   2448:       return (\@array, $string);
                   2449:   }
                   2450: 
                   2451:   $string =~ s/^__ARRAY_REF__//;
                   2452: 
                   2453:   while($string !~ /^__END_ARRAY_REF__/) {
                   2454:       my $value='';
                   2455:       if($string =~ /^__HASH_REF__/) {
                   2456:           ($value, $string)=&str2hashref($string);
                   2457:           if(defined($value->{'error'})) {
                   2458:               $array[0] ='Array reference error';
                   2459:               return (\@array, $string);
                   2460:           }
                   2461:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2462:           ($value, $string)=&str2arrayref($string);
                   2463:           if($value->[0] eq 'Array reference error') {
                   2464:               $array[0] ='Array reference error';
                   2465:               return (\@array, $string);
                   2466:           }
                   2467:       } else {
                   2468: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2469:       }
                   2470:       $string =~ s/^&//;
                   2471: 
                   2472:       push(@array, $value);
1.191     harris41 2473:   }
1.265     albertel 2474: 
                   2475:   $string =~ s/^__END_ARRAY_REF__//;
                   2476: 
                   2477:   return (\@array, $string);
1.168     albertel 2478: }
                   2479: 
1.167     albertel 2480: # -------------------------------------------------------------------Temp Store
                   2481: 
1.168     albertel 2482: sub tmpreset {
                   2483:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2484:   if (!$symb) {
                   2485:     $symb=&symbread();
1.620     albertel 2486:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2487:   }
                   2488:   $symb=escape($symb);
                   2489: 
1.620     albertel 2490:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2491:   $namespace=~s/\//\_/g;
                   2492:   $namespace=~s/\W//g;
                   2493: 
1.620     albertel 2494:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2495:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2496:   if ($domain eq 'public' && $stuname eq 'public') {
                   2497:       $stuname=$ENV{'REMOTE_ADDR'};
                   2498:   }
1.168     albertel 2499:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2500:   my %hash;
                   2501:   if (tie(%hash,'GDBM_File',
                   2502: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2503: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2504:     foreach my $key (keys %hash) {
1.180     albertel 2505:       if ($key=~ /:$symb/) {
1.168     albertel 2506: 	delete($hash{$key});
                   2507:       }
                   2508:     }
                   2509:   }
                   2510: }
                   2511: 
1.167     albertel 2512: sub tmpstore {
1.168     albertel 2513:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2514: 
                   2515:   if (!$symb) {
                   2516:     $symb=&symbread();
1.620     albertel 2517:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2518:   }
                   2519:   $symb=escape($symb);
                   2520: 
                   2521:   if (!$namespace) {
                   2522:     # I don't think we would ever want to store this for a course.
                   2523:     # it seems this will only be used if we don't have a course.
1.620     albertel 2524:     #$namespace=$env{'request.course.id'};
1.168     albertel 2525:     #if (!$namespace) {
1.620     albertel 2526:       $namespace=$env{'request.state'};
1.168     albertel 2527:     #}
                   2528:   }
                   2529:   $namespace=~s/\//\_/g;
                   2530:   $namespace=~s/\W//g;
1.620     albertel 2531:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2532:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2533:   if ($domain eq 'public' && $stuname eq 'public') {
                   2534:       $stuname=$ENV{'REMOTE_ADDR'};
                   2535:   }
1.168     albertel 2536:   my $now=time;
                   2537:   my %hash;
                   2538:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2539:   if (tie(%hash,'GDBM_File',
                   2540: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2541: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2542:     $hash{"version:$symb"}++;
                   2543:     my $version=$hash{"version:$symb"};
                   2544:     my $allkeys=''; 
                   2545:     foreach my $key (keys(%$storehash)) {
                   2546:       $allkeys.=$key.':';
1.591     albertel 2547:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2548:     }
                   2549:     $hash{"$version:$symb:timestamp"}=$now;
                   2550:     $allkeys.='timestamp';
                   2551:     $hash{"$version:keys:$symb"}=$allkeys;
                   2552:     if (untie(%hash)) {
                   2553:       return 'ok';
                   2554:     } else {
                   2555:       return "error:$!";
                   2556:     }
                   2557:   } else {
                   2558:     return "error:$!";
                   2559:   }
                   2560: }
1.167     albertel 2561: 
1.168     albertel 2562: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2563: 
1.168     albertel 2564: sub tmprestore {
                   2565:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2566: 
1.168     albertel 2567:   if (!$symb) {
                   2568:     $symb=&symbread();
1.620     albertel 2569:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2570:   }
                   2571:   $symb=escape($symb);
                   2572: 
1.620     albertel 2573:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2574: 
1.620     albertel 2575:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2576:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2577:   if ($domain eq 'public' && $stuname eq 'public') {
                   2578:       $stuname=$ENV{'REMOTE_ADDR'};
                   2579:   }
1.168     albertel 2580:   my %returnhash;
                   2581:   $namespace=~s/\//\_/g;
                   2582:   $namespace=~s/\W//g;
                   2583:   my %hash;
                   2584:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2585:   if (tie(%hash,'GDBM_File',
                   2586: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2587: 	  &GDBM_READER(),0640)) {
1.168     albertel 2588:     my $version=$hash{"version:$symb"};
                   2589:     $returnhash{'version'}=$version;
                   2590:     my $scope;
                   2591:     for ($scope=1;$scope<=$version;$scope++) {
                   2592:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2593:       my @keys=split(/:/,$vkeys);
                   2594:       my $key;
                   2595:       $returnhash{"$scope:keys"}=$vkeys;
                   2596:       foreach $key (@keys) {
1.591     albertel 2597: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2598: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2599:       }
                   2600:     }
1.168     albertel 2601:     if (!(untie(%hash))) {
                   2602:       return "error:$!";
                   2603:     }
                   2604:   } else {
                   2605:     return "error:$!";
                   2606:   }
                   2607:   return %returnhash;
1.167     albertel 2608: }
                   2609: 
1.9       www      2610: # ----------------------------------------------------------------------- Store
                   2611: 
                   2612: sub store {
1.124     www      2613:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2614:     my $home='';
                   2615: 
1.168     albertel 2616:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2617: 
1.213     www      2618:     $symb=&symbclean($symb);
1.122     albertel 2619:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2620: 
1.620     albertel 2621:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2622:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2623: 
                   2624:     &devalidate($symb,$stuname,$domain);
1.109     www      2625: 
                   2626:     $symb=escape($symb);
1.187     www      2627:     if (!$namespace) { 
1.620     albertel 2628:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2629:           return ''; 
                   2630:        } 
                   2631:     }
1.620     albertel 2632:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2633: 
                   2634:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2635:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2636: 
1.12      www      2637:     my $namevalue='';
1.800     albertel 2638:     foreach my $key (keys(%$storehash)) {
                   2639:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2640:     }
1.12      www      2641:     $namevalue=~s/\&$//;
1.187     www      2642:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2643:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2644: }
                   2645: 
1.47      www      2646: # -------------------------------------------------------------- Critical Store
                   2647: 
                   2648: sub cstore {
1.124     www      2649:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2650:     my $home='';
                   2651: 
1.168     albertel 2652:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2653: 
1.213     www      2654:     $symb=&symbclean($symb);
1.122     albertel 2655:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2656: 
1.620     albertel 2657:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2658:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2659: 
                   2660:     &devalidate($symb,$stuname,$domain);
1.109     www      2661: 
                   2662:     $symb=escape($symb);
1.187     www      2663:     if (!$namespace) { 
1.620     albertel 2664:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2665:           return ''; 
                   2666:        } 
                   2667:     }
1.620     albertel 2668:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2669: 
                   2670:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2671:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2672: 
1.47      www      2673:     my $namevalue='';
1.800     albertel 2674:     foreach my $key (keys(%$storehash)) {
                   2675:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2676:     }
1.47      www      2677:     $namevalue=~s/\&$//;
1.187     www      2678:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2679:     return critical
                   2680:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2681: }
                   2682: 
1.9       www      2683: # --------------------------------------------------------------------- Restore
                   2684: 
                   2685: sub restore {
1.124     www      2686:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2687:     my $home='';
                   2688: 
1.168     albertel 2689:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2690: 
1.122     albertel 2691:     if (!$symb) {
                   2692:       unless ($symb=escape(&symbread())) { return ''; }
                   2693:     } else {
1.213     www      2694:       $symb=&escape(&symbclean($symb));
1.122     albertel 2695:     }
1.188     www      2696:     if (!$namespace) { 
1.620     albertel 2697:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2698:           return ''; 
                   2699:        } 
                   2700:     }
1.620     albertel 2701:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2702:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2703:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2704:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2705: 
1.12      www      2706:     my %returnhash=();
1.800     albertel 2707:     foreach my $line (split(/\&/,$answer)) {
                   2708: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2709:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2710:     }
1.75      www      2711:     my $version;
                   2712:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2713:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2714:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2715:        }
1.75      www      2716:     }
1.13      www      2717:     return %returnhash;
1.34      www      2718: }
                   2719: 
                   2720: # ---------------------------------------------------------- Course Description
                   2721: 
                   2722: sub coursedescription {
1.731     albertel 2723:     my ($courseid,$args)=@_;
1.34      www      2724:     $courseid=~s/^\///;
1.49      www      2725:     $courseid=~s/\_/\//g;
1.34      www      2726:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2727:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2728:     my $normalid=$cdomain.'_'.$cnum;
                   2729:     # need to always cache even if we get errors otherwise we keep 
                   2730:     # trying and trying and trying to get the course description.
                   2731:     my %envhash=();
                   2732:     my %returnhash=();
1.731     albertel 2733:     
                   2734:     my $expiretime=600;
                   2735:     if ($env{'request.course.id'} eq $normalid) {
                   2736: 	$expiretime=120;
                   2737:     }
                   2738: 
                   2739:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2740:     if (!$args->{'freshen_cache'}
                   2741: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2742: 	foreach my $key (keys(%env)) {
                   2743: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2744: 	    my ($setting) = $1;
                   2745: 	    $returnhash{$setting} = $env{$key};
                   2746: 	}
                   2747: 	return %returnhash;
                   2748:     }
                   2749: 
                   2750:     # get the data agin
                   2751:     if (!$args->{'one_time'}) {
                   2752: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2753:     }
1.811     albertel 2754: 
1.34      www      2755:     if ($chome ne 'no_host') {
1.302     albertel 2756:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2757:        if (!exists($returnhash{'con_lost'})) {
                   2758:            $returnhash{'home'}= $chome;
                   2759: 	   $returnhash{'domain'} = $cdomain;
                   2760: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2761:            if (!defined($returnhash{'type'})) {
                   2762:                $returnhash{'type'} = 'Course';
                   2763:            }
1.130     albertel 2764:            while (my ($name,$value) = each %returnhash) {
1.53      www      2765:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2766:            }
1.270     www      2767:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2768:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2769: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2770:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2771:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2772:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2773:        }
                   2774:     }
1.731     albertel 2775:     if (!$args->{'one_time'}) {
                   2776: 	&appenv(%envhash);
                   2777:     }
1.302     albertel 2778:     return %returnhash;
1.461     www      2779: }
                   2780: 
                   2781: # -------------------------------------------------See if a user is privileged
                   2782: 
                   2783: sub privileged {
                   2784:     my ($username,$domain)=@_;
                   2785:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2786: 			&homeserver($username,$domain));
                   2787:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2788:     my $now=time;
                   2789:     if ($rolesdump ne '') {
1.800     albertel 2790:         foreach my $entry (split(/&/,$rolesdump)) {
                   2791: 	    if ($entry!~/^rolesdef_/) {
                   2792: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2793: 		$area=~s/\_\w\w$//;
                   2794: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2795: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2796: 		    my $active=1;
                   2797: 		    if ($tend) {
                   2798: 			if ($tend<$now) { $active=0; }
                   2799: 		    }
                   2800: 		    if ($tstart) {
                   2801: 			if ($tstart>$now) { $active=0; }
                   2802: 		    }
                   2803: 		    if ($active) { return 1; }
                   2804: 		}
                   2805: 	    }
                   2806: 	}
                   2807:     }
                   2808:     return 0;
1.9       www      2809: }
1.1       albertel 2810: 
1.103     harris41 2811: # -------------------------------------------------------- Get user privileges
1.11      www      2812: 
                   2813: sub rolesinit {
                   2814:     my ($domain,$username,$authhost)=@_;
                   2815:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2816:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2817:     my %allroles=();
1.678     raeburn  2818:     my %allgroups=();   
1.11      www      2819:     my $now=time;
1.743     albertel 2820:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2821:     my $group_privs;
1.11      www      2822: 
                   2823:     if ($rolesdump ne '') {
1.800     albertel 2824:         foreach my $entry (split(/&/,$rolesdump)) {
                   2825: 	  if ($entry!~/^rolesdef_/) {
                   2826:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2827: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2828:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2829: 	    if ($role=~/^cr/) { 
1.807     albertel 2830: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2831: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2832: 		    ($tend,$tstart)=split('_',$trest);
                   2833: 		} else {
                   2834: 		    $trole=$role;
                   2835: 		}
1.678     raeburn  2836:             } elsif ($role =~ m|^gr/|) {
                   2837:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2838:                 ($trole,$group_privs) = split(/\//,$trole);
                   2839:                 $group_privs = &unescape($group_privs);
1.587     albertel 2840: 	    } else {
                   2841: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2842: 	    }
1.743     albertel 2843: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2844: 					 $username);
                   2845: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2846:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2847:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2848:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2849: 		my $spec=$trole.'.'.$area;
                   2850: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2851: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2852:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2853:                 } elsif ($trole eq 'gr') {
                   2854:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2855: 		} else {
1.567     raeburn  2856:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2857: 		}
1.12      www      2858:             }
1.662     raeburn  2859:           }
1.191     harris41 2860:         }
1.743     albertel 2861:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2862:         $userroles{'user.adv'}    = $adv;
                   2863: 	$userroles{'user.author'} = $author;
1.620     albertel 2864:         $env{'user.adv'}=$adv;
1.11      www      2865:     }
1.743     albertel 2866:     return \%userroles;  
1.11      www      2867: }
                   2868: 
1.567     raeburn  2869: sub set_arearole {
                   2870:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2871: # log the associated role with the area
                   2872:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2873:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2874: }
                   2875: 
                   2876: sub custom_roleprivs {
                   2877:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2878:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2879:     my $homsvr=homeserver($rauthor,$rdomain);
                   2880:     if ($hostname{$homsvr} ne '') {
                   2881:         my ($rdummy,$roledef)=
                   2882:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2883:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2884:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2885:             if (defined($syspriv)) {
                   2886:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2887:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2888:             }
                   2889:             if ($tdomain ne '') {
                   2890:                 if (defined($dompriv)) {
                   2891:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2892:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2893:                 }
                   2894:                 if (($trest ne '') && (defined($coursepriv))) {
                   2895:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2896:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2897:                 }
                   2898:             }
                   2899:         }
                   2900:     }
                   2901: }
                   2902: 
1.678     raeburn  2903: sub group_roleprivs {
                   2904:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2905:     my $access = 1;
                   2906:     my $now = time;
                   2907:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2908:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2909:     if ($access) {
1.811     albertel 2910:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2911:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2912:     }
                   2913: }
1.567     raeburn  2914: 
                   2915: sub standard_roleprivs {
                   2916:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2917:     if (defined($pr{$trole.':s'})) {
                   2918:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2919:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2920:     }
                   2921:     if ($tdomain ne '') {
                   2922:         if (defined($pr{$trole.':d'})) {
                   2923:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2924:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2925:         }
                   2926:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2927:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2928:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2929:         }
                   2930:     }
                   2931: }
                   2932: 
                   2933: sub set_userprivs {
1.678     raeburn  2934:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2935:     my $author=0;
                   2936:     my $adv=0;
1.678     raeburn  2937:     my %grouproles = ();
                   2938:     if (keys(%{$allgroups}) > 0) {
                   2939:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2940:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2941:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2942:                 $trole = $1;
                   2943:                 $area = $2;
1.681     raeburn  2944:                 $sec = $3;
                   2945:                 $extendedarea = $area.$sec;
                   2946:                 if (exists($$allgroups{$area})) {
                   2947:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2948:                         my $spec = $trole.'.'.$extendedarea;
                   2949:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2950:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2951:                     }
                   2952:                 }
                   2953:             }
                   2954:         }
                   2955:     }
1.800     albertel 2956:     foreach my $group (keys(%grouproles)) {
                   2957:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2958:     }
1.800     albertel 2959:     foreach my $role (keys(%{$allroles})) {
                   2960:         my %thesepriv;
                   2961:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   2962:         foreach my $item (split(/:/,$$allroles{$role})) {
                   2963:             if ($item ne '') {
                   2964:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  2965:                 if ($restrictions eq '') {
                   2966:                     $thesepriv{$privilege}='F';
                   2967:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2968:                     $thesepriv{$privilege}.=$restrictions;
                   2969:                 }
                   2970:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2971:             }
                   2972:         }
                   2973:         my $thesestr='';
1.800     albertel 2974:         foreach my $priv (keys(%thesepriv)) {
                   2975: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   2976: 	}
                   2977:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  2978:     }
                   2979:     return ($author,$adv);
                   2980: }
                   2981: 
1.12      www      2982: # --------------------------------------------------------------- get interface
                   2983: 
                   2984: sub get {
1.131     albertel 2985:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2986:    my $items='';
1.800     albertel 2987:    foreach my $item (@$storearr) {
                   2988:        $items.=&escape($item).'&';
1.191     harris41 2989:    }
1.12      www      2990:    $items=~s/\&$//;
1.620     albertel 2991:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2992:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2993:    my $uhome=&homeserver($uname,$udomain);
                   2994: 
1.133     albertel 2995:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2996:    my @pairs=split(/\&/,$rep);
1.273     albertel 2997:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2998:      return @pairs;
                   2999:    }
1.15      www      3000:    my %returnhash=();
1.42      www      3001:    my $i=0;
1.800     albertel 3002:    foreach my $item (@$storearr) {
                   3003:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3004:       $i++;
1.191     harris41 3005:    }
1.15      www      3006:    return %returnhash;
1.27      www      3007: }
                   3008: 
                   3009: # --------------------------------------------------------------- del interface
                   3010: 
                   3011: sub del {
1.133     albertel 3012:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3013:    my $items='';
1.800     albertel 3014:    foreach my $item (@$storearr) {
                   3015:        $items.=&escape($item).'&';
1.191     harris41 3016:    }
1.27      www      3017:    $items=~s/\&$//;
1.620     albertel 3018:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3019:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3020:    my $uhome=&homeserver($uname,$udomain);
                   3021: 
                   3022:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3023: }
                   3024: 
                   3025: # -------------------------------------------------------------- dump interface
                   3026: 
                   3027: sub dump {
1.755     albertel 3028:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3029:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3030:     if (!$uname) { $uname=$env{'user.name'}; }
                   3031:     my $uhome=&homeserver($uname,$udomain);
                   3032:     if ($regexp) {
                   3033: 	$regexp=&escape($regexp);
                   3034:     } else {
                   3035: 	$regexp='.';
                   3036:     }
                   3037:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3038:     my @pairs=split(/\&/,$rep);
                   3039:     my %returnhash=();
                   3040:     foreach my $item (@pairs) {
                   3041: 	my ($key,$value)=split(/=/,$item,2);
                   3042: 	$key = &unescape($key);
                   3043: 	next if ($key =~ /^error: 2 /);
                   3044: 	$returnhash{$key}=&thaw_unescape($value);
                   3045:     }
                   3046:     return %returnhash;
1.407     www      3047: }
                   3048: 
1.717     albertel 3049: # --------------------------------------------------------- dumpstore interface
                   3050: 
                   3051: sub dumpstore {
                   3052:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3053:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   3054: }
                   3055: 
1.407     www      3056: # -------------------------------------------------------------- keys interface
                   3057: 
                   3058: sub getkeys {
                   3059:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3060:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3061:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3062:    my $uhome=&homeserver($uname,$udomain);
                   3063:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3064:    my @keyarray=();
1.800     albertel 3065:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3066:       next if ($key =~ /^error: 2 /);
1.800     albertel 3067:       push(@keyarray,&unescape($key));
1.407     www      3068:    }
                   3069:    return @keyarray;
1.318     matthew  3070: }
                   3071: 
1.319     matthew  3072: # --------------------------------------------------------------- currentdump
                   3073: sub currentdump {
1.328     matthew  3074:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3075:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3076:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3077:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3078:    my $uhome = &homeserver($sname,$sdom);
                   3079:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3080:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3081:    #
1.318     matthew  3082:    my %returnhash=();
1.319     matthew  3083:    #
                   3084:    if ($rep eq "unknown_cmd") { 
                   3085:        # an old lond will not know currentdump
                   3086:        # Do a dump and make it look like a currentdump
1.326     matthew  3087:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3088:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3089:        my %hash = @tmp;
                   3090:        @tmp=();
1.424     matthew  3091:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3092:    } else {
                   3093:        my @pairs=split(/\&/,$rep);
1.800     albertel 3094:        foreach my $pair (@pairs) {
                   3095:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3096:            my ($symb,$param) = split(/:/,$key);
                   3097:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3098:                                                         &thaw_unescape($value);
1.319     matthew  3099:        }
1.191     harris41 3100:    }
1.12      www      3101:    return %returnhash;
1.424     matthew  3102: }
                   3103: 
                   3104: sub convert_dump_to_currentdump{
                   3105:     my %hash = %{shift()};
                   3106:     my %returnhash;
                   3107:     # Code ripped from lond, essentially.  The only difference
                   3108:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3109:     # we might run in to problems with parameter names =~ /^v\./
                   3110:     while (my ($key,$value) = each(%hash)) {
                   3111:         my ($v,$symb,$param) = split(/:/,$key);
                   3112:         next if ($v eq 'version' || $symb eq 'keys');
                   3113:         next if (exists($returnhash{$symb}) &&
                   3114:                  exists($returnhash{$symb}->{$param}) &&
                   3115:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3116:         $returnhash{$symb}->{$param}=$value;
                   3117:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3118:     }
                   3119:     #
                   3120:     # Remove all of the keys in the hashes which keep track of
                   3121:     # the version of the parameter.
                   3122:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3123:         # use a foreach because we are going to delete from the hash.
                   3124:         foreach my $key (keys(%$param_hash)) {
                   3125:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3126:         }
                   3127:     }
                   3128:     return \%returnhash;
1.12      www      3129: }
                   3130: 
1.627     albertel 3131: # ------------------------------------------------------ critical inc interface
                   3132: 
                   3133: sub cinc {
                   3134:     return &inc(@_,'critical');
                   3135: }
                   3136: 
1.449     matthew  3137: # --------------------------------------------------------------- inc interface
                   3138: 
                   3139: sub inc {
1.627     albertel 3140:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3141:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3142:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3143:     my $uhome=&homeserver($uname,$udomain);
                   3144:     my $items='';
                   3145:     if (! ref($store)) {
                   3146:         # got a single value, so use that instead
                   3147:         $items = &escape($store).'=&';
                   3148:     } elsif (ref($store) eq 'SCALAR') {
                   3149:         $items = &escape($$store).'=&';        
                   3150:     } elsif (ref($store) eq 'ARRAY') {
                   3151:         $items = join('=&',map {&escape($_);} @{$store});
                   3152:     } elsif (ref($store) eq 'HASH') {
                   3153:         while (my($key,$value) = each(%{$store})) {
                   3154:             $items.= &escape($key).'='.&escape($value).'&';
                   3155:         }
                   3156:     }
                   3157:     $items=~s/\&$//;
1.627     albertel 3158:     if ($critical) {
                   3159: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3160:     } else {
                   3161: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3162:     }
1.449     matthew  3163: }
                   3164: 
1.12      www      3165: # --------------------------------------------------------------- put interface
                   3166: 
                   3167: sub put {
1.134     albertel 3168:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3169:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3170:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3171:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3172:    my $items='';
1.800     albertel 3173:    foreach my $item (keys(%$storehash)) {
                   3174:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3175:    }
1.12      www      3176:    $items=~s/\&$//;
1.134     albertel 3177:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3178: }
                   3179: 
1.631     albertel 3180: # ------------------------------------------------------------ newput interface
                   3181: 
                   3182: sub newput {
                   3183:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3184:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3185:    if (!$uname) { $uname=$env{'user.name'}; }
                   3186:    my $uhome=&homeserver($uname,$udomain);
                   3187:    my $items='';
                   3188:    foreach my $key (keys(%$storehash)) {
                   3189:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3190:    }
                   3191:    $items=~s/\&$//;
                   3192:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3193: }
                   3194: 
                   3195: # ---------------------------------------------------------  putstore interface
                   3196: 
1.524     raeburn  3197: sub putstore {
1.715     albertel 3198:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3199:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3200:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3201:    my $uhome=&homeserver($uname,$udomain);
                   3202:    my $items='';
1.715     albertel 3203:    foreach my $key (keys(%$storehash)) {
                   3204:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3205:    }
1.715     albertel 3206:    $items=~s/\&$//;
1.716     albertel 3207:    my $esc_symb=&escape($symb);
                   3208:    my $esc_v=&escape($version);
1.715     albertel 3209:    my $reply =
1.716     albertel 3210:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3211: 	      $uhome);
                   3212:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3213:        # gfall back to way things use to be done
1.715     albertel 3214:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3215: 			    $uname);
1.524     raeburn  3216:    }
1.715     albertel 3217:    return $reply;
                   3218: }
                   3219: 
                   3220: sub old_putstore {
1.716     albertel 3221:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3222:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3223:     if (!$uname) { $uname=$env{'user.name'}; }
                   3224:     my $uhome=&homeserver($uname,$udomain);
                   3225:     my %newstorehash;
1.800     albertel 3226:     foreach my $item (keys(%$storehash)) {
                   3227: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3228: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3229:     }
                   3230:     my $items='';
                   3231:     my %allitems = ();
1.800     albertel 3232:     foreach my $item (keys(%newstorehash)) {
                   3233: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3234: 	    my $key = $1.':keys:'.$2;
                   3235: 	    $allitems{$key} .= $3.':';
                   3236: 	}
1.800     albertel 3237: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3238:     }
1.800     albertel 3239:     foreach my $item (keys(%allitems)) {
                   3240: 	$allitems{$item} =~ s/\:$//;
                   3241: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3242:     }
                   3243:     $items=~s/\&$//;
                   3244:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3245: }
                   3246: 
1.47      www      3247: # ------------------------------------------------------ critical put interface
                   3248: 
                   3249: sub cput {
1.134     albertel 3250:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3251:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3252:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3253:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3254:    my $items='';
1.800     albertel 3255:    foreach my $item (keys(%$storehash)) {
                   3256:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3257:    }
1.47      www      3258:    $items=~s/\&$//;
1.134     albertel 3259:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3260: }
                   3261: 
                   3262: # -------------------------------------------------------------- eget interface
                   3263: 
                   3264: sub eget {
1.133     albertel 3265:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3266:    my $items='';
1.800     albertel 3267:    foreach my $item (@$storearr) {
                   3268:        $items.=&escape($item).'&';
1.191     harris41 3269:    }
1.12      www      3270:    $items=~s/\&$//;
1.620     albertel 3271:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3272:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3273:    my $uhome=&homeserver($uname,$udomain);
                   3274:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3275:    my @pairs=split(/\&/,$rep);
                   3276:    my %returnhash=();
1.42      www      3277:    my $i=0;
1.800     albertel 3278:    foreach my $item (@$storearr) {
                   3279:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3280:       $i++;
1.191     harris41 3281:    }
1.12      www      3282:    return %returnhash;
                   3283: }
                   3284: 
1.667     albertel 3285: # ------------------------------------------------------------ tmpput interface
                   3286: sub tmpput {
1.802     raeburn  3287:     my ($storehash,$server,$context)=@_;
1.667     albertel 3288:     my $items='';
1.800     albertel 3289:     foreach my $item (keys(%$storehash)) {
                   3290: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3291:     }
                   3292:     $items=~s/\&$//;
1.802     raeburn  3293:     if (defined($context)) {
                   3294:         $items .= ':'.&escape($context);
                   3295:     }
1.667     albertel 3296:     return &reply("tmpput:$items",$server);
                   3297: }
                   3298: 
                   3299: # ------------------------------------------------------------ tmpget interface
                   3300: sub tmpget {
1.688     albertel 3301:     my ($token,$server)=@_;
                   3302:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3303:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3304:     my %returnhash;
                   3305:     foreach my $item (split(/\&/,$rep)) {
                   3306: 	my ($key,$value)=split(/=/,$item);
                   3307: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3308:     }
                   3309:     return %returnhash;
                   3310: }
                   3311: 
1.688     albertel 3312: # ------------------------------------------------------------ tmpget interface
                   3313: sub tmpdel {
                   3314:     my ($token,$server)=@_;
                   3315:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3316:     return &reply("tmpdel:$token",$server);
                   3317: }
                   3318: 
1.765     albertel 3319: # -------------------------------------------------- portfolio access checking
                   3320: 
                   3321: sub portfolio_access {
1.766     albertel 3322:     my ($requrl) = @_;
1.765     albertel 3323:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3324:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3325:     if ($result) {
                   3326:         my %setters;
                   3327:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3328:             my ($startblock,$endblock) =
                   3329:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3330:             if ($startblock && $endblock) {
                   3331:                 return 'B';
                   3332:             }
                   3333:         } else {
                   3334:             my ($startblock,$endblock) =
                   3335:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3336:             if ($startblock && $endblock) {
                   3337:                 return 'B';
                   3338:             }
                   3339:         }
                   3340:     }
1.765     albertel 3341:     if ($result eq 'ok') {
1.766     albertel 3342:        return 'F';
1.765     albertel 3343:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3344:        return 'A';
1.765     albertel 3345:     }
1.766     albertel 3346:     return '';
1.765     albertel 3347: }
                   3348: 
                   3349: sub get_portfolio_access {
1.767     albertel 3350:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3351: 
                   3352:     if (!ref($access_hash)) {
                   3353: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3354: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3355: 						   $file_name);
                   3356: 	$access_hash = $access_controls{$file_name};
                   3357:     }
                   3358: 
1.765     albertel 3359:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3360:     my $now = time;
                   3361:     if (ref($access_hash) eq 'HASH') {
                   3362:         foreach my $key (keys(%{$access_hash})) {
                   3363:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3364:             if ($start > $now) {
                   3365:                 next;
                   3366:             }
                   3367:             if ($end && $end<$now) {
                   3368:                 next;
                   3369:             }
                   3370:             if ($scope eq 'public') {
                   3371:                 $public = $key;
                   3372:                 last;
                   3373:             } elsif ($scope eq 'guest') {
                   3374:                 $guest = $key;
                   3375:             } elsif ($scope eq 'domains') {
                   3376:                 push(@domains,$key);
                   3377:             } elsif ($scope eq 'users') {
                   3378:                 push(@users,$key);
                   3379:             } elsif ($scope eq 'course') {
                   3380:                 push(@courses,$key);
                   3381:             } elsif ($scope eq 'group') {
                   3382:                 push(@groups,$key);
                   3383:             }
                   3384:         }
                   3385:         if ($public) {
                   3386:             return 'ok';
                   3387:         }
                   3388:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3389:             if ($guest) {
                   3390:                 return $guest;
                   3391:             }
                   3392:         } else {
                   3393:             if (@domains > 0) {
                   3394:                 foreach my $domkey (@domains) {
                   3395:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3396:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3397:                             return 'ok';
                   3398:                         }
                   3399:                     }
                   3400:                 }
                   3401:             }
                   3402:             if (@users > 0) {
                   3403:                 foreach my $userkey (@users) {
                   3404:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3405:                         return 'ok';
                   3406:                     }
                   3407:                 }
                   3408:             }
                   3409:             my %roleshash;
                   3410:             my @courses_and_groups = @courses;
                   3411:             push(@courses_and_groups,@groups); 
                   3412:             if (@courses_and_groups > 0) {
                   3413:                 my (%allgroups,%allroles); 
                   3414:                 my ($start,$end,$role,$sec,$group);
                   3415:                 foreach my $envkey (%env) {
1.811     albertel 3416:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3417:                         my $cid = $2.'_'.$3; 
                   3418:                         if ($1 eq 'gr') {
                   3419:                             $group = $4;
                   3420:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3421:                         } else {
                   3422:                             if ($4 eq '') {
                   3423:                                 $sec = 'none';
                   3424:                             } else {
                   3425:                                 $sec = $4;
                   3426:                             }
                   3427:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3428:                         }
1.811     albertel 3429:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3430:                         my $cid = $2.'_'.$3;
                   3431:                         if ($4 eq '') {
                   3432:                             $sec = 'none';
                   3433:                         } else {
                   3434:                             $sec = $4;
                   3435:                         }
                   3436:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3437:                     }
                   3438:                 }
                   3439:                 if (keys(%allroles) == 0) {
                   3440:                     return;
                   3441:                 }
                   3442:                 foreach my $key (@courses_and_groups) {
                   3443:                     my %content = %{$$access_hash{$key}};
                   3444:                     my $cnum = $content{'number'};
                   3445:                     my $cdom = $content{'domain'};
                   3446:                     my $cid = $cdom.'_'.$cnum;
                   3447:                     if (!exists($allroles{$cid})) {
                   3448:                         next;
                   3449:                     }    
                   3450:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3451:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3452:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3453:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3454:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3455:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3456:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3457:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3458:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3459:                                         if (grep/^all$/,@sections) {
                   3460:                                             return 'ok';
                   3461:                                         } else {
                   3462:                                             if (grep/^$sec$/,@sections) {
                   3463:                                                 return 'ok';
                   3464:                                             }
                   3465:                                         }
                   3466:                                     }
                   3467:                                 }
                   3468:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3469:                                     if (grep/^none$/,@groups) {
                   3470:                                         return 'ok';
                   3471:                                     }
                   3472:                                 } else {
                   3473:                                     if (grep/^all$/,@groups) {
                   3474:                                         return 'ok';
                   3475:                                     } 
                   3476:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3477:                                         if (grep/^$group$/,@groups) {
                   3478:                                             return 'ok';
                   3479:                                         }
                   3480:                                     }
                   3481:                                 } 
                   3482:                             }
                   3483:                         }
                   3484:                     }
                   3485:                 }
                   3486:             }
                   3487:             if ($guest) {
                   3488:                 return $guest;
                   3489:             }
                   3490:         }
                   3491:     }
                   3492:     return;
                   3493: }
                   3494: 
                   3495: sub course_group_datechecker {
                   3496:     my ($dates,$now,$status) = @_;
                   3497:     my ($start,$end) = split(/\./,$dates);
                   3498:     if (!$start && !$end) {
                   3499:         return 'ok';
                   3500:     }
                   3501:     if (grep/^active$/,@{$status}) {
                   3502:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3503:             return 'ok';
                   3504:         }
                   3505:     }
                   3506:     if (grep/^previous$/,@{$status}) {
                   3507:         if ($end > $now ) {
                   3508:             return 'ok';
                   3509:         }
                   3510:     }
                   3511:     if (grep/^future$/,@{$status}) {
                   3512:         if ($start > $now) {
                   3513:             return 'ok';
                   3514:         }
                   3515:     }
                   3516:     return; 
                   3517: }
                   3518: 
                   3519: sub parse_portfolio_url {
                   3520:     my ($url) = @_;
                   3521: 
                   3522:     my ($type,$udom,$unum,$group,$file_name);
                   3523:     
1.807     albertel 3524:     if ($url =~  m-^/*uploaded/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3525: 	$type = 1;
                   3526:         $udom = $1;
                   3527:         $unum = $2;
                   3528:         $file_name = $3;
1.811     albertel 3529:     } elsif ($url =~ m-^/*uploaded/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3530: 	$type = 2;
                   3531:         $udom = $1;
                   3532:         $unum = $2;
                   3533:         $group = $3;
                   3534:         $file_name = $3.'/'.$4;
                   3535:     }
                   3536:     if (wantarray) {
                   3537: 	return ($type,$udom,$unum,$file_name,$group);
                   3538:     }
                   3539:     return $type;
                   3540: }
                   3541: 
                   3542: sub is_portfolio_url {
                   3543:     my ($url) = @_;
                   3544:     return scalar(&parse_portfolio_url($url));
                   3545: }
                   3546: 
1.798     raeburn  3547: sub is_portfolio_file {
                   3548:     my ($file) = @_;
1.811     albertel 3549:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w\/portfolio/)) {
1.798     raeburn  3550:         return 1;
                   3551:     }
                   3552:     return;
                   3553: }
                   3554: 
                   3555: 
1.341     www      3556: # ---------------------------------------------- Custom access rule evaluation
                   3557: 
                   3558: sub customaccess {
                   3559:     my ($priv,$uri)=@_;
1.807     albertel 3560:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.343     www      3561:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3562:     $udom = &LONCAPA::clean_domain($udom);
                   3563:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3564:     my $access=0;
1.800     albertel 3565:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3566: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3567:         if ($role) {
                   3568: 	   if ($role ne $urole) { next; }
                   3569:         }
1.800     albertel 3570:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3571:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3572:             if ($tdom) {
                   3573: 		if ($tdom ne $udom) { next; }
                   3574:             }
                   3575:             if ($tcrs) {
                   3576: 		if ($tcrs ne $ucrs) { next; }
                   3577:             }
                   3578:             if ($tsec) {
                   3579: 		if ($tsec ne $usec) { next; }
                   3580:             }
                   3581:             $access=($effect eq 'allow');
                   3582:             last;
1.342     www      3583:         }
1.402     bowersj2 3584: 	if ($realm eq '' && $role eq '') {
                   3585:             $access=($effect eq 'allow');
                   3586: 	}
1.341     www      3587:     }
                   3588:     return $access;
                   3589: }
                   3590: 
1.103     harris41 3591: # ------------------------------------------------- Check for a user privilege
1.12      www      3592: 
                   3593: sub allowed {
1.810     raeburn  3594:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3595:     my $ver_orguri=$uri;
1.439     www      3596:     $uri=&deversion($uri);
1.152     www      3597:     my $orguri=$uri;
1.52      www      3598:     $uri=&declutter($uri);
1.809     raeburn  3599: 
1.810     raeburn  3600:     if ($priv eq 'evb') {
                   3601: # Evade communication block restrictions for specified role in a course
                   3602:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3603:             return $1;
                   3604:         } else {
                   3605:             return;
                   3606:         }
                   3607:     }
                   3608: 
1.620     albertel 3609:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3610: # Free bre access to adm and meta resources
1.775     albertel 3611:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3612: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3613: 	&& ($priv eq 'bre')) {
1.14      www      3614: 	return 'F';
1.159     www      3615:     }
                   3616: 
1.545     banghart 3617: # Free bre access to user's own portfolio contents
1.714     raeburn  3618:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3619:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3620: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3621:         my %setters;
                   3622:         my ($startblock,$endblock) = 
                   3623:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3624:         if ($startblock && $endblock) {
                   3625:             return 'B';
                   3626:         } else {
                   3627:             return 'F';
                   3628:         }
1.545     banghart 3629:     }
                   3630: 
1.762     raeburn  3631: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3632:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3633:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3634:         if (exists($env{'request.course.id'})) {
                   3635:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3636:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3637:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3638:                 my $courseprivid=$env{'request.course.id'};
                   3639:                 $courseprivid=~s/\_/\//;
                   3640:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3641:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3642:                     return $1; 
1.762     raeburn  3643:                 } else {
                   3644:                     if ($env{'request.course.sec'}) {
                   3645:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3646:                     }
                   3647:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3648:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3649:                         return $2;
                   3650:                     }
1.714     raeburn  3651:                 }
                   3652:             }
                   3653:         }
                   3654:     }
                   3655: 
1.159     www      3656: # Free bre to public access
                   3657: 
                   3658:     if ($priv eq 'bre') {
1.238     www      3659:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3660: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3661:            return 'F'; 
                   3662:         }
1.238     www      3663:         if ($copyright eq 'priv') {
                   3664:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3665: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3666: 		return '';
                   3667:             }
                   3668:         }
                   3669:         if ($copyright eq 'domain') {
                   3670:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3671: 	    unless (($env{'user.domain'} eq $1) ||
                   3672:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3673: 		return '';
                   3674:             }
1.262     matthew  3675:         }
1.620     albertel 3676:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3677:             # Library role, so allow browsing of resources in this domain.
                   3678:             return 'F';
1.238     www      3679:         }
1.341     www      3680:         if ($copyright eq 'custom') {
                   3681: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3682:         }
1.14      www      3683:     }
1.264     matthew  3684:     # Domain coordinator is trying to create a course
1.620     albertel 3685:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3686:         # uri is the requested domain in this case.
                   3687:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3688:         # a role of dc for the domain in question.
1.620     albertel 3689:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3690:     }
1.29      www      3691: 
1.52      www      3692:     my $thisallowed='';
                   3693:     my $statecond=0;
                   3694:     my $courseprivid='';
                   3695: 
                   3696: # Course
                   3697: 
1.620     albertel 3698:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3699:        $thisallowed.=$1;
                   3700:     }
1.29      www      3701: 
1.52      www      3702: # Domain
                   3703: 
1.620     albertel 3704:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3705:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3706:        $thisallowed.=$1;
                   3707:     }
1.52      www      3708: 
                   3709: # Course: uri itself is a course
1.66      www      3710:     my $courseuri=$uri;
                   3711:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3712:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3713: 
1.620     albertel 3714:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3715:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3716:        $thisallowed.=$1;
                   3717:     }
1.29      www      3718: 
1.665     albertel 3719: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3720: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3721:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3722: 	$thisallowed='';
1.671     raeburn  3723:         my ($match)=&is_on_map($uri);
                   3724:         if ($match) {
                   3725:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3726:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3727:                 $thisallowed.=$1;
                   3728:             }
                   3729:         } else {
1.705     albertel 3730:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3731:             if ($refuri) {
                   3732:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3733:                     $thisallowed='F';
1.671     raeburn  3734:                 } else {
                   3735:                     $refuri=&declutter($refuri);
                   3736:                     my ($match) = &is_on_map($refuri);
                   3737:                     if ($match) {
                   3738:                         $thisallowed='F';
                   3739:                     }
1.669     raeburn  3740:                 }
1.671     raeburn  3741:             }
                   3742:         }
1.314     www      3743:     }
1.492     albertel 3744: 
1.766     albertel 3745:     if ($priv eq 'bre'
                   3746: 	&& $thisallowed ne 'F' 
                   3747: 	&& $thisallowed ne '2'
                   3748: 	&& &is_portfolio_url($uri)) {
                   3749: 	$thisallowed = &portfolio_access($uri);
                   3750:     }
                   3751:     
1.52      www      3752: # Full access at system, domain or course-wide level? Exit.
1.29      www      3753: 
                   3754:     if ($thisallowed=~/F/) {
                   3755: 	return 'F';
                   3756:     }
                   3757: 
1.52      www      3758: # If this is generating or modifying users, exit with special codes
1.29      www      3759: 
1.643     www      3760:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3761: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3762: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3763: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3764: 	    unless ($auname) { return $thisallowed; }
                   3765: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3766: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3767: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3768: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3769: 	}
1.52      www      3770: 	return $thisallowed;
                   3771:     }
                   3772: #
1.103     harris41 3773: # Gathered so far: system, domain and course wide privileges
1.52      www      3774: #
                   3775: # Course: See if uri or referer is an individual resource that is part of 
                   3776: # the course
                   3777: 
1.620     albertel 3778:     if ($env{'request.course.id'}) {
1.232     www      3779: 
1.620     albertel 3780:        $courseprivid=$env{'request.course.id'};
                   3781:        if ($env{'request.course.sec'}) {
                   3782:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3783:        }
                   3784:        $courseprivid=~s/\_/\//;
                   3785:        my $checkreferer=1;
1.232     www      3786:        my ($match,$cond)=&is_on_map($uri);
                   3787:        if ($match) {
                   3788:            $statecond=$cond;
1.620     albertel 3789:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3790:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3791:                $thisallowed.=$1;
                   3792:                $checkreferer=0;
                   3793:            }
1.29      www      3794:        }
1.83      www      3795:        
1.148     www      3796:        if ($checkreferer) {
1.620     albertel 3797: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3798:             unless ($refuri) {
1.800     albertel 3799:                 foreach my $key (keys(%env)) {
                   3800: 		    if ($key=~/^httpref\..*\*/) {
                   3801: 			my $pattern=$key;
1.156     www      3802:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3803:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3804:                         $pattern=~s/\//\\\//g;
1.152     www      3805:                         if ($orguri=~/$pattern/) {
1.800     albertel 3806: 			    $refuri=$env{$key};
1.148     www      3807:                         }
                   3808:                     }
1.191     harris41 3809:                 }
1.148     www      3810:             }
1.232     www      3811: 
1.148     www      3812:          if ($refuri) { 
1.152     www      3813: 	  $refuri=&declutter($refuri);
1.232     www      3814:           my ($match,$cond)=&is_on_map($refuri);
                   3815:             if ($match) {
                   3816:               my $refstatecond=$cond;
1.620     albertel 3817:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3818:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3819:                   $thisallowed.=$1;
1.53      www      3820:                   $uri=$refuri;
                   3821:                   $statecond=$refstatecond;
1.52      www      3822:               }
                   3823:           }
1.148     www      3824:         }
1.29      www      3825:        }
1.52      www      3826:    }
1.29      www      3827: 
1.52      www      3828: #
1.103     harris41 3829: # Gathered now: all privileges that could apply, and condition number
1.52      www      3830: # 
                   3831: #
                   3832: # Full or no access?
                   3833: #
1.29      www      3834: 
1.52      www      3835:     if ($thisallowed=~/F/) {
                   3836: 	return 'F';
                   3837:     }
1.29      www      3838: 
1.52      www      3839:     unless ($thisallowed) {
                   3840:         return '';
                   3841:     }
1.29      www      3842: 
1.52      www      3843: # Restrictions exist, deal with them
                   3844: #
                   3845: #   C:according to course preferences
                   3846: #   R:according to resource settings
                   3847: #   L:unless locked
                   3848: #   X:according to user session state
                   3849: #
                   3850: 
                   3851: # Possibly locked functionality, check all courses
1.54      www      3852: # Locks might take effect only after 10 minutes cache expiration for other
                   3853: # courses, and 2 minutes for current course
1.52      www      3854: 
                   3855:     my $envkey;
                   3856:     if ($thisallowed=~/L/) {
1.620     albertel 3857:         foreach $envkey (keys %env) {
1.54      www      3858:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3859:                my $courseid=$2;
                   3860:                my $roleid=$1.'.'.$2;
1.92      www      3861:                $courseid=~s/^\///;
1.54      www      3862:                my $expiretime=600;
1.620     albertel 3863:                if ($env{'request.role'} eq $roleid) {
1.54      www      3864: 		  $expiretime=120;
                   3865:                }
                   3866: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3867:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3868:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3869: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3870:                }
1.620     albertel 3871:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3872:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3873: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3874:                        &log($env{'user.domain'},$env{'user.name'},
                   3875:                             $env{'user.home'},
1.57      www      3876:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3877:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3878:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3879: 		       return '';
                   3880:                    }
                   3881:                }
1.620     albertel 3882:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3883:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3884: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3885:                        &log($env{'user.domain'},$env{'user.name'},
                   3886:                             $env{'user.home'},
1.57      www      3887:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3888:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3889:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3890: 		       return '';
                   3891:                    }
                   3892:                }
                   3893: 	   }
1.29      www      3894:        }
1.52      www      3895:     }
                   3896:    
                   3897: #
                   3898: # Rest of the restrictions depend on selected course
                   3899: #
                   3900: 
1.620     albertel 3901:     unless ($env{'request.course.id'}) {
1.766     albertel 3902: 	if ($thisallowed eq 'A') {
                   3903: 	    return 'A';
1.814     raeburn  3904:         } elsif ($thisallowed eq 'B') {
                   3905:             return 'B';
1.766     albertel 3906: 	} else {
                   3907: 	    return '1';
                   3908: 	}
1.52      www      3909:     }
1.29      www      3910: 
1.52      www      3911: #
                   3912: # Now user is definitely in a course
                   3913: #
1.53      www      3914: 
                   3915: 
                   3916: # Course preferences
                   3917: 
                   3918:    if ($thisallowed=~/C/) {
1.620     albertel 3919:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3920:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3921:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3922: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3923: 	   if ($priv ne 'pch') { 
                   3924: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3925: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3926: 			$env{'request.course.id'});
                   3927: 	   }
1.237     www      3928:            return '';
                   3929:        }
                   3930: 
1.620     albertel 3931:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3932: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3933: 	   if ($priv ne 'pch') { 
                   3934: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3935: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3936: 			$env{'request.course.id'});
                   3937: 	   }
1.54      www      3938:            return '';
                   3939:        }
1.53      www      3940:    }
                   3941: 
                   3942: # Resource preferences
                   3943: 
                   3944:    if ($thisallowed=~/R/) {
1.620     albertel 3945:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3946:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3947: 	   if ($priv ne 'pch') { 
                   3948: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3949: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3950: 	   }
                   3951: 	   return '';
1.54      www      3952:        }
1.53      www      3953:    }
1.30      www      3954: 
1.246     www      3955: # Restricted by state or randomout?
1.30      www      3956: 
1.52      www      3957:    if ($thisallowed=~/X/) {
1.620     albertel 3958:       if ($env{'acc.randomout'}) {
1.579     albertel 3959: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3960:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3961:             return ''; 
                   3962:          }
1.247     www      3963:       }
                   3964:       if (&condval($statecond)) {
1.52      www      3965: 	 return '2';
                   3966:       } else {
                   3967:          return '';
                   3968:       }
                   3969:    }
1.30      www      3970: 
1.766     albertel 3971:     if ($thisallowed eq 'A') {
                   3972: 	return 'A';
1.814     raeburn  3973:     } elsif ($thisallowed eq 'B') {
                   3974:         return 'B';
1.766     albertel 3975:     }
1.52      www      3976:    return 'F';
1.232     www      3977: }
                   3978: 
1.710     albertel 3979: sub split_uri_for_cond {
                   3980:     my $uri=&deversion(&declutter(shift));
                   3981:     my @uriparts=split(/\//,$uri);
                   3982:     my $filename=pop(@uriparts);
                   3983:     my $pathname=join('/',@uriparts);
                   3984:     return ($pathname,$filename);
                   3985: }
1.232     www      3986: # --------------------------------------------------- Is a resource on the map?
                   3987: 
                   3988: sub is_on_map {
1.710     albertel 3989:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3990:     #Trying to find the conditional for the file
1.620     albertel 3991:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3992: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3993:     if ($match) {
1.289     bowersj2 3994: 	return (1,$1);
                   3995:     } else {
1.434     www      3996: 	return (0,0);
1.289     bowersj2 3997:     }
1.12      www      3998: }
                   3999: 
1.427     www      4000: # --------------------------------------------------------- Get symb from alias
                   4001: 
                   4002: sub get_symb_from_alias {
                   4003:     my $symb=shift;
                   4004:     my ($map,$resid,$url)=&decode_symb($symb);
                   4005: # Already is a symb
                   4006:     if ($url) { return $symb; }
                   4007: # Must be an alias
                   4008:     my $aliassymb='';
                   4009:     my %bighash;
1.620     albertel 4010:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4011:                             &GDBM_READER(),0640)) {
                   4012:         my $rid=$bighash{'mapalias_'.$symb};
                   4013: 	if ($rid) {
                   4014: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4015: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4016: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4017: 	}
                   4018:         untie %bighash;
                   4019:     }
                   4020:     return $aliassymb;
                   4021: }
                   4022: 
1.12      www      4023: # ----------------------------------------------------------------- Define Role
                   4024: 
                   4025: sub definerole {
                   4026:   if (allowed('mcr','/')) {
                   4027:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4028:     foreach my $role (split(':',$sysrole)) {
                   4029: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4030:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4031:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4032: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4033:                return "refused:s:$crole&$cqual"; 
                   4034:             }
                   4035:         }
1.191     harris41 4036:     }
1.800     albertel 4037:     foreach my $role (split(':',$domrole)) {
                   4038: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4039:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4040:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4041: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4042:                return "refused:d:$crole&$cqual"; 
                   4043:             }
                   4044:         }
1.191     harris41 4045:     }
1.800     albertel 4046:     foreach my $role (split(':',$courole)) {
                   4047: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4048:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4049:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4050: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4051:                return "refused:c:$crole&$cqual"; 
                   4052:             }
                   4053:         }
1.191     harris41 4054:     }
1.620     albertel 4055:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4056:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4057: 	        "rolesdef_$rolename=".
                   4058:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4059:     return reply($command,$env{'user.home'});
1.12      www      4060:   } else {
                   4061:     return 'refused';
                   4062:   }
1.105     harris41 4063: }
                   4064: 
                   4065: # ---------------- Make a metadata query against the network of library servers
                   4066: 
                   4067: sub metadata_query {
1.244     matthew  4068:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4069:     my %rhash;
1.244     matthew  4070:     my @server_list = (defined($server_array) ? @$server_array
                   4071:                                               : keys(%libserv) );
                   4072:     for my $server (@server_list) {
1.118     harris41 4073: 	unless ($custom or $customshow) {
                   4074: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4075: 	    $rhash{$server}=$reply;
                   4076: 	}
                   4077: 	else {
                   4078: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4079: 			     &escape($custom).':'.&escape($customshow),
                   4080: 			     $server);
                   4081: 	    $rhash{$server}=$reply;
                   4082: 	}
1.112     harris41 4083:     }
1.118     harris41 4084:     return \%rhash;
1.240     www      4085: }
                   4086: 
                   4087: # ----------------------------------------- Send log queries and wait for reply
                   4088: 
                   4089: sub log_query {
                   4090:     my ($uname,$udom,$query,%filters)=@_;
                   4091:     my $uhome=&homeserver($uname,$udom);
                   4092:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4093:     my $uhost=$hostname{$uhome};
1.800     albertel 4094:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4095:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4096:                        $uhome);
1.479     albertel 4097:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4098:     return get_query_reply($queryid);
                   4099: }
                   4100: 
1.508     raeburn  4101: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4102: 
                   4103: sub fetch_enrollment_query {
1.511     raeburn  4104:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4105:     my $homeserver;
1.547     raeburn  4106:     my $maxtries = 1;
1.508     raeburn  4107:     if ($context eq 'automated') {
                   4108:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4109:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4110:     } else {
                   4111:         $homeserver = &homeserver($cnum,$dom);
                   4112:     }
1.506     raeburn  4113:     my $host=$hostname{$homeserver};
                   4114:     my $cmd = '';
1.800     albertel 4115:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4116:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4117:     }
                   4118:     $cmd =~ s/%%$//;
                   4119:     $cmd = &escape($cmd);
                   4120:     my $query = 'fetchenrollment';
1.620     albertel 4121:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4122:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4123:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4124:         return 'error: '.$queryid;
                   4125:     }
1.506     raeburn  4126:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4127:     my $tries = 1;
                   4128:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4129:         $reply = &get_query_reply($queryid);
                   4130:         $tries ++;
                   4131:     }
1.526     raeburn  4132:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4133:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4134:     } else {
1.515     raeburn  4135:         my @responses = split/:/,$reply;
                   4136:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4137:             foreach my $line (@responses) {
                   4138:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4139:                 $$replyref{$key} = $value;
                   4140:             }
                   4141:         } else {
1.506     raeburn  4142:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4143:             foreach my $line (@responses) {
                   4144:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4145:                 $$replyref{$key} = $value;
                   4146:                 if ($value > 0) {
1.800     albertel 4147:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4148:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4149:                         my $destname = $pathname.'/'.$filename;
                   4150:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4151:                         if ($xml_classlist =~ /^error/) {
                   4152:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4153:                         } else {
1.506     raeburn  4154:                             if ( open(FILE,">$destname") ) {
                   4155:                                 print FILE &unescape($xml_classlist);
                   4156:                                 close(FILE);
1.526     raeburn  4157:                             } else {
                   4158:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4159:                             }
                   4160:                         }
                   4161:                     }
                   4162:                 }
                   4163:             }
                   4164:         }
                   4165:         return 'ok';
                   4166:     }
                   4167:     return 'error';
                   4168: }
                   4169: 
1.242     www      4170: sub get_query_reply {
                   4171:     my $queryid=shift;
1.240     www      4172:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4173:     my $reply='';
                   4174:     for (1..100) {
                   4175: 	sleep 2;
                   4176:         if (-e $replyfile.'.end') {
1.448     albertel 4177: 	    if (open(my $fh,$replyfile)) {
1.240     www      4178:                $reply.=<$fh>;
1.448     albertel 4179:                close($fh);
1.240     www      4180: 	   } else { return 'error: reply_file_error'; }
1.242     www      4181:            return &unescape($reply);
                   4182: 	}
1.240     www      4183:     }
1.242     www      4184:     return 'timeout:'.$queryid;
1.240     www      4185: }
                   4186: 
                   4187: sub courselog_query {
1.241     www      4188: #
                   4189: # possible filters:
                   4190: # url: url or symb
                   4191: # username
                   4192: # domain
                   4193: # action: view, submit, grade
                   4194: # start: timestamp
                   4195: # end: timestamp
                   4196: #
1.240     www      4197:     my (%filters)=@_;
1.620     albertel 4198:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4199:     if ($filters{'url'}) {
                   4200: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4201:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4202:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4203:     }
1.620     albertel 4204:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4205:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4206:     return &log_query($cname,$cdom,'courselog',%filters);
                   4207: }
                   4208: 
                   4209: sub userlog_query {
                   4210:     my ($uname,$udom,%filters)=@_;
                   4211:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4212: }
                   4213: 
1.506     raeburn  4214: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4215: 
                   4216: sub auto_run {
1.508     raeburn  4217:     my ($cnum,$cdom) = @_;
                   4218:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4219:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4220:     return $response;
                   4221: }
1.776     albertel 4222: 
1.506     raeburn  4223: sub auto_get_sections {
1.508     raeburn  4224:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4225:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4226:     my @secs = ();
1.511     raeburn  4227:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4228:     unless ($response eq 'refused') {
                   4229:         @secs = split/:/,$response;
                   4230:     }
                   4231:     return @secs;
                   4232: }
1.776     albertel 4233: 
1.506     raeburn  4234: sub auto_new_course {
1.508     raeburn  4235:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4236:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4237:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4238:     return $response;
                   4239: }
1.776     albertel 4240: 
1.506     raeburn  4241: sub auto_validate_courseID {
1.508     raeburn  4242:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4243:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4244:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4245:     return $response;
                   4246: }
1.776     albertel 4247: 
1.506     raeburn  4248: sub auto_create_password {
1.508     raeburn  4249:     my ($cnum,$cdom,$authparam) = @_;
                   4250:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4251:     my $create_passwd = 0;
                   4252:     my $authchk = '';
1.511     raeburn  4253:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4254:     if ($response eq 'refused') {
                   4255:         $authchk = 'refused';
                   4256:     } else {
                   4257:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4258:     }
                   4259:     return ($authparam,$create_passwd,$authchk);
                   4260: }
                   4261: 
1.706     raeburn  4262: sub auto_photo_permission {
                   4263:     my ($cnum,$cdom,$students) = @_;
                   4264:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4265:     my ($outcome,$perm_reqd,$conditions) = 
                   4266: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4267:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4268: 	return (undef,undef);
                   4269:     }
1.706     raeburn  4270:     return ($outcome,$perm_reqd,$conditions);
                   4271: }
                   4272: 
                   4273: sub auto_checkphotos {
                   4274:     my ($uname,$udom,$pid) = @_;
                   4275:     my $homeserver = &homeserver($uname,$udom);
                   4276:     my ($result,$resulttype);
                   4277:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4278: 				   &escape($uname).':'.&escape($pid),
                   4279: 				   $homeserver));
1.709     albertel 4280:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4281: 	return (undef,undef);
                   4282:     }
1.706     raeburn  4283:     if ($outcome) {
                   4284:         ($result,$resulttype) = split(/:/,$outcome);
                   4285:     } 
                   4286:     return ($result,$resulttype);
                   4287: }
                   4288: 
                   4289: sub auto_photochoice {
                   4290:     my ($cnum,$cdom) = @_;
                   4291:     my $homeserver = &homeserver($cnum,$cdom);
                   4292:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4293: 						       &escape($cdom),
                   4294: 						       $homeserver)));
1.709     albertel 4295:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4296: 	return (undef,undef);
                   4297:     }
1.706     raeburn  4298:     return ($update,$comment);
                   4299: }
                   4300: 
                   4301: sub auto_photoupdate {
                   4302:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4303:     my $homeserver = &homeserver($cnum,$dom);
                   4304:     my $host=$hostname{$homeserver};
                   4305:     my $cmd = '';
                   4306:     my $maxtries = 1;
1.800     albertel 4307:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4308:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4309:     }
                   4310:     $cmd =~ s/%%$//;
                   4311:     $cmd = &escape($cmd);
                   4312:     my $query = 'institutionalphotos';
                   4313:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4314:     unless ($queryid=~/^\Q$host\E\_/) {
                   4315:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4316:         return 'error: '.$queryid;
                   4317:     }
                   4318:     my $reply = &get_query_reply($queryid);
                   4319:     my $tries = 1;
                   4320:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4321:         $reply = &get_query_reply($queryid);
                   4322:         $tries ++;
                   4323:     }
                   4324:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4325:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4326:     } else {
                   4327:         my @responses = split(/:/,$reply);
                   4328:         my $outcome = shift(@responses); 
                   4329:         foreach my $item (@responses) {
                   4330:             my ($key,$value) = split(/=/,$item);
                   4331:             $$photo{$key} = $value;
                   4332:         }
                   4333:         return $outcome;
                   4334:     }
                   4335:     return 'error';
                   4336: }
                   4337: 
1.521     raeburn  4338: sub auto_instcode_format {
1.793     albertel 4339:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4340: 	$cat_order) = @_;
1.521     raeburn  4341:     my $courses = '';
1.772     raeburn  4342:     my @homeservers;
1.521     raeburn  4343:     if ($caller eq 'global') {
1.793     albertel 4344:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4345:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4346:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4347:                     push(@homeservers,$tryserver);
                   4348:                 }
1.584     raeburn  4349:             }
                   4350:         }
1.521     raeburn  4351:     } else {
1.772     raeburn  4352:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4353:     }
1.793     albertel 4354:     foreach my $code (keys(%{$instcodes})) {
                   4355:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4356:     }
                   4357:     chop($courses);
1.772     raeburn  4358:     my $ok_response = 0;
                   4359:     my $response;
                   4360:     while (@homeservers > 0 && $ok_response == 0) {
                   4361:         my $server = shift(@homeservers); 
                   4362:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4363:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4364:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4365: 		split/:/,$response;
1.772     raeburn  4366:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4367:             push(@{$codetitles},&str2array($codetitles_str));
                   4368:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4369:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4370:             $ok_response = 1;
                   4371:         }
                   4372:     }
                   4373:     if ($ok_response) {
1.521     raeburn  4374:         return 'ok';
1.772     raeburn  4375:     } else {
                   4376:         return $response;
1.521     raeburn  4377:     }
                   4378: }
                   4379: 
1.792     raeburn  4380: sub auto_instcode_defaults {
                   4381:     my ($domain,$returnhash,$code_order) = @_;
                   4382:     my @homeservers;
1.793     albertel 4383:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4384:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4385:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4386:                 push(@homeservers,$tryserver);
                   4387:             }
                   4388:         }
                   4389:     }
                   4390:     my $ok_response = 0;
                   4391:     my $response;
                   4392:     while (@homeservers > 0 && $ok_response == 0) {
                   4393:         my $server = shift(@homeservers);
                   4394:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4395:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4396:             foreach my $pair (split(/\&/,$response)) {
                   4397:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4398:                 if ($name eq 'code_order') {
1.796     raeburn  4399:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4400:                 } else {
1.796     raeburn  4401:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4402:                 }
                   4403:             }
1.804     raeburn  4404:             $ok_response = 1;
1.792     raeburn  4405:         }
                   4406:     }
                   4407:     if ($ok_response) {
                   4408:         return 'ok';
                   4409:     } else {
                   4410:         return $response;
                   4411:     }
                   4412: } 
                   4413: 
1.777     albertel 4414: sub auto_validate_class_sec {
1.773     raeburn  4415:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4416:     my $homeserver = &homeserver($cnum,$cdom);
                   4417:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4418:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4419:     return $response;
                   4420: }
                   4421: 
1.679     raeburn  4422: # ------------------------------------------------------- Course Group routines
                   4423: 
                   4424: sub get_coursegroups {
1.809     raeburn  4425:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4426:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4427: }
                   4428: 
1.679     raeburn  4429: sub modify_coursegroup {
                   4430:     my ($cdom,$cnum,$groupsettings) = @_;
                   4431:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4432: }
                   4433: 
1.809     raeburn  4434: sub toggle_coursegroup_status {
                   4435:     my ($cdom,$cnum,$group,$action) = @_;
                   4436:     my ($from_namespace,$to_namespace);
                   4437:     if ($action eq 'delete') {
                   4438:         $from_namespace = 'coursegroups';
                   4439:         $to_namespace = 'deleted_groups';
                   4440:     } else {
                   4441:         $from_namespace = 'deleted_groups';
                   4442:         $to_namespace = 'coursegroups';
                   4443:     }
                   4444:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4445:     if (my $tmp = &error(%curr_group)) {
                   4446:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4447:         return ('read error',$tmp);
                   4448:     } else {
                   4449:         my %savedsettings = %curr_group; 
1.809     raeburn  4450:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4451:         my $deloutcome;
                   4452:         if ($result eq 'ok') {
1.809     raeburn  4453:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4454:         } else {
                   4455:             return ('write error',$result);
                   4456:         }
                   4457:         if ($deloutcome eq 'ok') {
                   4458:             return 'ok';
                   4459:         } else {
                   4460:             return ('delete error',$deloutcome);
                   4461:         }
                   4462:     }
                   4463: }
                   4464: 
1.679     raeburn  4465: sub modify_group_roles {
                   4466:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4467:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4468:     my $role = 'gr/'.&escape($userprivs);
                   4469:     my ($uname,$udom) = split(/:/,$user);
                   4470:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4471:     if ($result eq 'ok') {
                   4472:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4473:     }
1.679     raeburn  4474:     return $result;
                   4475: }
                   4476: 
                   4477: sub modify_coursegroup_membership {
                   4478:     my ($cdom,$cnum,$membership) = @_;
                   4479:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4480:     return $result;
                   4481: }
                   4482: 
1.682     raeburn  4483: sub get_active_groups {
                   4484:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4485:     my $now = time;
                   4486:     my %groups = ();
                   4487:     foreach my $key (keys(%env)) {
1.811     albertel 4488:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4489:             my ($start,$end) = split(/\./,$env{$key});
                   4490:             if (($end!=0) && ($end<$now)) { next; }
                   4491:             if (($start!=0) && ($start>$now)) { next; }
                   4492:             if ($1 eq $cdom && $2 eq $cnum) {
                   4493:                 $groups{$3} = $env{$key} ;
                   4494:             }
                   4495:         }
                   4496:     }
                   4497:     return %groups;
                   4498: }
                   4499: 
1.683     raeburn  4500: sub get_group_membership {
                   4501:     my ($cdom,$cnum,$group) = @_;
                   4502:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4503: }
                   4504: 
                   4505: sub get_users_groups {
                   4506:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4507:     my @usersgroups;
1.683     raeburn  4508:     my $cachetime=1800;
                   4509: 
                   4510:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4511:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4512:     if (defined($cached)) {
1.734     albertel 4513:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4514:     } else {  
                   4515:         $grouplist = '';
1.816   ! raeburn  4516:         my $courseurl = &courseid_to_courseurl($courseid);
        !          4517:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.733     raeburn  4518:         my ($tmp) = keys(%roleshash);
                   4519:         if ($tmp=~/^error:/) {
                   4520:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4521:         } else {
                   4522:             my $access_end = $env{'course.'.$courseid.
                   4523:                                   '.default_enrollment_end_date'};
                   4524:             my $now = time;
1.734     albertel 4525:             foreach my $key (keys(%roleshash)) {
1.816   ! raeburn  4526:                 if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
1.733     raeburn  4527:                     my $group = $1;
                   4528:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4529:                         my $start = $2;
                   4530:                         my $end = $1;
                   4531:                         if ($start == -1) { next; } # deleted from group
                   4532:                         if (($start!=0) && ($start>$now)) { next; }
                   4533:                         if (($end!=0) && ($end<$now)) {
                   4534:                             if ($access_end && $access_end < $now) {
                   4535:                                 if ($access_end - $end < 86400) {
                   4536:                                     push(@usersgroups,$group);
                   4537:                                 }
                   4538:                             }
                   4539:                             next;
                   4540:                         }
                   4541:                         push(@usersgroups,$group);
                   4542:                     }
1.683     raeburn  4543:                 }
                   4544:             }
1.733     raeburn  4545:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4546:             $grouplist = join(':',@usersgroups);
                   4547:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4548:         }
                   4549:     }
1.733     raeburn  4550:     return @usersgroups;
1.683     raeburn  4551: }
                   4552: 
                   4553: sub devalidate_getgroups_cache {
                   4554:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4555:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4556: 
1.683     raeburn  4557:     my $hashid="$udom:$uname:$courseid";
                   4558:     &devalidate_cache_new('getgroups',$hashid);
                   4559: }
                   4560: 
1.12      www      4561: # ------------------------------------------------------------------ Plain Text
                   4562: 
                   4563: sub plaintext {
1.742     raeburn  4564:     my ($short,$type,$cid) = @_;
1.758     albertel 4565:     if ($short =~ /^cr/) {
                   4566: 	return (split('/',$short))[-1];
                   4567:     }
1.742     raeburn  4568:     if (!defined($cid)) {
                   4569:         $cid = $env{'request.course.id'};
                   4570:     }
                   4571:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4572:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4573:                                           '.plaintext'});
                   4574:     }
                   4575:     my %rolenames = (
                   4576:                       Course => 'std',
                   4577:                       Group => 'alt1',
                   4578:                     );
                   4579:     if (defined($type) && 
                   4580:          defined($rolenames{$type}) && 
                   4581:          defined($prp{$short}{$rolenames{$type}})) {
                   4582:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4583:     } else {
                   4584:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4585:     }
1.12      www      4586: }
                   4587: 
                   4588: # ----------------------------------------------------------------- Assign Role
                   4589: 
                   4590: sub assignrole {
1.357     www      4591:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4592:     my $mrole;
                   4593:     if ($role =~ /^cr\//) {
1.393     www      4594:         my $cwosec=$url;
1.811     albertel 4595:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4596: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4597:            &logthis('Refused custom assignrole: '.
                   4598:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4599: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4600:            return 'refused'; 
                   4601:         }
1.21      www      4602:         $mrole='cr';
1.678     raeburn  4603:     } elsif ($role =~ /^gr\//) {
                   4604:         my $cwogrp=$url;
1.811     albertel 4605:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4606:         unless (&allowed('mdg',$cwogrp)) {
                   4607:             &logthis('Refused group assignrole: '.
                   4608:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4609:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4610:             return 'refused';
                   4611:         }
                   4612:         $mrole='gr';
1.21      www      4613:     } else {
1.82      www      4614:         my $cwosec=$url;
1.811     albertel 4615:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4616:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4617:            &logthis('Refused assignrole: '.
                   4618:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4619: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4620:            return 'refused'; 
                   4621:         }
1.21      www      4622:         $mrole=$role;
                   4623:     }
1.620     albertel 4624:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4625:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4626:     if ($end) { $command.='_'.$end; }
1.21      www      4627:     if ($start) {
                   4628: 	if ($end) { 
1.81      www      4629:            $command.='_'.$start; 
1.21      www      4630:         } else {
1.81      www      4631:            $command.='_0_'.$start;
1.21      www      4632:         }
                   4633:     }
1.739     raeburn  4634:     my $origstart = $start;
                   4635:     my $origend = $end;
1.357     www      4636: # actually delete
                   4637:     if ($deleteflag) {
1.373     www      4638: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4639: # modify command to delete the role
1.620     albertel 4640:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4641:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4642: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4643: # set start and finish to negative values for userrolelog
                   4644:            $start=-1;
                   4645:            $end=-1;
                   4646:         }
                   4647:     }
                   4648: # send command
1.349     www      4649:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4650: # log new user role if status is ok
1.349     www      4651:     if ($answer eq 'ok') {
1.663     raeburn  4652: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4653: # for course roles, perform group memberships changes triggered by role change.
                   4654:         unless ($role =~ /^gr/) {
                   4655:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4656:                                              $origstart);
                   4657:         }
1.349     www      4658:     }
                   4659:     return $answer;
1.169     harris41 4660: }
                   4661: 
                   4662: # -------------------------------------------------- Modify user authentication
1.197     www      4663: # Overrides without validation
                   4664: 
1.169     harris41 4665: sub modifyuserauth {
                   4666:     my ($udom,$uname,$umode,$upass)=@_;
                   4667:     my $uhome=&homeserver($uname,$udom);
1.197     www      4668:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4669:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4670:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4671:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4672:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4673: 		     &escape($upass),$uhome);
1.620     albertel 4674:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4675:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4676:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4677:     &log($udom,,$uname,$uhome,
1.620     albertel 4678:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4679:                                      $env{'user.name'}.', '.$umode.
1.197     www      4680:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4681:     unless ($reply eq 'ok') {
1.197     www      4682:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4683: 	return 'error: '.$reply;
                   4684:     }   
1.170     harris41 4685:     return 'ok';
1.80      www      4686: }
                   4687: 
1.81      www      4688: # --------------------------------------------------------------- Modify a user
1.80      www      4689: 
1.81      www      4690: sub modifyuser {
1.206     matthew  4691:     my ($udom,    $uname, $uid,
                   4692:         $umode,   $upass, $first,
                   4693:         $middle,  $last,  $gene,
1.387     www      4694:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4695:     $udom= &LONCAPA::clean_domain($udom);
                   4696:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4697:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4698:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4699: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4700:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4701:                                      ' desiredhome not specified'). 
1.620     albertel 4702:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4703:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4704:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4705: # ----------------------------------------------------------------- Create User
1.406     albertel 4706:     if (($uhome eq 'no_host') && 
                   4707: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4708:         my $unhome='';
1.209     matthew  4709:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4710:             $unhome = $desiredhome;
1.620     albertel 4711: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4712: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4713:         } else { # load balancing routine for determining $unhome
1.80      www      4714:             my $tryserver;
1.81      www      4715:             my $loadm=10000000;
1.80      www      4716:             foreach $tryserver (keys %libserv) {
                   4717: 	       if ($hostdom{$tryserver} eq $udom) {
                   4718:                   my $answer=reply('load',$tryserver);
                   4719:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4720: 		      $loadm=$answer;
                   4721:                       $unhome=$tryserver;
                   4722:                   }
                   4723: 	       }
                   4724: 	    }
                   4725:         }
                   4726:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4727: 	    return 'error: unable to find a home server for '.$uname.
                   4728:                    ' in domain '.$udom;
1.80      www      4729:         }
                   4730:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4731:                          &escape($upass),$unhome);
                   4732: 	unless ($reply eq 'ok') {
                   4733:             return 'error: '.$reply;
                   4734:         }   
1.230     stredwic 4735:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4736:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4737: 	    return 'error: unable verify users home machine.';
1.80      www      4738:         }
1.209     matthew  4739:     }   # End of creation of new user
1.80      www      4740: # ---------------------------------------------------------------------- Add ID
                   4741:     if ($uid) {
                   4742:        $uid=~tr/A-Z/a-z/;
                   4743:        my %uidhash=&idrget($udom,$uname);
1.196     www      4744:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4745:          && (!$forceid)) {
1.80      www      4746: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4747: 	      return 'error: user id "'.$uid.'" does not match '.
                   4748:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4749:           }
                   4750:        } else {
                   4751: 	  &idput($udom,($uname => $uid));
                   4752:        }
                   4753:     }
                   4754: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4755:     my @tmp=&get('environment',
1.134     albertel 4756: 		   ['firstname','middlename','lastname','generation'],
                   4757: 		   $udom,$uname);
1.313     matthew  4758:     my %names;
                   4759:     if ($tmp[0] =~ m/^error:.*/) { 
                   4760:         %names=(); 
                   4761:     } else {
                   4762:         %names = @tmp;
                   4763:     }
1.388     www      4764: #
                   4765: # Make sure to not trash student environment if instructor does not bother
                   4766: # to supply name and email information
                   4767: #
                   4768:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4769:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4770:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4771:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4772:     if ($email) {
                   4773:        $email=~s/[^\w\@\.\-\,]//gs;
                   4774:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4775: 			   $names{'critnotification'} = $email;
                   4776: 			   $names{'permanentemail'} = $email; }
                   4777:     }
1.134     albertel 4778:     my $reply = &put('environment', \%names, $udom,$uname);
                   4779:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4780:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4781:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4782:              $umode.', '.$first.', '.$middle.', '.
                   4783: 	     $last.', '.$gene.' by '.
1.620     albertel 4784:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4785:     return 'ok';
1.80      www      4786: }
                   4787: 
1.81      www      4788: # -------------------------------------------------------------- Modify student
1.80      www      4789: 
1.81      www      4790: sub modifystudent {
                   4791:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4792:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4793:     if (!$cid) {
1.620     albertel 4794: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4795: 	    return 'not_in_class';
                   4796: 	}
1.80      www      4797:     }
                   4798: # --------------------------------------------------------------- Make the user
1.81      www      4799:     my $reply=&modifyuser
1.209     matthew  4800: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4801:          $desiredhome,$email);
1.80      www      4802:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4803:     # This will cause &modify_student_enrollment to get the uid from the
                   4804:     # students environment
                   4805:     $uid = undef if (!$forceid);
1.455     albertel 4806:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4807: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4808:     return $reply;
                   4809: }
                   4810: 
                   4811: sub modify_student_enrollment {
1.515     raeburn  4812:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4813:     my ($cdom,$cnum,$chome);
                   4814:     if (!$cid) {
1.620     albertel 4815: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4816: 	    return 'not_in_class';
                   4817: 	}
1.620     albertel 4818: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4819: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4820:     } else {
                   4821: 	($cdom,$cnum)=split(/_/,$cid);
                   4822:     }
1.620     albertel 4823:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4824:     if (!$chome) {
1.457     raeburn  4825: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4826:     }
1.455     albertel 4827:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4828:     # Make sure the user exists
1.81      www      4829:     my $uhome=&homeserver($uname,$udom);
                   4830:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4831: 	return 'error: no such user';
                   4832:     }
1.297     matthew  4833:     # Get student data if we were not given enough information
                   4834:     if (!defined($first)  || $first  eq '' || 
                   4835:         !defined($last)   || $last   eq '' || 
                   4836:         !defined($uid)    || $uid    eq '' || 
                   4837:         !defined($middle) || $middle eq '' || 
                   4838:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4839:         # They did not supply us with enough data to enroll the student, so
                   4840:         # we need to pick up more information.
1.297     matthew  4841:         my %tmp = &get('environment',
1.294     matthew  4842:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4843:                        ,$udom,$uname);
                   4844: 
1.800     albertel 4845:         #foreach my $key (keys(%tmp)) {
                   4846:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4847:         #}
1.294     matthew  4848:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4849:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4850:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4851:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4852:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4853:     }
1.556     albertel 4854:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4855:     my $reply=cput('classlist',
                   4856: 		   {"$uname:$udom" => 
1.515     raeburn  4857: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4858: 		   $cdom,$cnum);
1.81      www      4859:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4860: 	return 'error: '.$reply;
1.652     albertel 4861:     } else {
                   4862: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4863:     }
1.297     matthew  4864:     # Add student role to user
1.83      www      4865:     my $uurl='/'.$cid;
1.81      www      4866:     $uurl=~s/\_/\//g;
                   4867:     if ($usec) {
                   4868: 	$uurl.='/'.$usec;
                   4869:     }
                   4870:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4871: }
                   4872: 
1.556     albertel 4873: sub format_name {
                   4874:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4875:     my $name;
                   4876:     if ($first ne 'lastname') {
                   4877: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4878:     } else {
                   4879: 	if ($lastname=~/\S/) {
                   4880: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4881: 	    $name=~s/\s+,/,/;
                   4882: 	} else {
                   4883: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4884: 	}
                   4885:     }
                   4886:     $name=~s/^\s+//;
                   4887:     $name=~s/\s+$//;
                   4888:     $name=~s/\s+/ /g;
                   4889:     return $name;
                   4890: }
                   4891: 
1.84      www      4892: # ------------------------------------------------- Write to course preferences
                   4893: 
                   4894: sub writecoursepref {
                   4895:     my ($courseid,%prefs)=@_;
                   4896:     $courseid=~s/^\///;
                   4897:     $courseid=~s/\_/\//g;
                   4898:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4899:     my $chome=homeserver($cnum,$cdomain);
                   4900:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4901: 	return 'error: no such course';
                   4902:     }
                   4903:     my $cstring='';
1.800     albertel 4904:     foreach my $pref (keys(%prefs)) {
                   4905: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4906:     }
1.84      www      4907:     $cstring=~s/\&$//;
                   4908:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4909: }
                   4910: 
                   4911: # ---------------------------------------------------------- Make/modify course
                   4912: 
                   4913: sub createcourse {
1.741     raeburn  4914:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4915:         $course_owner,$crstype)=@_;
1.84      www      4916:     $url=&declutter($url);
                   4917:     my $cid='';
1.264     matthew  4918:     unless (&allowed('ccc',$udom)) {
1.84      www      4919:         return 'refused';
                   4920:     }
                   4921: # ------------------------------------------------------------------- Create ID
1.674     www      4922:    my $uname=int(1+rand(9)).
                   4923:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4924:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4925:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4926: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4927:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4928:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4929:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4930:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4931:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4932:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4933:            return 'error: unable to generate unique course-ID';
                   4934:        } 
                   4935:    }
1.264     matthew  4936: # ------------------------------------------------ Check supplied server name
1.620     albertel 4937:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4938:     if (! exists($libserv{$course_server})) {
                   4939:         return 'error:bad server name '.$course_server;
                   4940:     }
1.84      www      4941: # ------------------------------------------------------------- Make the course
                   4942:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4943:                       $course_server);
1.84      www      4944:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4945:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4946:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4947: 	return 'error: no such course';
                   4948:     }
1.271     www      4949: # ----------------------------------------------------------------- Course made
1.516     raeburn  4950: # log existence
                   4951:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4952:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4953:                   &escape($crstype),$uhome);
1.358     www      4954:     &flushcourselogs();
                   4955: # set toplevel url
1.271     www      4956:     my $topurl=$url;
                   4957:     unless ($nonstandard) {
                   4958: # ------------------------------------------ For standard courses, make top url
                   4959:         my $mapurl=&clutter($url);
1.278     www      4960:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4961:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4962: <map>
                   4963: <resource id="1" type="start"></resource>
                   4964: <resource id="2" src="$mapurl"></resource>
                   4965: <resource id="3" type="finish"></resource>
                   4966: <link index="1" from="1" to="2"></link>
                   4967: <link index="2" from="2" to="3"></link>
                   4968: </map>
                   4969: ENDINITMAP
                   4970:         $topurl=&declutter(
1.638     albertel 4971:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4972:                           );
                   4973:     }
                   4974: # ----------------------------------------------------------- Write preferences
1.84      www      4975:     &writecoursepref($udom.'_'.$uname,
                   4976:                      ('description' => $description,
1.271     www      4977:                       'url'         => $topurl));
1.84      www      4978:     return '/'.$udom.'/'.$uname;
                   4979: }
                   4980: 
1.813     albertel 4981: sub is_course {
                   4982:     my ($cdom,$cnum) = @_;
                   4983:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   4984: 				undef,'.');
                   4985:     if (exists($courses{$cdom.'_'.$cnum})) {
                   4986:         return 1;
                   4987:     }
                   4988:     return 0;
                   4989: }
                   4990: 
1.21      www      4991: # ---------------------------------------------------------- Assign Custom Role
                   4992: 
                   4993: sub assigncustomrole {
1.357     www      4994:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4995:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4996:                        $end,$start,$deleteflag);
1.21      www      4997: }
                   4998: 
                   4999: # ----------------------------------------------------------------- Revoke Role
                   5000: 
                   5001: sub revokerole {
1.357     www      5002:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5003:     my $now=time;
1.357     www      5004:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5005: }
                   5006: 
                   5007: # ---------------------------------------------------------- Revoke Custom Role
                   5008: 
                   5009: sub revokecustomrole {
1.357     www      5010:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5011:     my $now=time;
1.357     www      5012:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5013:            $deleteflag);
1.17      www      5014: }
                   5015: 
1.533     banghart 5016: # ------------------------------------------------------------ Disk usage
1.535     albertel 5017: sub diskusage {
1.533     banghart 5018:     my ($udom,$uname,$directoryRoot)=@_;
                   5019:     $directoryRoot =~ s/\/$//;
1.535     albertel 5020:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5021:     return $listing;
1.512     banghart 5022: }
                   5023: 
1.566     banghart 5024: sub is_locked {
                   5025:     my ($file_name, $domain, $user) = @_;
                   5026:     my @check;
                   5027:     my $is_locked;
                   5028:     push @check, $file_name;
1.613     albertel 5029:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5030: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5031:     my ($tmp)=keys(%locked);
                   5032:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5033:     
1.566     banghart 5034:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5035:         $is_locked = 'false';
                   5036:         foreach my $entry (@{$locked{$file_name}}) {
                   5037:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5038:                $is_locked = 'true';
                   5039:                last;
1.745     raeburn  5040:            }
                   5041:        }
1.566     banghart 5042:     } else {
                   5043:         $is_locked = 'false';
                   5044:     }
                   5045: }
                   5046: 
1.759     albertel 5047: sub declutter_portfile {
                   5048:     my ($file) = @_;
                   5049:     &logthis("got $file");
                   5050:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5051:     &logthis("ret $file");
                   5052:     return $file;
                   5053: }
                   5054: 
1.559     banghart 5055: # ------------------------------------------------------------- Mark as Read Only
                   5056: 
                   5057: sub mark_as_readonly {
                   5058:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5059:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5060:     my ($tmp)=keys(%current_permissions);
                   5061:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5062:     foreach my $file (@{$files}) {
1.759     albertel 5063: 	$file = &declutter_portfile($file);
1.561     banghart 5064:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5065:     }
1.613     albertel 5066:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5067:     return;
                   5068: }
                   5069: 
1.572     banghart 5070: # ------------------------------------------------------------Save Selected Files
                   5071: 
                   5072: sub save_selected_files {
                   5073:     my ($user, $path, @files) = @_;
                   5074:     my $filename = $user."savedfiles";
1.573     banghart 5075:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5076:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5077:     foreach my $file (@files) {
1.620     albertel 5078:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5079:     }
                   5080:     foreach my $file (@other_files) {
1.574     banghart 5081:         print (OUT $file."\n");
1.572     banghart 5082:     }
1.574     banghart 5083:     close (OUT);
1.572     banghart 5084:     return 'ok';
                   5085: }
                   5086: 
1.574     banghart 5087: sub clear_selected_files {
                   5088:     my ($user) = @_;
                   5089:     my $filename = $user."savedfiles";
                   5090:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5091:     print (OUT undef);
                   5092:     close (OUT);
                   5093:     return ("ok");    
                   5094: }
                   5095: 
1.572     banghart 5096: sub files_in_path {
                   5097:     my ($user, $path) = @_;
                   5098:     my $filename = $user."savedfiles";
                   5099:     my %return_files;
1.574     banghart 5100:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5101:     while (my $line_in = <IN>) {
1.574     banghart 5102:         chomp ($line_in);
                   5103:         my @paths_and_file = split (m!/!, $line_in);
                   5104:         my $file_part = pop (@paths_and_file);
                   5105:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5106:         $path_part.='/';
                   5107:         my $path_and_file = $path_part.$file_part;
                   5108:         if ($path_part eq $path) {
                   5109:             $return_files{$file_part}= 'selected';
                   5110:         }
                   5111:     }
1.574     banghart 5112:     close (IN);
                   5113:     return (\%return_files);
1.572     banghart 5114: }
                   5115: 
                   5116: # called in portfolio select mode, to show files selected NOT in current directory
                   5117: sub files_not_in_path {
                   5118:     my ($user, $path) = @_;
                   5119:     my $filename = $user."savedfiles";
                   5120:     my @return_files;
                   5121:     my $path_part;
1.800     albertel 5122:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5123:     while (my $line = <IN>) {
1.572     banghart 5124:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5125:         my @paths_and_file = split(m|/|, $line);
                   5126:         my $file_part = pop(@paths_and_file);
                   5127:         chomp($file_part);
                   5128:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5129:         $path_part .= '/';
                   5130:         my $path_and_file = $path_part.$file_part;
                   5131:         if ($path_part ne $path) {
1.800     albertel 5132:             push(@return_files, ($path_and_file));
1.572     banghart 5133:         }
                   5134:     }
1.800     albertel 5135:     close(OUT);
1.574     banghart 5136:     return (@return_files);
1.572     banghart 5137: }
                   5138: 
1.745     raeburn  5139: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5140: 
1.745     raeburn  5141: sub get_portfile_permissions {
                   5142:     my ($domain,$user) = @_;
1.613     albertel 5143:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5144:     my ($tmp)=keys(%current_permissions);
                   5145:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5146:     return \%current_permissions;
                   5147: }
                   5148: 
                   5149: #---------------------------------------------Get portfolio file access controls
                   5150: 
1.749     raeburn  5151: sub get_access_controls {
1.745     raeburn  5152:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5153:     my %access;
                   5154:     my $real_file = $file;
                   5155:     $file =~ s/\.meta$//;
1.745     raeburn  5156:     if (defined($file)) {
1.749     raeburn  5157:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5158:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5159:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5160:             }
                   5161:         }
1.745     raeburn  5162:     } else {
1.749     raeburn  5163:         foreach my $key (keys(%{$current_permissions})) {
                   5164:             if ($key =~ /\0accesscontrol$/) {
                   5165:                 if (defined($group)) {
                   5166:                     if ($key !~ m-^\Q$group\E/-) {
                   5167:                         next;
                   5168:                     }
                   5169:                 }
                   5170:                 my ($fullpath) = split(/\0/,$key);
                   5171:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5172:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5173:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5174:                     }
                   5175:                 }
                   5176:             }
                   5177:         }
                   5178:     }
                   5179:     return %access;
                   5180: }
                   5181: 
                   5182: sub modify_access_controls {
                   5183:     my ($file_name,$changes,$domain,$user)=@_;
                   5184:     my ($outcome,$deloutcome);
                   5185:     my %store_permissions;
                   5186:     my %new_values;
                   5187:     my %new_control;
                   5188:     my %translation;
                   5189:     my @deletions = ();
                   5190:     my $now = time;
                   5191:     if (exists($$changes{'activate'})) {
                   5192:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5193:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5194:             my $numnew = scalar(@newitems);
                   5195:             for (my $i=0; $i<$numnew; $i++) {
                   5196:                 my $newkey = $newitems[$i];
                   5197:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5198:                 if ($newkey =~ /^\d+:/) { 
                   5199:                     $newkey =~ s/^(\d+)/$newid/;
                   5200:                     $translation{$1} = $newid;
                   5201:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5202:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5203:                     $translation{$1} = $newid;
                   5204:                 }
1.749     raeburn  5205:                 $new_values{$file_name."\0".$newkey} = 
                   5206:                                           $$changes{'activate'}{$newitems[$i]};
                   5207:                 $new_control{$newkey} = $now;
                   5208:             }
                   5209:         }
                   5210:     }
                   5211:     my %todelete;
                   5212:     my %changed_items;
                   5213:     foreach my $action ('delete','update') {
                   5214:         if (exists($$changes{$action})) {
                   5215:             if (ref($$changes{$action}) eq 'HASH') {
                   5216:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5217:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5218:                     if ($action eq 'delete') { 
                   5219:                         $todelete{$itemnum} = 1;
                   5220:                     } else {
                   5221:                         $changed_items{$itemnum} = $key;
                   5222:                     }
                   5223:                 }
1.745     raeburn  5224:             }
                   5225:         }
1.749     raeburn  5226:     }
                   5227:     # get lock on access controls for file.
                   5228:     my $lockhash = {
                   5229:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5230:                                                        ':'.$env{'user.domain'},
                   5231:                    }; 
                   5232:     my $tries = 0;
                   5233:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5234:    
                   5235:     while (($gotlock ne 'ok') && $tries <3) {
                   5236:         $tries ++;
                   5237:         sleep 1;
                   5238:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5239:     }
                   5240:     if ($gotlock eq 'ok') {
                   5241:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5242:         my ($tmp)=keys(%curr_permissions);
                   5243:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5244:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5245:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5246:             if (ref($curr_controls) eq 'HASH') {
                   5247:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5248:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5249:                     if (defined($todelete{$itemnum})) {
                   5250:                         push(@deletions,$file_name."\0".$control_item);
                   5251:                     } else {
                   5252:                         if (defined($changed_items{$itemnum})) {
                   5253:                             $new_control{$changed_items{$itemnum}} = $now;
                   5254:                             push(@deletions,$file_name."\0".$control_item);
                   5255:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5256:                         } else {
                   5257:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5258:                         }
                   5259:                     }
1.745     raeburn  5260:                 }
                   5261:             }
                   5262:         }
1.749     raeburn  5263:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5264:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5265:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5266:         #  remove lock
                   5267:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5268:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5269:     } else {
                   5270:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5271:     }
1.749     raeburn  5272:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5273: }
                   5274: 
                   5275: #------------------------------------------------------Get Marked as Read Only
                   5276: 
                   5277: sub get_marked_as_readonly {
                   5278:     my ($domain,$user,$what,$group) = @_;
                   5279:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5280:     my @readonly_files;
1.629     banghart 5281:     my $cmp1=$what;
                   5282:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5283:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5284:         if (defined($group)) {
                   5285:             if ($file_name !~ m-^\Q$group\E/-) {
                   5286:                 next;
                   5287:             }
                   5288:         }
1.561     banghart 5289:         if (ref($value) eq "ARRAY"){
                   5290:             foreach my $stored_what (@{$value}) {
1.629     banghart 5291:                 my $cmp2=$stored_what;
1.759     albertel 5292:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5293:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5294:                 }
1.629     banghart 5295:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5296:                     push(@readonly_files, $file_name);
1.745     raeburn  5297:                     last;
1.563     banghart 5298:                 } elsif (!defined($what)) {
                   5299:                     push(@readonly_files, $file_name);
1.745     raeburn  5300:                     last;
1.561     banghart 5301:                 }
                   5302:             }
1.745     raeburn  5303:         }
1.561     banghart 5304:     }
                   5305:     return @readonly_files;
                   5306: }
1.577     banghart 5307: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5308: 
1.577     banghart 5309: sub get_marked_as_readonly_hash {
1.745     raeburn  5310:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5311:     my %readonly_files;
1.745     raeburn  5312:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5313:         if (defined($group)) {
                   5314:             if ($file_name !~ m-^\Q$group\E/-) {
                   5315:                 next;
                   5316:             }
                   5317:         }
1.577     banghart 5318:         if (ref($value) eq "ARRAY"){
                   5319:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5320:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5321:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5322:                         if ($lock_descriptor eq 'graded') {
                   5323:                             $readonly_files{$file_name} = 'graded';
                   5324:                         } elsif ($lock_descriptor eq 'handback') {
                   5325:                             $readonly_files{$file_name} = 'handback';
                   5326:                         } else {
                   5327:                             if (!exists($readonly_files{$file_name})) {
                   5328:                                 $readonly_files{$file_name} = 'locked';
                   5329:                             }
                   5330:                         }
1.745     raeburn  5331:                     }
1.750     banghart 5332:                 } 
1.577     banghart 5333:             }
                   5334:         } 
                   5335:     }
                   5336:     return %readonly_files;
                   5337: }
1.559     banghart 5338: # ------------------------------------------------------------ Unmark as Read Only
                   5339: 
                   5340: sub unmark_as_readonly {
1.629     banghart 5341:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5342:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5343:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5344:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5345:     my $symb_crs = $what;
                   5346:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5347:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5348:     my ($tmp)=keys(%current_permissions);
                   5349:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5350:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5351:     foreach my $file (@readonly_files) {
1.759     albertel 5352: 	my $clean_file = &declutter_portfile($file);
                   5353: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5354: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5355:         my @new_locks;
                   5356:         my @del_keys;
                   5357:         if (ref($current_locks) eq "ARRAY"){
                   5358:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5359:                 my $compare=$locker;
1.749     raeburn  5360:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5361:                     $compare=join('',@{$locker});
1.746     raeburn  5362:                     if ($compare ne $symb_crs) {
                   5363:                         push(@new_locks, $locker);
                   5364:                     }
1.563     banghart 5365:                 }
                   5366:             }
1.650     albertel 5367:             if (scalar(@new_locks) > 0) {
1.563     banghart 5368:                 $current_permissions{$file} = \@new_locks;
                   5369:             } else {
                   5370:                 push(@del_keys, $file);
1.613     albertel 5371:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5372:                 delete($current_permissions{$file});
1.563     banghart 5373:             }
                   5374:         }
1.561     banghart 5375:     }
1.613     albertel 5376:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5377:     return;
                   5378: }
1.512     banghart 5379: 
1.17      www      5380: # ------------------------------------------------------------ Directory lister
                   5381: 
                   5382: sub dirlist {
1.253     stredwic 5383:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5384: 
1.18      www      5385:     $uri=~s/^\///;
                   5386:     $uri=~s/\/$//;
1.253     stredwic 5387:     my ($udom, $uname);
                   5388:     (undef,$udom,$uname)=split(/\//,$uri);
                   5389:     if(defined($userdomain)) {
                   5390:         $udom = $userdomain;
                   5391:     }
                   5392:     if(defined($username)) {
                   5393:         $uname = $username;
                   5394:     }
                   5395: 
                   5396:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5397:     if(defined($alternateDirectoryRoot)) {
                   5398:         $dirRoot = $alternateDirectoryRoot;
                   5399:         $dirRoot =~ s/\/$//;
1.751     banghart 5400:     }
1.253     stredwic 5401: 
                   5402:     if($udom) {
                   5403:         if($uname) {
1.800     albertel 5404:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5405: 				 &homeserver($uname,$udom));
1.605     matthew  5406:             my @listing_results;
                   5407:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5408:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5409: 				  &homeserver($uname,$udom));
1.605     matthew  5410:                 @listing_results = split(/:/,$listing);
                   5411:             } else {
                   5412:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5413:             }
                   5414:             return @listing_results;
1.253     stredwic 5415:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5416:             my %allusers;
                   5417:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5418:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5419:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5420: 					 $udom, $tryserver);
1.605     matthew  5421:                     my @listing_results;
                   5422:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5423:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5424: 					  $udom, $tryserver);
1.605     matthew  5425:                         @listing_results = split(/:/,$listing);
                   5426:                     } else {
                   5427:                         @listing_results =
                   5428:                             map { &unescape($_); } split(/:/,$listing);
                   5429:                     }
                   5430:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5431:                         $listing_results[0] ne 'empty'       &&
                   5432:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5433:                         foreach my $line (@listing_results) {
                   5434:                             my ($entry) = split(/&/,$line,2);
                   5435:                             $allusers{$entry} = 1;
1.253     stredwic 5436:                         }
                   5437:                     }
1.191     harris41 5438:                 }
1.253     stredwic 5439:             }
                   5440:             my $alluserstr='';
1.800     albertel 5441:             foreach my $user (sort(keys(%allusers))) {
                   5442:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5443:             }
                   5444:             $alluserstr=~s/:$//;
                   5445:             return split(/:/,$alluserstr);
                   5446:         } else {
1.800     albertel 5447:             return ('missing user name');
1.253     stredwic 5448:         }
                   5449:     } elsif(!defined($alternateDirectoryRoot)) {
                   5450:         my $tryserver;
                   5451:         my %alldom=();
1.800     albertel 5452:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5453:             $alldom{$hostdom{$tryserver}}=1;
                   5454:         }
                   5455:         my $alldomstr='';
1.800     albertel 5456:         foreach my $domain (sort(keys(%alldom))) {
                   5457:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5458:         }
                   5459:         $alldomstr=~s/:$//;
                   5460:         return split(/:/,$alldomstr);       
                   5461:     } else {
1.800     albertel 5462:         return ('missing domain');
1.275     stredwic 5463:     }
                   5464: }
                   5465: 
                   5466: # --------------------------------------------- GetFileTimestamp
                   5467: # This function utilizes dirlist and returns the date stamp for
                   5468: # when it was last modified.  It will also return an error of -1
                   5469: # if an error occurs
                   5470: 
1.410     matthew  5471: ##
                   5472: ## FIXME: This subroutine assumes its caller knows something about the
                   5473: ## directory structure of the home server for the student ($root).
                   5474: ## Not a good assumption to make.  Since this is for looking up files
                   5475: ## in user directories, the full path should be constructed by lond, not
                   5476: ## whatever machine we request data from.
                   5477: ##
1.275     stredwic 5478: sub GetFileTimestamp {
                   5479:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5480:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5481:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5482:     my $subdir=$studentName.'__';
                   5483:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5484:     my $proname="$studentDomain/$subdir/$studentName";
                   5485:     $proname .= '/'.$filename;
1.375     matthew  5486:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5487:                                               $studentName, $root);
1.275     stredwic 5488:     my @stats = split('&', $fileStat);
                   5489:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5490:         # @stats contains first the filename, then the stat output
                   5491:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5492:     } else {
                   5493:         return -1;
1.253     stredwic 5494:     }
1.26      www      5495: }
                   5496: 
1.712     albertel 5497: sub stat_file {
                   5498:     my ($uri) = @_;
1.787     albertel 5499:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5500: 
1.712     albertel 5501:     my ($udom,$uname,$file,$dir);
                   5502:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5503: 	($udom,$uname,$file) =
1.811     albertel 5504: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5505: 	$file = 'userfiles/'.$file;
1.740     www      5506: 	$dir = &propath($udom,$uname);
1.712     albertel 5507:     }
                   5508:     if ($uri =~ m-^/res/-) {
                   5509: 	($udom,$uname) = 
1.807     albertel 5510: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5511: 	$file = $uri;
                   5512:     }
                   5513: 
                   5514:     if (!$udom || !$uname || !$file) {
                   5515: 	# unable to handle the uri
                   5516: 	return ();
                   5517:     }
                   5518: 
                   5519:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5520:     my @stats = split('&', $result);
1.721     banghart 5521:     
1.712     albertel 5522:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5523: 	shift(@stats); #filename is first
                   5524: 	return @stats;
                   5525:     }
                   5526:     return ();
                   5527: }
                   5528: 
1.26      www      5529: # -------------------------------------------------------- Value of a Condition
                   5530: 
1.713     albertel 5531: # gets the value of a specific preevaluated condition
                   5532: #    stored in the string  $env{user.state.<cid>}
                   5533: # or looks up a condition reference in the bighash and if if hasn't
                   5534: # already been evaluated recurses into docondval to get the value of
                   5535: # the condition, then memoizing it to 
                   5536: #   $env{user.state.<cid>.<condition>}
1.40      www      5537: sub directcondval {
                   5538:     my $number=shift;
1.620     albertel 5539:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5540: 	&Apache::lonuserstate::evalstate();
                   5541:     }
1.713     albertel 5542:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5543: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5544:     } elsif ($number =~ /^_/) {
                   5545: 	my $sub_condition;
                   5546: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5547: 		&GDBM_READER(),0640)) {
                   5548: 	    $sub_condition=$bighash{'conditions'.$number};
                   5549: 	    untie(%bighash);
                   5550: 	}
                   5551: 	my $value = &docondval($sub_condition);
                   5552: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5553: 	return $value;
                   5554:     }
1.620     albertel 5555:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5556:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5557:     } else {
                   5558:        return 2;
                   5559:     }
                   5560: }
                   5561: 
1.713     albertel 5562: # get the collection of conditions for this resource
1.26      www      5563: sub condval {
                   5564:     my $condidx=shift;
1.54      www      5565:     my $allpathcond='';
1.713     albertel 5566:     foreach my $cond (split(/\|/,$condidx)) {
                   5567: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5568: 	    $allpathcond.=
                   5569: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5570: 	}
1.191     harris41 5571:     }
1.54      www      5572:     $allpathcond=~s/\|$//;
1.713     albertel 5573:     return &docondval($allpathcond);
                   5574: }
                   5575: 
                   5576: #evaluates an expression of conditions
                   5577: sub docondval {
                   5578:     my ($allpathcond) = @_;
                   5579:     my $result=0;
                   5580:     if ($env{'request.course.id'}
                   5581: 	&& defined($allpathcond)) {
                   5582: 	my $operand='|';
                   5583: 	my @stack;
                   5584: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5585: 	    if ($chunk eq '(') {
                   5586: 		push @stack,($operand,$result);
                   5587: 	    } elsif ($chunk eq ')') {
                   5588: 		my $before=pop @stack;
                   5589: 		if (pop @stack eq '&') {
                   5590: 		    $result=$result>$before?$before:$result;
                   5591: 		} else {
                   5592: 		    $result=$result>$before?$result:$before;
                   5593: 		}
                   5594: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5595: 		$operand=$chunk;
                   5596: 	    } else {
                   5597: 		my $new=directcondval($chunk);
                   5598: 		if ($operand eq '&') {
                   5599: 		    $result=$result>$new?$new:$result;
                   5600: 		} else {
                   5601: 		    $result=$result>$new?$result:$new;
                   5602: 		}
                   5603: 	    }
                   5604: 	}
1.26      www      5605:     }
                   5606:     return $result;
1.421     albertel 5607: }
                   5608: 
                   5609: # ---------------------------------------------------- Devalidate courseresdata
                   5610: 
                   5611: sub devalidatecourseresdata {
                   5612:     my ($coursenum,$coursedomain)=@_;
                   5613:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5614:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5615: }
                   5616: 
1.763     www      5617: 
1.200     www      5618: # --------------------------------------------------- Course Resourcedata Query
                   5619: 
1.624     albertel 5620: sub get_courseresdata {
                   5621:     my ($coursenum,$coursedomain)=@_;
1.200     www      5622:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5623:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5624:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5625:     my %dumpreply;
1.417     albertel 5626:     unless (defined($cached)) {
1.624     albertel 5627: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5628: 	$result=\%dumpreply;
1.251     albertel 5629: 	my ($tmp) = keys(%dumpreply);
                   5630: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5631: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5632: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5633: 	    return $tmp;
1.416     albertel 5634: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5635: 	    $result=undef;
1.599     albertel 5636: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5637: 	}
                   5638:     }
1.624     albertel 5639:     return $result;
                   5640: }
                   5641: 
1.633     albertel 5642: sub devalidateuserresdata {
                   5643:     my ($uname,$udom)=@_;
                   5644:     my $hashid="$udom:$uname";
                   5645:     &devalidate_cache_new('userres',$hashid);
                   5646: }
                   5647: 
1.624     albertel 5648: sub get_userresdata {
                   5649:     my ($uname,$udom)=@_;
                   5650:     #most student don\'t have any data set, check if there is some data
                   5651:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5652: 
                   5653:     my $hashid="$udom:$uname";
                   5654:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5655:     if (!defined($cached)) {
                   5656: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5657: 	$result=\%resourcedata;
                   5658: 	&do_cache_new('userres',$hashid,$result,600);
                   5659:     }
                   5660:     my ($tmp)=keys(%$result);
                   5661:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5662: 	return $result;
                   5663:     }
                   5664:     #error 2 occurs when the .db doesn't exist
                   5665:     if ($tmp!~/error: 2 /) {
1.672     albertel 5666: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5667: 		 " Trying to get resource data for ".
                   5668: 		 $uname." at ".$udom.": ".
                   5669: 		 $tmp."</font>");
                   5670:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5671: 	#&EXT_cache_set($udom,$uname);
                   5672: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5673: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5674:     }
                   5675:     return $tmp;
                   5676: }
                   5677: 
                   5678: sub resdata {
                   5679:     my ($name,$domain,$type,@which)=@_;
                   5680:     my $result;
                   5681:     if ($type eq 'course') {
                   5682: 	$result=&get_courseresdata($name,$domain);
                   5683:     } elsif ($type eq 'user') {
                   5684: 	$result=&get_userresdata($name,$domain);
                   5685:     }
                   5686:     if (!ref($result)) { return $result; }    
1.251     albertel 5687:     foreach my $item (@which) {
1.417     albertel 5688: 	if (defined($result->{$item})) {
                   5689: 	    return $result->{$item};
1.251     albertel 5690: 	}
1.250     albertel 5691:     }
1.291     albertel 5692:     return undef;
1.200     www      5693: }
                   5694: 
1.379     matthew  5695: #
                   5696: # EXT resource caching routines
                   5697: #
                   5698: 
                   5699: sub clear_EXT_cache_status {
1.383     albertel 5700:     &delenv('cache.EXT.');
1.379     matthew  5701: }
                   5702: 
                   5703: sub EXT_cache_status {
                   5704:     my ($target_domain,$target_user) = @_;
1.383     albertel 5705:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5706:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5707:         # We know already the user has no data
                   5708:         return 1;
                   5709:     } else {
                   5710:         return 0;
                   5711:     }
                   5712: }
                   5713: 
                   5714: sub EXT_cache_set {
                   5715:     my ($target_domain,$target_user) = @_;
1.383     albertel 5716:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5717:     #&appenv($cachename => time);
1.379     matthew  5718: }
                   5719: 
1.28      www      5720: # --------------------------------------------------------- Value of a Variable
1.58      www      5721: sub EXT {
1.715     albertel 5722: 
1.395     albertel 5723:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5724:     unless ($varname) { return ''; }
1.218     albertel 5725:     #get real user name/domain, courseid and symb
                   5726:     my $courseid;
1.359     albertel 5727:     my $publicuser;
1.427     www      5728:     if ($symbparm) {
                   5729: 	$symbparm=&get_symb_from_alias($symbparm);
                   5730:     }
1.218     albertel 5731:     if (!($uname && $udom)) {
1.790     albertel 5732:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5733:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5734:     } else {
1.620     albertel 5735: 	$courseid=$env{'request.course.id'};
1.218     albertel 5736:     }
1.48      www      5737:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5738:     my $rest;
1.320     albertel 5739:     if (defined($therest[0])) {
1.48      www      5740:        $rest=join('.',@therest);
                   5741:     } else {
                   5742:        $rest='';
                   5743:     }
1.320     albertel 5744: 
1.57      www      5745:     my $qualifierrest=$qualifier;
                   5746:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5747:     my $spacequalifierrest=$space;
                   5748:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5749:     if ($realm eq 'user') {
1.48      www      5750: # --------------------------------------------------------------- user.resource
                   5751: 	if ($space eq 'resource') {
1.651     albertel 5752: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5753: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5754: 		 &&
1.744     albertel 5755: 		 ($symbparm eq &symbread()) ) {	
                   5756: 		# if we are in the middle of processing the resource the
                   5757: 		# get the value we are planning on committing
                   5758:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5759:                     return $Apache::lonhomework::results{$qualifierrest};
                   5760:                 } else {
                   5761:                     return $Apache::lonhomework::history{$qualifierrest};
                   5762:                 }
1.335     albertel 5763: 	    } else {
1.359     albertel 5764: 		my %restored;
1.620     albertel 5765: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5766: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5767: 		} else {
                   5768: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5769: 		}
1.335     albertel 5770: 		return $restored{$qualifierrest};
                   5771: 	    }
1.48      www      5772: # ----------------------------------------------------------------- user.access
                   5773:         } elsif ($space eq 'access') {
1.218     albertel 5774: 	    # FIXME - not supporting calls for a specific user
1.48      www      5775:             return &allowed($qualifier,$rest);
                   5776: # ------------------------------------------ user.preferences, user.environment
                   5777:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5778: 	    if (($uname eq $env{'user.name'}) &&
                   5779: 		($udom eq $env{'user.domain'})) {
                   5780: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5781: 	    } else {
1.359     albertel 5782: 		my %returnhash;
                   5783: 		if (!$publicuser) {
                   5784: 		    %returnhash=&userenvironment($udom,$uname,
                   5785: 						 $qualifierrest);
                   5786: 		}
1.218     albertel 5787: 		return $returnhash{$qualifierrest};
                   5788: 	    }
1.48      www      5789: # ----------------------------------------------------------------- user.course
                   5790:         } elsif ($space eq 'course') {
1.218     albertel 5791: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5792:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5793: # ------------------------------------------------------------------- user.role
                   5794:         } elsif ($space eq 'role') {
1.218     albertel 5795: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5796:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5797:             if ($qualifier eq 'value') {
                   5798: 		return $role;
                   5799:             } elsif ($qualifier eq 'extent') {
                   5800:                 return $where;
                   5801:             }
                   5802: # ----------------------------------------------------------------- user.domain
                   5803:         } elsif ($space eq 'domain') {
1.218     albertel 5804:             return $udom;
1.48      www      5805: # ------------------------------------------------------------------- user.name
                   5806:         } elsif ($space eq 'name') {
1.218     albertel 5807:             return $uname;
1.48      www      5808: # ---------------------------------------------------- Any other user namespace
1.29      www      5809:         } else {
1.359     albertel 5810: 	    my %reply;
                   5811: 	    if (!$publicuser) {
                   5812: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5813: 	    }
                   5814: 	    return $reply{$qualifierrest};
1.48      www      5815:         }
1.236     www      5816:     } elsif ($realm eq 'query') {
                   5817: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5818:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5819: 						[$spacequalifierrest]);
1.620     albertel 5820: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5821:    } elsif ($realm eq 'request') {
1.48      www      5822: # ------------------------------------------------------------- request.browser
                   5823:         if ($space eq 'browser') {
1.430     www      5824: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5825: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5826: 		    return 1;
                   5827: 		} else {
                   5828: 		    return 0;
                   5829: 		}
                   5830: 	    } else {
1.620     albertel 5831: 		return $env{'browser.'.$qualifier};
1.430     www      5832: 	    }
1.57      www      5833: # ------------------------------------------------------------ request.filename
                   5834:         } else {
1.620     albertel 5835:             return $env{'request.'.$spacequalifierrest};
1.29      www      5836:         }
1.28      www      5837:     } elsif ($realm eq 'course') {
1.48      www      5838: # ---------------------------------------------------------- course.description
1.620     albertel 5839:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5840:     } elsif ($realm eq 'resource') {
1.165     www      5841: 
1.620     albertel 5842: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5843: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5844: 	}
1.693     albertel 5845: 
                   5846: 	if ($space eq 'title') {
                   5847: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5848: 	    return &gettitle($symbparm);
                   5849: 	}
                   5850: 	
                   5851: 	if ($space eq 'map') {
                   5852: 	    my ($map) = &decode_symb($symbparm);
                   5853: 	    return &symbread($map);
                   5854: 	}
                   5855: 
                   5856: 	my ($section, $group, @groups);
1.593     albertel 5857: 	my ($courselevelm,$courselevel);
1.539     albertel 5858: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5859: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5860: 
1.218     albertel 5861: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5862: 
1.60      www      5863: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5864: 	    my $symbp=$symbparm;
1.735     albertel 5865: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5866: 
                   5867: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5868: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5869: 
1.620     albertel 5870: 	    if (($env{'user.name'} eq $uname) &&
                   5871: 		($env{'user.domain'} eq $udom)) {
                   5872: 		$section=$env{'request.course.sec'};
1.733     raeburn  5873:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5874:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5875: 	    } else {
1.539     albertel 5876: 		if (! defined($usection)) {
1.551     albertel 5877: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5878: 		} else {
                   5879: 		    $section = $usection;
                   5880: 		}
1.733     raeburn  5881:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5882: 	    }
                   5883: 
                   5884: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5885: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5886: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5887: 
1.593     albertel 5888: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5889: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5890: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5891: 
1.60      www      5892: # ----------------------------------------------------------- first, check user
1.624     albertel 5893: 
                   5894: 	    my $userreply=&resdata($uname,$udom,'user',
                   5895: 				       ($courselevelr,$courselevelm,
                   5896: 					$courselevel));
                   5897: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5898: 
1.594     albertel 5899: # ------------------------------------------------ second, check some of course
1.684     raeburn  5900:             my $coursereply;
1.691     raeburn  5901:             if (@groups > 0) {
                   5902:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5903:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5904:                 if (defined($coursereply)) { return $coursereply; }
                   5905:             }
1.96      www      5906: 
1.684     raeburn  5907: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5908: 				     $env{'course.'.$courseid.'.domain'},
                   5909: 				     'course',
                   5910: 				     ($seclevelr,$seclevelm,$seclevel,
                   5911: 				      $courselevelr));
1.287     albertel 5912: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5913: 
1.60      www      5914: # ------------------------------------------------------ third, check map parms
1.218     albertel 5915: 	    my %parmhash=();
                   5916: 	    my $thisparm='';
                   5917: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5918: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5919: 		    &GDBM_READER(),0640)) {
1.218     albertel 5920: 		$thisparm=$parmhash{$symbparm};
                   5921: 		untie(%parmhash);
                   5922: 	    }
                   5923: 	    if ($thisparm) { return $thisparm; }
                   5924: 	}
1.594     albertel 5925: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5926: 
1.218     albertel 5927: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5928: 	my $filename;
                   5929: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5930: 	if ($symbparm) {
1.409     www      5931: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5932: 	} else {
1.620     albertel 5933: 	    $filename=$env{'request.filename'};
1.282     albertel 5934: 	}
                   5935: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5936: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5937: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5938: 	if (defined($metadata)) { return $metadata; }
1.142     www      5939: 
1.594     albertel 5940: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5941: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5942: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5943: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5944: 				     $env{'course.'.$courseid.'.domain'},
                   5945: 				     'course',
                   5946: 				     ($courselevelm,$courselevel));
1.593     albertel 5947: 	    if (defined($coursereply)) { return $coursereply; }
                   5948: 	}
1.145     www      5949: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5950: 	unless ($space eq '0') {
1.336     albertel 5951: 	    my @parts=split(/_/,$space);
                   5952: 	    my $id=pop(@parts);
                   5953: 	    my $part=join('_',@parts);
                   5954: 	    if ($part eq '') { $part='0'; }
                   5955: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5956: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5957: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5958: 	}
1.395     albertel 5959: 	if ($recurse) { return undef; }
                   5960: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5961: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5962: 
1.48      www      5963: # ---------------------------------------------------- Any other user namespace
                   5964:     } elsif ($realm eq 'environment') {
                   5965: # ----------------------------------------------------------------- environment
1.620     albertel 5966: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5967: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5968: 	} else {
1.770     albertel 5969: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5970: 		return '';
                   5971: 	    }
1.219     albertel 5972: 	    my %returnhash=&userenvironment($udom,$uname,
                   5973: 					    $spacequalifierrest);
                   5974: 	    return $returnhash{$spacequalifierrest};
                   5975: 	}
1.28      www      5976:     } elsif ($realm eq 'system') {
1.48      www      5977: # ----------------------------------------------------------------- system.time
                   5978: 	if ($space eq 'time') {
                   5979: 	    return time;
                   5980:         }
1.696     albertel 5981:     } elsif ($realm eq 'server') {
                   5982: # ----------------------------------------------------------------- system.time
                   5983: 	if ($space eq 'name') {
                   5984: 	    return $ENV{'SERVER_NAME'};
                   5985:         }
1.28      www      5986:     }
1.48      www      5987:     return '';
1.61      www      5988: }
                   5989: 
1.691     raeburn  5990: sub check_group_parms {
                   5991:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5992:     my @groupitems = ();
                   5993:     my $resultitem;
                   5994:     my @levels = ($symbparm,$mapparm,$what);
                   5995:     foreach my $group (@{$groups}) {
                   5996:         foreach my $level (@levels) {
                   5997:              my $item = $courseid.'.['.$group.'].'.$level;
                   5998:              push(@groupitems,$item);
                   5999:         }
                   6000:     }
                   6001:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6002:                             $env{'course.'.$courseid.'.domain'},
                   6003:                                      'course',@groupitems);
                   6004:     return $coursereply;
                   6005: }
                   6006: 
                   6007: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6008:     my ($courseid,@groups) = @_;
                   6009:     @groups = sort(@groups);
1.691     raeburn  6010:     return @groups;
                   6011: }
                   6012: 
1.395     albertel 6013: sub packages_tab_default {
                   6014:     my ($uri,$varname)=@_;
                   6015:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6016: 
                   6017:     my (@extension,@specifics,$do_default);
                   6018:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6019: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6020: 	if ($pack_type eq 'default') {
                   6021: 	    $do_default=1;
                   6022: 	} elsif ($pack_type eq 'extension') {
                   6023: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6024: 	} else {
                   6025: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6026: 	}
                   6027:     }
                   6028:     # first look for a package that matches the requested part id
                   6029:     foreach my $package (@specifics) {
                   6030: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6031: 	next if ($pack_part ne $part);
                   6032: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6033: 	    return $packagetab{"$pack_type&$name&default"};
                   6034: 	}
                   6035:     }
                   6036:     # look for any possible matching non extension_ package
                   6037:     foreach my $package (@specifics) {
                   6038: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6039: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6040: 	    return $packagetab{"$pack_type&$name&default"};
                   6041: 	}
1.585     albertel 6042: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6043: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6044: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6045: 	}
                   6046:     }
1.738     albertel 6047:     # look for any posible extension_ match
                   6048:     foreach my $package (@extension) {
                   6049: 	my ($package,$pack_type)=@{$package};
                   6050: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6051: 	    return $packagetab{"$pack_type&$name&default"};
                   6052: 	}
                   6053: 	if (defined($packagetab{$package."&$name&default"})) {
                   6054: 	    return $packagetab{$package."&$name&default"};
                   6055: 	}
                   6056:     }
                   6057:     # look for a global default setting
                   6058:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6059: 	return $packagetab{"default&$name&default"};
                   6060:     }
1.395     albertel 6061:     return undef;
                   6062: }
                   6063: 
1.334     albertel 6064: sub add_prefix_and_part {
                   6065:     my ($prefix,$part)=@_;
                   6066:     my $keyroot;
                   6067:     if (defined($prefix) && $prefix !~ /^__/) {
                   6068: 	# prefix that has a part already
                   6069: 	$keyroot=$prefix;
                   6070:     } elsif (defined($prefix)) {
                   6071: 	# prefix that is missing a part
                   6072: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6073:     } else {
                   6074: 	# no prefix at all
                   6075: 	if (defined($part)) { $keyroot='_'.$part; }
                   6076:     }
                   6077:     return $keyroot;
                   6078: }
                   6079: 
1.71      www      6080: # ---------------------------------------------------------------- Get metadata
                   6081: 
1.599     albertel 6082: my %metaentry;
1.71      www      6083: sub metadata {
1.176     www      6084:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6085:     $uri=&declutter($uri);
1.288     albertel 6086:     # if it is a non metadata possible uri return quickly
1.529     albertel 6087:     if (($uri eq '') || 
                   6088: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6089: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6090:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6091: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6092: 	return undef;
1.288     albertel 6093:     }
1.73      www      6094:     my $filename=$uri;
                   6095:     $uri=~s/\.meta$//;
1.172     www      6096: #
                   6097: # Is the metadata already cached?
1.177     www      6098: # Look at timestamp of caching
1.172     www      6099: # Everything is cached by the main uri, libraries are never directly cached
                   6100: #
1.428     albertel 6101:     if (!defined($liburi)) {
1.599     albertel 6102: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6103: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6104:     }
                   6105:     {
1.172     www      6106: #
                   6107: # Is this a recursive call for a library?
                   6108: #
1.599     albertel 6109: #	if (! exists($metacache{$uri})) {
                   6110: #	    $metacache{$uri}={};
                   6111: #	}
1.171     www      6112:         if ($liburi) {
                   6113: 	    $liburi=&declutter($liburi);
                   6114:             $filename=$liburi;
1.401     bowersj2 6115:         } else {
1.599     albertel 6116: 	    &devalidate_cache_new('meta',$uri);
                   6117: 	    undef(%metaentry);
1.401     bowersj2 6118: 	}
1.140     www      6119:         my %metathesekeys=();
1.73      www      6120:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6121: 	my $metastring;
1.768     albertel 6122: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6123: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6124: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6125: 	    $metastring=&getfile($file);
1.489     albertel 6126: 	}
1.208     albertel 6127:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6128:         my $token;
1.140     www      6129:         undef %metathesekeys;
1.71      www      6130:         while ($token=$parser->get_token) {
1.339     albertel 6131: 	    if ($token->[0] eq 'S') {
                   6132: 		if (defined($token->[2]->{'package'})) {
1.172     www      6133: #
                   6134: # This is a package - get package info
                   6135: #
1.339     albertel 6136: 		    my $package=$token->[2]->{'package'};
                   6137: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6138: 		    if (defined($token->[2]->{'id'})) { 
                   6139: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6140: 		    }
1.599     albertel 6141: 		    if ($metaentry{':packages'}) {
                   6142: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6143: 		    } else {
1.599     albertel 6144: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6145: 		    }
1.736     albertel 6146: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6147: 			my $part=$keyroot;
                   6148: 			$part=~s/^\_//;
1.736     albertel 6149: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6150: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6151: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6152: 			    # ignore package.tab specified default values
                   6153:                             # here &package_tab_default() will fetch those
                   6154: 			    if ($subp eq 'default') { next; }
1.736     albertel 6155: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6156: 			    my $unikey;
                   6157: 			    if ($pack =~ /_0$/) {
                   6158: 				$unikey='parameter_0_'.$name;
                   6159: 				$part=0;
                   6160: 			    } else {
                   6161: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6162: 			    }
1.339     albertel 6163: 			    if ($subp eq 'display') {
                   6164: 				$value.=' [Part: '.$part.']';
                   6165: 			    }
1.599     albertel 6166: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6167: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6168: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6169: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6170: 			    }
1.599     albertel 6171: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6172: 				$metaentry{':'.$unikey}=
                   6173: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6174: 			    }
1.339     albertel 6175: 			}
                   6176: 		    }
                   6177: 		} else {
1.172     www      6178: #
                   6179: # This is not a package - some other kind of start tag
1.339     albertel 6180: #
                   6181: 		    my $entry=$token->[1];
                   6182: 		    my $unikey;
                   6183: 		    if ($entry eq 'import') {
                   6184: 			$unikey='';
                   6185: 		    } else {
                   6186: 			$unikey=$entry;
                   6187: 		    }
                   6188: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6189: 
                   6190: 		    if (defined($token->[2]->{'id'})) { 
                   6191: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6192: 		    }
1.175     www      6193: 
1.339     albertel 6194: 		    if ($entry eq 'import') {
1.175     www      6195: #
                   6196: # Importing a library here
1.339     albertel 6197: #
                   6198: 			if ($depthcount<20) {
                   6199: 			    my $location=$parser->get_text('/import');
                   6200: 			    my $dir=$filename;
                   6201: 			    $dir=~s|[^/]*$||;
                   6202: 			    $location=&filelocation($dir,$location);
1.736     albertel 6203: 			    my $metadata = 
                   6204: 				&metadata($uri,'keys', $location,$unikey,
                   6205: 					  $depthcount+1);
                   6206: 			    foreach my $meta (split(',',$metadata)) {
                   6207: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6208: 				$metathesekeys{$meta}=1;
1.339     albertel 6209: 			    }
                   6210: 			}
                   6211: 		    } else { 
                   6212: 			
                   6213: 			if (defined($token->[2]->{'name'})) { 
                   6214: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6215: 			}
                   6216: 			$metathesekeys{$unikey}=1;
1.736     albertel 6217: 			foreach my $param (@{$token->[3]}) {
                   6218: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6219: 				$token->[2]->{$param};
1.339     albertel 6220: 			}
                   6221: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6222: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6223: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6224: 		 # only ws inside the tag, and not in default, so use default
                   6225: 		 # as value
1.599     albertel 6226: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6227: 			} else {
1.321     albertel 6228: 		  # either something interesting inside the tag or default
                   6229:                   # uninteresting
1.599     albertel 6230: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6231: 			}
1.172     www      6232: # end of not-a-package not-a-library import
1.339     albertel 6233: 		    }
1.172     www      6234: # end of not-a-package start tag
1.339     albertel 6235: 		}
1.172     www      6236: # the next is the end of "start tag"
1.339     albertel 6237: 	    }
                   6238: 	}
1.483     albertel 6239: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6240: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6241: 	    #no specific packages #how's our extension
                   6242: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6243: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6244: 					 \%metathesekeys);
                   6245: 	}
1.599     albertel 6246: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6247: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6248: 		#no specific packages well let's get default then
                   6249: 		if ($key!~/^default&/) { next; }
1.488     albertel 6250: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6251: 					     \%metathesekeys);
                   6252: 	    }
                   6253: 	}
1.338     www      6254: # are there custom rights to evaluate
1.599     albertel 6255: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6256: 
1.338     www      6257:     #
                   6258:     # Importing a rights file here
1.339     albertel 6259:     #
                   6260: 	    unless ($depthcount) {
1.599     albertel 6261: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6262: 		my $dir=$filename;
                   6263: 		$dir=~s|[^/]*$||;
                   6264: 		$location=&filelocation($dir,$location);
1.736     albertel 6265: 		my $rights_metadata =
                   6266: 		    &metadata($uri,'keys',$location,'_rights',
                   6267: 			      $depthcount+1);
                   6268: 		foreach my $rights (split(',',$rights_metadata)) {
                   6269: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6270: 		    $metathesekeys{$rights}=1;
1.339     albertel 6271: 		}
                   6272: 	    }
                   6273: 	}
1.737     albertel 6274: 	# uniqifiy package listing
                   6275: 	my %seen;
                   6276: 	my @uniq_packages =
                   6277: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6278: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6279: 
                   6280: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6281: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6282: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6283: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6284: # this is the end of "was not already recently cached
1.71      www      6285:     }
1.599     albertel 6286:     return $metaentry{':'.$what};
1.261     albertel 6287: }
                   6288: 
1.488     albertel 6289: sub metadata_create_package_def {
1.483     albertel 6290:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6291:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6292:     if ($subp eq 'default') { next; }
                   6293:     
1.599     albertel 6294:     if (defined($metaentry{':packages'})) {
                   6295: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6296:     } else {
1.599     albertel 6297: 	$metaentry{':packages'}=$package;
1.483     albertel 6298:     }
                   6299:     my $value=$packagetab{$key};
                   6300:     my $unikey;
                   6301:     $unikey='parameter_0_'.$name;
1.599     albertel 6302:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6303:     $$metathesekeys{$unikey}=1;
1.599     albertel 6304:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6305: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6306:     }
1.599     albertel 6307:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6308: 	$metaentry{':'.$unikey}=
                   6309: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6310:     }
                   6311: }
                   6312: 
1.261     albertel 6313: sub metadata_generate_part0 {
                   6314:     my ($metadata,$metacache,$uri) = @_;
                   6315:     my %allnames;
1.737     albertel 6316:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6317: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6318: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6319: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6320: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6321: 	    $allnames{$name}=$part;
                   6322: 	  }
                   6323: 	}
                   6324:     }
                   6325:     foreach my $name (keys(%allnames)) {
                   6326:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6327:       my $key=":parameter_0_$name";
1.261     albertel 6328:       $$metacache{"$key.part"}='0';
                   6329:       $$metacache{"$key.name"}=$name;
1.428     albertel 6330:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6331: 					   $allnames{$name}.'_'.$name.
                   6332: 					   '.type'};
1.428     albertel 6333:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6334: 			     '.display'};
1.644     www      6335:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6336:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6337:       $$metacache{"$key.display"}=$olddis;
                   6338:     }
1.71      www      6339: }
                   6340: 
1.764     albertel 6341: # ------------------------------------------------------ Devalidate title cache
                   6342: 
                   6343: sub devalidate_title_cache {
                   6344:     my ($url)=@_;
                   6345:     if (!$env{'request.course.id'}) { return; }
                   6346:     my $symb=&symbread($url);
                   6347:     if (!$symb) { return; }
                   6348:     my $key=$env{'request.course.id'}."\0".$symb;
                   6349:     &devalidate_cache_new('title',$key);
                   6350: }
                   6351: 
1.301     www      6352: # ------------------------------------------------- Get the title of a resource
                   6353: 
                   6354: sub gettitle {
                   6355:     my $urlsymb=shift;
                   6356:     my $symb=&symbread($urlsymb);
1.534     albertel 6357:     if ($symb) {
1.620     albertel 6358: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6359: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6360: 	if (defined($cached)) { 
                   6361: 	    return $result;
                   6362: 	}
1.534     albertel 6363: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6364: 	my $title='';
                   6365: 	my %bighash;
1.620     albertel 6366: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6367: 		&GDBM_READER(),0640)) {
                   6368: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6369: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6370: 	    untie %bighash;
                   6371: 	}
                   6372: 	$title=~s/\&colon\;/\:/gs;
                   6373: 	if ($title) {
1.599     albertel 6374: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6375: 	}
                   6376: 	$urlsymb=$url;
                   6377:     }
                   6378:     my $title=&metadata($urlsymb,'title');
                   6379:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6380:     return $title;
1.301     www      6381: }
1.613     albertel 6382: 
1.614     albertel 6383: sub get_slot {
                   6384:     my ($which,$cnum,$cdom)=@_;
                   6385:     if (!$cnum || !$cdom) {
1.790     albertel 6386: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6387: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6388: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6389:     }
1.703     albertel 6390:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6391:     my %slotinfo;
                   6392:     if (exists($remembered{$key})) {
                   6393: 	$slotinfo{$which} = $remembered{$key};
                   6394:     } else {
                   6395: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6396: 	&Apache::lonhomework::showhash(%slotinfo);
                   6397: 	my ($tmp)=keys(%slotinfo);
                   6398: 	if ($tmp=~/^error:/) { return (); }
                   6399: 	$remembered{$key} = $slotinfo{$which};
                   6400:     }
1.616     albertel 6401:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6402: 	return %{$slotinfo{$which}};
                   6403:     }
                   6404:     return $slotinfo{$which};
1.614     albertel 6405: }
1.31      www      6406: # ------------------------------------------------- Update symbolic store links
                   6407: 
                   6408: sub symblist {
                   6409:     my ($mapname,%newhash)=@_;
1.438     www      6410:     $mapname=&deversion(&declutter($mapname));
1.31      www      6411:     my %hash;
1.620     albertel 6412:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6413:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6414:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6415: 	    foreach my $url (keys %newhash) {
                   6416: 		next if ($url eq 'last_known'
                   6417: 			 && $env{'form.no_update_last_known'});
                   6418: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6419: 						    $newhash{$url}->[1],
                   6420: 						    $newhash{$url}->[0]);
1.191     harris41 6421:             }
1.31      www      6422:             if (untie(%hash)) {
                   6423: 		return 'ok';
                   6424:             }
                   6425:         }
                   6426:     }
                   6427:     return 'error';
1.212     www      6428: }
                   6429: 
                   6430: # --------------------------------------------------------------- Verify a symb
                   6431: 
                   6432: sub symbverify {
1.510     www      6433:     my ($symb,$thisurl)=@_;
                   6434:     my $thisfn=$thisurl;
1.439     www      6435:     $thisfn=&declutter($thisfn);
1.215     www      6436: # direct jump to resource in page or to a sequence - will construct own symbs
                   6437:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6438: # check URL part
1.409     www      6439:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6440: 
1.431     www      6441:     unless ($url eq $thisfn) { return 0; }
1.213     www      6442: 
1.216     www      6443:     $symb=&symbclean($symb);
1.510     www      6444:     $thisurl=&deversion($thisurl);
1.439     www      6445:     $thisfn=&deversion($thisfn);
1.213     www      6446: 
                   6447:     my %bighash;
                   6448:     my $okay=0;
1.431     www      6449: 
1.620     albertel 6450:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6451:                             &GDBM_READER(),0640)) {
1.510     www      6452:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6453:         unless ($ids) { 
1.510     www      6454:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6455:         }
                   6456:         if ($ids) {
                   6457: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6458: 	    foreach my $id (split(/\,/,$ids)) {
                   6459: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6460:                if (
                   6461:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6462:    eq $symb) { 
1.620     albertel 6463: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6464: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6465: 		       $okay=1; 
                   6466: 		   }
                   6467: 	       }
1.216     www      6468: 	   }
                   6469:         }
1.213     www      6470: 	untie(%bighash);
                   6471:     }
                   6472:     return $okay;
1.31      www      6473: }
                   6474: 
1.210     www      6475: # --------------------------------------------------------------- Clean-up symb
                   6476: 
                   6477: sub symbclean {
                   6478:     my $symb=shift;
1.568     albertel 6479:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6480: # remove version from map
                   6481:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6482: 
1.210     www      6483: # remove version from URL
                   6484:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6485: 
1.507     www      6486: # remove wrapper
                   6487: 
1.510     www      6488:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6489:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6490:     return $symb;
1.409     www      6491: }
                   6492: 
                   6493: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6494: 
                   6495: sub encode_symb {
                   6496:     my ($map,$resid,$url)=@_;
                   6497:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6498: }
1.409     www      6499: 
                   6500: sub decode_symb {
1.568     albertel 6501:     my $symb=shift;
                   6502:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6503:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6504:     return (&fixversion($map),$resid,&fixversion($url));
                   6505: }
                   6506: 
                   6507: sub fixversion {
                   6508:     my $fn=shift;
1.609     banghart 6509:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6510:     my %bighash;
                   6511:     my $uri=&clutter($fn);
1.620     albertel 6512:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6513: # is this cached?
1.599     albertel 6514:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6515:     if (defined($cached)) { return $result; }
                   6516: # unfortunately not cached, or expired
1.620     albertel 6517:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6518: 	    &GDBM_READER(),0640)) {
                   6519:  	if ($bighash{'version_'.$uri}) {
                   6520:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6521:  	    unless (($version eq 'mostrecent') || 
                   6522: 		    ($version==&getversion($uri))) {
1.440     www      6523:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6524:  	    }
                   6525:  	}
                   6526:  	untie %bighash;
1.413     www      6527:     }
1.599     albertel 6528:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6529: }
                   6530: 
                   6531: sub deversion {
                   6532:     my $url=shift;
                   6533:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6534:     return $url;
1.210     www      6535: }
                   6536: 
1.31      www      6537: # ------------------------------------------------------ Return symb list entry
                   6538: 
                   6539: sub symbread {
1.249     www      6540:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6541:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6542:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6543: # no filename provided? try from environment
1.44      www      6544:     unless ($thisfn) {
1.620     albertel 6545:         if ($env{'request.symb'}) {
                   6546: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6547: 	}
1.620     albertel 6548: 	$thisfn=$env{'request.filename'};
1.44      www      6549:     }
1.569     albertel 6550:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6551: # is that filename actually a symb? Verify, clean, and return
                   6552:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6553: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6554: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6555: 	}
1.242     www      6556:     }
1.44      www      6557:     $thisfn=declutter($thisfn);
1.31      www      6558:     my %hash;
1.37      www      6559:     my %bighash;
                   6560:     my $syval='';
1.620     albertel 6561:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6562:         my $targetfn = $thisfn;
1.609     banghart 6563:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6564:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6565:         }
1.687     albertel 6566: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6567: 	    $targetfn=$1;
                   6568: 	}
1.620     albertel 6569:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6570:                       &GDBM_READER(),0640)) {
1.481     raeburn  6571: 	    $syval=$hash{$targetfn};
1.37      www      6572:             untie(%hash);
                   6573:         }
                   6574: # ---------------------------------------------------------- There was an entry
                   6575:         if ($syval) {
1.601     albertel 6576: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6577: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6578: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6579: 		    #return $env{$cache_str}='';
1.601     albertel 6580: 		#}    
                   6581: 		#$syval.=$1;
                   6582: 	    #}
1.37      www      6583:         } else {
                   6584: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6585:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6586:                             &GDBM_READER(),0640)) {
1.37      www      6587: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6588:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6589:               unless ($ids) { 
                   6590:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6591:               }
                   6592:               unless ($ids) {
                   6593: # alias?
                   6594: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6595:               }
1.37      www      6596:               if ($ids) {
                   6597: # ------------------------------------------------------------------- Has ID(s)
                   6598:                  my @possibilities=split(/\,/,$ids);
1.39      www      6599:                  if ($#possibilities==0) {
                   6600: # ----------------------------------------------- There is only one possibility
1.37      www      6601: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6602: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6603: 						    $resid,$thisfn);
1.249     www      6604:                  } elsif (!$donotrecurse) {
1.39      www      6605: # ------------------------------------------ There is more than one possibility
                   6606:                      my $realpossible=0;
1.800     albertel 6607:                      foreach my $id (@possibilities) {
                   6608: 			 my $file=$bighash{'src_'.$id};
1.39      www      6609:                          if (&allowed('bre',$file)) {
1.800     albertel 6610:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6611:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6612: 				$realpossible++;
1.626     albertel 6613:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6614: 						    $resid,$thisfn);
1.39      www      6615:                             }
                   6616: 			 }
1.191     harris41 6617:                      }
1.39      www      6618: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6619:                  } else {
                   6620:                      $syval='';
1.37      www      6621:                  }
                   6622: 	      }
                   6623:               untie(%bighash)
1.481     raeburn  6624:            }
1.31      www      6625:         }
1.62      www      6626:         if ($syval) {
1.620     albertel 6627: 	    return $env{$cache_str}=$syval;
1.62      www      6628:         }
1.31      www      6629:     }
1.44      www      6630:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6631:     return $env{$cache_str}='';
1.31      www      6632: }
                   6633: 
                   6634: # ---------------------------------------------------------- Return random seed
                   6635: 
1.32      www      6636: sub numval {
                   6637:     my $txt=shift;
                   6638:     $txt=~tr/A-J/0-9/;
                   6639:     $txt=~tr/a-j/0-9/;
                   6640:     $txt=~tr/K-T/0-9/;
                   6641:     $txt=~tr/k-t/0-9/;
                   6642:     $txt=~tr/U-Z/0-5/;
                   6643:     $txt=~tr/u-z/0-5/;
                   6644:     $txt=~s/\D//g;
1.564     albertel 6645:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6646:     return int($txt);
1.368     albertel 6647: }
                   6648: 
1.484     albertel 6649: sub numval2 {
                   6650:     my $txt=shift;
                   6651:     $txt=~tr/A-J/0-9/;
                   6652:     $txt=~tr/a-j/0-9/;
                   6653:     $txt=~tr/K-T/0-9/;
                   6654:     $txt=~tr/k-t/0-9/;
                   6655:     $txt=~tr/U-Z/0-5/;
                   6656:     $txt=~tr/u-z/0-5/;
                   6657:     $txt=~s/\D//g;
                   6658:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6659:     my $total;
                   6660:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6661:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6662:     return int($total);
                   6663: }
                   6664: 
1.575     albertel 6665: sub numval3 {
                   6666:     use integer;
                   6667:     my $txt=shift;
                   6668:     $txt=~tr/A-J/0-9/;
                   6669:     $txt=~tr/a-j/0-9/;
                   6670:     $txt=~tr/K-T/0-9/;
                   6671:     $txt=~tr/k-t/0-9/;
                   6672:     $txt=~tr/U-Z/0-5/;
                   6673:     $txt=~tr/u-z/0-5/;
                   6674:     $txt=~s/\D//g;
                   6675:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6676:     my $total;
                   6677:     foreach my $val (@txts) { $total+=$val; }
                   6678:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6679:     return $total;
                   6680: }
                   6681: 
1.675     albertel 6682: sub digest {
                   6683:     my ($data)=@_;
                   6684:     my $digest=&Digest::MD5::md5($data);
                   6685:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6686:     my ($e,$f);
                   6687:     {
                   6688:         use integer;
                   6689:         $e=($a+$b);
                   6690:         $f=($c+$d);
                   6691:         if ($_64bit) {
                   6692:             $e=(($e<<32)>>32);
                   6693:             $f=(($f<<32)>>32);
                   6694:         }
                   6695:     }
                   6696:     if (wantarray) {
                   6697: 	return ($e,$f);
                   6698:     } else {
                   6699: 	my $g;
                   6700: 	{
                   6701: 	    use integer;
                   6702: 	    $g=($e+$f);
                   6703: 	    if ($_64bit) {
                   6704: 		$g=(($g<<32)>>32);
                   6705: 	    }
                   6706: 	}
                   6707: 	return $g;
                   6708:     }
                   6709: }
                   6710: 
1.368     albertel 6711: sub latest_rnd_algorithm_id {
1.675     albertel 6712:     return '64bit5';
1.366     albertel 6713: }
1.32      www      6714: 
1.503     albertel 6715: sub get_rand_alg {
                   6716:     my ($courseid)=@_;
1.790     albertel 6717:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6718:     if ($courseid) {
1.620     albertel 6719: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6720:     }
                   6721:     return &latest_rnd_algorithm_id();
                   6722: }
                   6723: 
1.562     albertel 6724: sub validCODE {
                   6725:     my ($CODE)=@_;
                   6726:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6727:     return 0;
                   6728: }
                   6729: 
1.491     albertel 6730: sub getCODE {
1.620     albertel 6731:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6732:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6733: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6734: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6735: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6736:     }
                   6737:     return undef;
                   6738: }
                   6739: 
1.31      www      6740: sub rndseed {
1.155     albertel 6741:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6742: 
1.790     albertel 6743:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6744:     if (!$symb) {
1.366     albertel 6745: 	unless ($symb=$wsymb) { return time; }
                   6746:     }
                   6747:     if (!$courseid) { $courseid=$wcourseid; }
                   6748:     if (!$domain) { $domain=$wdomain; }
                   6749:     if (!$username) { $username=$wusername }
1.503     albertel 6750:     my $which=&get_rand_alg();
1.803     albertel 6751: 
1.491     albertel 6752:     if (defined(&getCODE())) {
1.675     albertel 6753: 	if ($which eq '64bit5') {
                   6754: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6755: 	} elsif ($which eq '64bit4') {
1.575     albertel 6756: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6757: 	} else {
                   6758: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6759: 	}
1.675     albertel 6760:     } elsif ($which eq '64bit5') {
                   6761: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6762:     } elsif ($which eq '64bit4') {
                   6763: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6764:     } elsif ($which eq '64bit3') {
                   6765: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6766:     } elsif ($which eq '64bit2') {
                   6767: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6768:     } elsif ($which eq '64bit') {
                   6769: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6770:     }
                   6771:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6772: }
                   6773: 
                   6774: sub rndseed_32bit {
                   6775:     my ($symb,$courseid,$domain,$username)=@_;
                   6776:     {
                   6777: 	use integer;
                   6778: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6779: 	my $symbseed=numval($symb) << 22;
                   6780: 	my $namechck=unpack("%32C*",$username) << 17;
                   6781: 	my $nameseed=numval($username) << 12;
                   6782: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6783: 	my $courseseed=unpack("%32C*",$courseid);
                   6784: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6785: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6786: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6787: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6788: 	return $num;
                   6789:     }
                   6790: }
                   6791: 
                   6792: sub rndseed_64bit {
                   6793:     my ($symb,$courseid,$domain,$username)=@_;
                   6794:     {
                   6795: 	use integer;
                   6796: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6797: 	my $symbseed=numval($symb) << 10;
                   6798: 	my $namechck=unpack("%32S*",$username);
                   6799: 	
                   6800: 	my $nameseed=numval($username) << 21;
                   6801: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6802: 	my $courseseed=unpack("%32S*",$courseid);
                   6803: 	
                   6804: 	my $num1=$symbchck+$symbseed+$namechck;
                   6805: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6806: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6807: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6808: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6809: 	return "$num1,$num2";
1.155     albertel 6810:     }
1.366     albertel 6811: }
                   6812: 
1.443     albertel 6813: sub rndseed_64bit2 {
                   6814:     my ($symb,$courseid,$domain,$username)=@_;
                   6815:     {
                   6816: 	use integer;
                   6817: 	# strings need to be an even # of cahracters long, it it is odd the
                   6818:         # last characters gets thrown away
                   6819: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6820: 	my $symbseed=numval($symb) << 10;
                   6821: 	my $namechck=unpack("%32S*",$username.' ');
                   6822: 	
                   6823: 	my $nameseed=numval($username) << 21;
1.501     albertel 6824: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6825: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6826: 	
                   6827: 	my $num1=$symbchck+$symbseed+$namechck;
                   6828: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6829: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6830: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6831: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6832: 	return "$num1,$num2";
                   6833:     }
                   6834: }
                   6835: 
                   6836: sub rndseed_64bit3 {
                   6837:     my ($symb,$courseid,$domain,$username)=@_;
                   6838:     {
                   6839: 	use integer;
                   6840: 	# strings need to be an even # of cahracters long, it it is odd the
                   6841:         # last characters gets thrown away
                   6842: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6843: 	my $symbseed=numval2($symb) << 10;
                   6844: 	my $namechck=unpack("%32S*",$username.' ');
                   6845: 	
                   6846: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6847: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6848: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6849: 	
                   6850: 	my $num1=$symbchck+$symbseed+$namechck;
                   6851: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6852: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6853: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6854: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6855: 	
1.503     albertel 6856: 	return "$num1:$num2";
1.443     albertel 6857:     }
                   6858: }
                   6859: 
1.575     albertel 6860: sub rndseed_64bit4 {
                   6861:     my ($symb,$courseid,$domain,$username)=@_;
                   6862:     {
                   6863: 	use integer;
                   6864: 	# strings need to be an even # of cahracters long, it it is odd the
                   6865:         # last characters gets thrown away
                   6866: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6867: 	my $symbseed=numval3($symb) << 10;
                   6868: 	my $namechck=unpack("%32S*",$username.' ');
                   6869: 	
                   6870: 	my $nameseed=numval3($username) << 21;
                   6871: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6872: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6873: 	
                   6874: 	my $num1=$symbchck+$symbseed+$namechck;
                   6875: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6876: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6877: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6878: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6879: 	
                   6880: 	return "$num1:$num2";
                   6881:     }
                   6882: }
                   6883: 
1.675     albertel 6884: sub rndseed_64bit5 {
                   6885:     my ($symb,$courseid,$domain,$username)=@_;
                   6886:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6887:     return "$num1:$num2";
                   6888: }
                   6889: 
1.366     albertel 6890: sub rndseed_CODE_64bit {
                   6891:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6892:     {
1.366     albertel 6893: 	use integer;
1.443     albertel 6894: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6895: 	my $symbseed=numval2($symb);
1.491     albertel 6896: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6897: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6898: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6899: 	my $num1=$symbseed+$CODEchck;
                   6900: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6901: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6902: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6903: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6904: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6905: 	return "$num1:$num2";
1.366     albertel 6906:     }
                   6907: }
                   6908: 
1.575     albertel 6909: sub rndseed_CODE_64bit4 {
                   6910:     my ($symb,$courseid,$domain,$username)=@_;
                   6911:     {
                   6912: 	use integer;
                   6913: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6914: 	my $symbseed=numval3($symb);
                   6915: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6916: 	my $CODEseed=numval3(&getCODE());
                   6917: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6918: 	my $num1=$symbseed+$CODEchck;
                   6919: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6920: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6921: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6922: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6923: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6924: 	return "$num1:$num2";
                   6925:     }
                   6926: }
                   6927: 
1.675     albertel 6928: sub rndseed_CODE_64bit5 {
                   6929:     my ($symb,$courseid,$domain,$username)=@_;
                   6930:     my $code = &getCODE();
                   6931:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6932:     return "$num1:$num2";
                   6933: }
                   6934: 
1.366     albertel 6935: sub setup_random_from_rndseed {
                   6936:     my ($rndseed)=@_;
1.503     albertel 6937:     if ($rndseed =~/([,:])/) {
                   6938: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6939: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6940:     } else {
                   6941: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6942:     }
1.36      albertel 6943: }
                   6944: 
1.474     albertel 6945: sub latest_receipt_algorithm_id {
                   6946:     return 'receipt2';
                   6947: }
                   6948: 
1.480     www      6949: sub recunique {
                   6950:     my $fucourseid=shift;
                   6951:     my $unique;
1.620     albertel 6952:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6953: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6954:     } else {
                   6955: 	$unique=$perlvar{'lonReceipt'};
                   6956:     }
                   6957:     return unpack("%32C*",$unique);
                   6958: }
                   6959: 
                   6960: sub recprefix {
                   6961:     my $fucourseid=shift;
                   6962:     my $prefix;
1.620     albertel 6963:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6964: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6965:     } else {
                   6966: 	$prefix=$perlvar{'lonHostID'};
                   6967:     }
                   6968:     return unpack("%32C*",$prefix);
                   6969: }
                   6970: 
1.76      www      6971: sub ireceipt {
1.474     albertel 6972:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6973:     my $cuname=unpack("%32C*",$funame);
                   6974:     my $cudom=unpack("%32C*",$fudom);
                   6975:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6976:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6977:     my $cunique=&recunique($fucourseid);
1.474     albertel 6978:     my $cpart=unpack("%32S*",$part);
1.480     www      6979:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6980:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6981: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6982: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6983: 			       
                   6984: 	$return.= ($cunique%$cuname+
                   6985: 		   $cunique%$cudom+
                   6986: 		   $cusymb%$cuname+
                   6987: 		   $cusymb%$cudom+
                   6988: 		   $cucourseid%$cuname+
                   6989: 		   $cucourseid%$cudom+
                   6990: 		   $cpart%$cuname+
                   6991: 		   $cpart%$cudom);
                   6992:     } else {
                   6993: 	$return.= ($cunique%$cuname+
                   6994: 		   $cunique%$cudom+
                   6995: 		   $cusymb%$cuname+
                   6996: 		   $cusymb%$cudom+
                   6997: 		   $cucourseid%$cuname+
                   6998: 		   $cucourseid%$cudom);
                   6999:     }
                   7000:     return $return;
1.76      www      7001: }
                   7002: 
                   7003: sub receipt {
1.474     albertel 7004:     my ($part)=@_;
1.790     albertel 7005:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7006:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7007: }
1.260     ng       7008: 
1.790     albertel 7009: sub whichuser {
                   7010:     my ($passedsymb)=@_;
                   7011:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7012:     if (defined($env{'form.grade_symb'})) {
                   7013: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7014: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7015: 	if (!$allowed &&
                   7016: 	    exists($env{'request.course.sec'}) &&
                   7017: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7018: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7019: 			      '/'.$env{'request.course.sec'});
                   7020: 	}
                   7021: 	if ($allowed) {
                   7022: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7023: 	    $courseid=$tmp_courseid;
                   7024: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7025: 	    ($name)=&get_env_multiple('form.grade_username');
                   7026: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7027: 	}
                   7028:     }
                   7029:     if (!$passedsymb) {
                   7030: 	$symb=&symbread();
                   7031:     } else {
                   7032: 	$symb=$passedsymb;
                   7033:     }
                   7034:     $courseid=$env{'request.course.id'};
                   7035:     $domain=$env{'user.domain'};
                   7036:     $name=$env{'user.name'};
                   7037:     if ($name eq 'public' && $domain eq 'public') {
                   7038: 	if (!defined($env{'form.username'})) {
                   7039: 	    $env{'form.username'}.=time.rand(10000000);
                   7040: 	}
                   7041: 	$name.=$env{'form.username'};
                   7042:     }
                   7043:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7044: 
                   7045: }
                   7046: 
1.36      albertel 7047: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7048: # returns either the contents of the file or 
                   7049: # -1 if the file doesn't exist
1.481     raeburn  7050: #
                   7051: # if the target is a file that was uploaded via DOCS, 
                   7052: # a check will be made to see if a current copy exists on the local server,
                   7053: # if it does this will be served, otherwise a copy will be retrieved from
                   7054: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7055: # the local server.   
1.472     albertel 7056: 
1.36      albertel 7057: sub getfile {
1.538     albertel 7058:     my ($file) = @_;
1.609     banghart 7059:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7060:     &repcopy($file);
                   7061:     return &readfile($file);
                   7062: }
                   7063: 
                   7064: sub repcopy_userfile {
                   7065:     my ($file)=@_;
1.609     banghart 7066:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7067:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7068:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7069: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7070:     my ($info,$rtncode);
                   7071:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7072:     if (-e "$file") {
                   7073: 	my @fileinfo = stat($file);
                   7074: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7075: 	if ($lwpresp ne 'ok') {
                   7076: 	    if ($rtncode eq '404') {
1.538     albertel 7077: 		unlink($file);
1.482     albertel 7078: 	    }
1.517     albertel 7079: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7080: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7081: 	    #my $response=$ua->request($request);
                   7082: 	    #if ($response->is_success()) {
                   7083: 	#	return $response->content;
                   7084: 	#    } else {
                   7085: 	#	return -1;
                   7086: 	#    }
1.482     albertel 7087: 	    return -1;
                   7088: 	}
                   7089: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7090: 	    return 'ok';
1.482     albertel 7091: 	}
                   7092: 	$info = '';
1.538     albertel 7093: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7094: 	if ($lwpresp ne 'ok') {
                   7095: 	    return -1;
                   7096: 	}
                   7097:     } else {
1.538     albertel 7098: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7099: 	if ($lwpresp ne 'ok') {
1.517     albertel 7100: 	    my $ua=new LWP::UserAgent;
1.538     albertel 7101: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7102: 	    my $response=$ua->request($request);
                   7103: 	    if ($response->is_success()) {
1.538     albertel 7104: 		$info=$response->content;
1.517     albertel 7105: 	    } else {
                   7106: 		return -1;
                   7107: 	    }
1.482     albertel 7108: 	}
                   7109: 	my @parts = ($cdom,$cnum); 
                   7110: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7111: 	    push @parts, split(/\//,$1);
1.518     albertel 7112: 	}
1.538     albertel 7113: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7114: 	foreach my $part (@parts) {
                   7115: 	    $path .= '/'.$part;
                   7116: 	    if (!-e $path) {
                   7117: 		mkdir($path,0770);
                   7118: 	    }
                   7119: 	}
                   7120:     }
1.538     albertel 7121:     open(FILE,">$file");
1.482     albertel 7122:     print FILE $info;
                   7123:     close(FILE);
1.607     raeburn  7124:     return 'ok';
1.481     raeburn  7125: }
                   7126: 
1.517     albertel 7127: sub tokenwrapper {
                   7128:     my $uri=shift;
1.552     albertel 7129:     $uri=~s|^http\://([^/]+)||;
                   7130:     $uri=~s|^/||;
1.620     albertel 7131:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7132:     my $token=$1;
1.552     albertel 7133:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7134:     if ($udom && $uname && $file) {
                   7135: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7136:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7137:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7138:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7139:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7140:     } else {
                   7141:         return '/adm/notfound.html';
                   7142:     }
                   7143: }
                   7144: 
1.481     raeburn  7145: sub getuploaded {
                   7146:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7147:     $uri=~s/^\///;
                   7148:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7149:     my $ua=new LWP::UserAgent;
                   7150:     my $request=new HTTP::Request($reqtype,$uri);
                   7151:     my $response=$ua->request($request);
                   7152:     $$rtncode = $response->code;
1.482     albertel 7153:     if (! $response->is_success()) {
                   7154: 	return 'failed';
                   7155:     }      
                   7156:     if ($reqtype eq 'HEAD') {
1.486     www      7157: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7158:     } elsif ($reqtype eq 'GET') {
                   7159: 	$$info = $response->content;
1.472     albertel 7160:     }
1.482     albertel 7161:     return 'ok';
1.36      albertel 7162: }
                   7163: 
1.481     raeburn  7164: sub readfile {
                   7165:     my $file = shift;
                   7166:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7167:     my $fh;
                   7168:     open($fh,"<$file");
                   7169:     my $a='';
1.800     albertel 7170:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7171:     return $a;
                   7172: }
                   7173: 
1.36      albertel 7174: sub filelocation {
1.590     banghart 7175:     my ($dir,$file) = @_;
                   7176:     my $location;
                   7177:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7178: 
                   7179:     if ($file =~ m-^/adm/-) {
                   7180: 	$file=~s-^/adm/wrapper/-/-;
                   7181: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7182:     }
1.590     banghart 7183:     if ($file=~m:^/~:) { # is a contruction space reference
                   7184:         $location = $file;
                   7185:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7186:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7187: 	# is a correct contruction space reference
                   7188:         $location = $file;
1.609     banghart 7189:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7190:         my ($udom,$uname,$filename)=
1.811     albertel 7191:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7192:         my $home=&homeserver($uname,$udom);
                   7193:         my $is_me=0;
                   7194:         my @ids=&current_machine_ids();
                   7195:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7196:         if ($is_me) {
1.740     www      7197:   	    $location=&propath($udom,$uname).
1.590     banghart 7198:   	      '/userfiles/'.$filename;
                   7199:         } else {
                   7200:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7201:   	      $udom.'/'.$uname.'/'.$filename;
                   7202:         }
                   7203:     } else {
                   7204:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7205:         $file=~s:^/res/:/:;
                   7206:         if ( !( $file =~ m:^/:) ) {
                   7207:             $location = $dir. '/'.$file;
                   7208:         } else {
                   7209:             $location = '/home/httpd/html/res'.$file;
                   7210:         }
1.59      albertel 7211:     }
1.590     banghart 7212:     $location=~s://+:/:g; # remove duplicate /
                   7213:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7214:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7215:     return $location;
1.46      www      7216: }
1.36      albertel 7217: 
1.46      www      7218: sub hreflocation {
                   7219:     my ($dir,$file)=@_;
1.460     albertel 7220:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7221: 	$file=filelocation($dir,$file);
1.700     albertel 7222:     } elsif ($file=~m-^/adm/-) {
                   7223: 	$file=~s-^/adm/wrapper/-/-;
                   7224: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7225:     }
                   7226:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7227: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7228:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7229: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7230:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7231: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7232: 	    -/uploaded/$1/$2/-x;
1.46      www      7233:     }
1.462     albertel 7234:     return $file;
1.465     albertel 7235: }
                   7236: 
                   7237: sub current_machine_domains {
                   7238:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7239:     my @domains;
                   7240:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7241: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7242: 	if ($hostname eq $name) {
                   7243: 	    push(@domains,$hostdom{$id});
                   7244: 	}
                   7245:     }
                   7246:     return @domains;
                   7247: }
                   7248: 
                   7249: sub current_machine_ids {
                   7250:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7251:     my @ids;
                   7252:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7253: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7254: 	if ($hostname eq $name) {
                   7255: 	    push(@ids,$id);
                   7256: 	}
                   7257:     }
                   7258:     return @ids;
1.31      www      7259: }
                   7260: 
                   7261: # ------------------------------------------------------------- Declutters URLs
                   7262: 
                   7263: sub declutter {
                   7264:     my $thisfn=shift;
1.569     albertel 7265:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7266:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7267:     $thisfn=~s/^\///;
1.697     albertel 7268:     $thisfn=~s|^adm/wrapper/||;
                   7269:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7270:     $thisfn=~s/^res\///;
1.235     www      7271:     $thisfn=~s/\?.+$//;
1.268     www      7272:     return $thisfn;
                   7273: }
                   7274: 
                   7275: # ------------------------------------------------------------- Clutter up URLs
                   7276: 
                   7277: sub clutter {
                   7278:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7279:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7280:        $thisfn='/res'.$thisfn; 
                   7281:     }
1.694     albertel 7282:     if ($thisfn !~m|/adm|) {
1.695     albertel 7283: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7284: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7285: 	} else {
                   7286: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7287: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7288: 	    if ($embstyle eq 'ssi'
                   7289: 		|| ($embstyle eq 'hdn')
                   7290: 		|| ($embstyle eq 'rat')
                   7291: 		|| ($embstyle eq 'prv')
                   7292: 		|| ($embstyle eq 'ign')) {
                   7293: 		#do nothing with these
                   7294: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7295: 		|| ($embstyle eq 'emb')
                   7296: 		|| ($embstyle eq 'wrp')) {
                   7297: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7298: 	    } elsif ($embstyle eq 'unk'
                   7299: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7300: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7301: 	    } else {
1.718     www      7302: #		&logthis("Got a blank emb style");
1.695     albertel 7303: 	    }
1.694     albertel 7304: 	}
                   7305:     }
1.31      www      7306:     return $thisfn;
1.12      www      7307: }
                   7308: 
1.787     albertel 7309: sub clutter_with_no_wrapper {
                   7310:     my $uri = &clutter(shift);
                   7311:     if ($uri =~ m-^/adm/-) {
                   7312: 	$uri =~ s-^/adm/wrapper/-/-;
                   7313: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7314:     }
                   7315:     return $uri;
                   7316: }
                   7317: 
1.557     albertel 7318: sub freeze_escape {
                   7319:     my ($value)=@_;
                   7320:     if (ref($value)) {
                   7321: 	$value=&nfreeze($value);
                   7322: 	return '__FROZEN__'.&escape($value);
                   7323:     }
                   7324:     return &escape($value);
                   7325: }
                   7326: 
1.11      www      7327: 
1.557     albertel 7328: sub thaw_unescape {
                   7329:     my ($value)=@_;
                   7330:     if ($value =~ /^__FROZEN__/) {
                   7331: 	substr($value,0,10,undef);
                   7332: 	$value=&unescape($value);
                   7333: 	return &thaw($value);
                   7334:     }
                   7335:     return &unescape($value);
                   7336: }
                   7337: 
1.436     albertel 7338: sub correct_line_ends {
                   7339:     my ($result)=@_;
                   7340:     $$result =~s/\r\n/\n/mg;
                   7341:     $$result =~s/\r/\n/mg;
1.415     albertel 7342: }
1.1       albertel 7343: # ================================================================ Main Program
                   7344: 
1.184     www      7345: sub goodbye {
1.204     albertel 7346:    &logthis("Starting Shut down");
1.443     albertel 7347: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7348:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7349: #converted
1.599     albertel 7350: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7351:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7352: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7353: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7354: #1.1 only
1.599     albertel 7355: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7356: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7357: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7358: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7359:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7360:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7361:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7362:    &flushcourselogs();
                   7363:    &logthis("Shutting down");
                   7364: }
                   7365: 
1.179     www      7366: BEGIN {
1.228     harris41 7367: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7368:     unless ($readit) {
1.217     harris41 7369: {
1.781     raeburn  7370:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7371:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7372: }
1.1       albertel 7373: 
1.327     albertel 7374: # ------------------------------------------------------------ Read domain file
                   7375: {
                   7376:     %domaindescription = ();
                   7377:     %domain_auth_def = ();
                   7378:     %domain_auth_arg_def = ();
1.448     albertel 7379:     my $fh;
                   7380:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7381: 	while (my $line = <$fh>) {
                   7382:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7383: #           next if /^\#/;
1.801     foxr     7384:            chomp $line;
1.403     www      7385:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7386: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7387: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7388:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7389: 	   $domaindescription{$domain}=$domain_description;
                   7390: 	   $domain_lang_def{$domain}=$def_lang;
                   7391: 	   $domain_city{$domain}=$city;
                   7392: 	   $domain_longi{$domain}=$longi;
                   7393: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7394:            $domain_primary{$domain}=$primary;
1.403     www      7395: 
1.448     albertel 7396:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7397: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7398: 	}
1.327     albertel 7399:     }
1.448     albertel 7400:     close ($fh);
1.327     albertel 7401: }
                   7402: 
                   7403: 
1.1       albertel 7404: # ------------------------------------------------------------- Read hosts file
                   7405: {
1.448     albertel 7406:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7407: 
                   7408:     while (my $configline=<$config>) {
1.303     matthew  7409:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7410:        chomp($configline);
1.595     albertel 7411:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7412:        $name=~s/\s//g;
1.595     albertel 7413:        if ($id && $domain && $role && $name) {
1.252     albertel 7414: 	 $hostname{$id}=$name;
                   7415: 	 $hostdom{$id}=$domain;
                   7416: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7417:        }
1.1       albertel 7418:     }
1.448     albertel 7419:     close($config);
1.619     albertel 7420:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7421:     #&get_iphost();
1.1       albertel 7422: }
                   7423: 
1.598     albertel 7424: sub get_iphost {
                   7425:     if (%iphost) { return %iphost; }
1.653     albertel 7426:     my %name_to_ip;
1.598     albertel 7427:     foreach my $id (keys(%hostname)) {
                   7428: 	my $name=$hostname{$id};
1.653     albertel 7429: 	my $ip;
                   7430: 	if (!exists($name_to_ip{$name})) {
                   7431: 	    $ip = gethostbyname($name);
                   7432: 	    if (!$ip || length($ip) ne 4) {
                   7433: 		&logthis("Skipping host $id name $name no IP found\n");
                   7434: 		next;
                   7435: 	    }
                   7436: 	    $ip=inet_ntoa($ip);
                   7437: 	    $name_to_ip{$name} = $ip;
                   7438: 	} else {
                   7439: 	    $ip = $name_to_ip{$name};
1.598     albertel 7440: 	}
                   7441: 	push(@{$iphost{$ip}},$id);
                   7442:     }
                   7443:     return %iphost;
                   7444: }
                   7445: 
1.1       albertel 7446: # ------------------------------------------------------ Read spare server file
                   7447: {
1.448     albertel 7448:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7449: 
                   7450:     while (my $configline=<$config>) {
                   7451:        chomp($configline);
1.284     matthew  7452:        if ($configline) {
1.784     albertel 7453: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7454: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7455: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7456:        }
                   7457:     }
1.448     albertel 7458:     close($config);
1.1       albertel 7459: }
1.11      www      7460: # ------------------------------------------------------------ Read permissions
                   7461: {
1.448     albertel 7462:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7463: 
                   7464:     while (my $configline=<$config>) {
1.448     albertel 7465: 	chomp($configline);
                   7466: 	if ($configline) {
                   7467: 	    my ($role,$perm)=split(/ /,$configline);
                   7468: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7469: 	}
1.11      www      7470:     }
1.448     albertel 7471:     close($config);
1.11      www      7472: }
                   7473: 
                   7474: # -------------------------------------------- Read plain texts for permissions
                   7475: {
1.448     albertel 7476:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7477: 
                   7478:     while (my $configline=<$config>) {
1.448     albertel 7479: 	chomp($configline);
                   7480: 	if ($configline) {
1.742     raeburn  7481: 	    my ($short,@plain)=split(/:/,$configline);
                   7482:             %{$prp{$short}} = ();
                   7483: 	    if (@plain > 0) {
                   7484:                 $prp{$short}{'std'} = $plain[0];
                   7485:                 for (my $i=1; $i<@plain; $i++) {
                   7486:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7487:                 }
                   7488:             }
1.448     albertel 7489: 	}
1.135     www      7490:     }
1.448     albertel 7491:     close($config);
1.135     www      7492: }
                   7493: 
                   7494: # ---------------------------------------------------------- Read package table
                   7495: {
1.448     albertel 7496:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7497: 
                   7498:     while (my $configline=<$config>) {
1.483     albertel 7499: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7500: 	chomp($configline);
                   7501: 	my ($short,$plain)=split(/:/,$configline);
                   7502: 	my ($pack,$name)=split(/\&/,$short);
                   7503: 	if ($plain ne '') {
                   7504: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7505: 	    $packagetab{$short}=$plain; 
                   7506: 	}
1.11      www      7507:     }
1.448     albertel 7508:     close($config);
1.329     matthew  7509: }
                   7510: 
                   7511: # ------------- set up temporary directory
                   7512: {
                   7513:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7514: 
1.11      www      7515: }
                   7516: 
1.794     albertel 7517: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7518: 				'compress_threshold'=> 20_000,
                   7519:  			        });
1.185     www      7520: 
1.281     www      7521: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7522: $dumpcount=0;
1.22      www      7523: 
1.163     harris41 7524: &logtouch();
1.672     albertel 7525: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7526: $readit=1;
1.564     albertel 7527:     {
                   7528: 	use integer;
                   7529: 	my $test=(2**32)+1;
1.568     albertel 7530: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7531: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7532:     }
1.195     www      7533: }
1.1       albertel 7534: }
1.179     www      7535: 
1.1       albertel 7536: 1;
1.191     harris41 7537: __END__
                   7538: 
1.243     albertel 7539: =pod
                   7540: 
1.191     harris41 7541: =head1 NAME
                   7542: 
1.243     albertel 7543: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7544: 
                   7545: =head1 SYNOPSIS
                   7546: 
1.243     albertel 7547: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7548: 
                   7549:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7550: 
1.243     albertel 7551: Common parameters:
                   7552: 
                   7553: =over 4
                   7554: 
                   7555: =item *
                   7556: 
                   7557: $uname : an internal username (if $cname expecting a course Id specifically)
                   7558: 
                   7559: =item *
                   7560: 
                   7561: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7562: 
                   7563: =item *
                   7564: 
                   7565: $symb : a resource instance identifier
                   7566: 
                   7567: =item *
                   7568: 
                   7569: $namespace : the name of a .db file that contains the data needed or
                   7570: being set.
                   7571: 
                   7572: =back
                   7573: 
1.394     bowersj2 7574: =head1 OVERVIEW
1.191     harris41 7575: 
1.394     bowersj2 7576: lonnet provides subroutines which interact with the
                   7577: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7578: about classes, users, and resources.
1.243     albertel 7579: 
                   7580: For many of these objects you can also use this to store data about
                   7581: them or modify them in various ways.
1.191     harris41 7582: 
1.394     bowersj2 7583: =head2 Symbs
1.191     harris41 7584: 
1.394     bowersj2 7585: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7586: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7587: map, the resource number of the resource in the map, and the URL of
                   7588: the resource itself. The latter is somewhat redundant, but might help
                   7589: if maps change.
                   7590: 
                   7591: An example is
                   7592: 
                   7593:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7594: 
                   7595: The respective map entry is
                   7596: 
                   7597:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7598:   title="Problem 2">
                   7599:  </resource>
                   7600: 
                   7601: Symbs are used by the random number generator, as well as to store and
                   7602: restore data specific to a certain instance of for example a problem.
                   7603: 
                   7604: =head2 Storing And Retrieving Data
                   7605: 
                   7606: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7607: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7608: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7609: is is the non-critical message twin of cstore. These functions are for
                   7610: handlers to store a perl hash to a user's permanent data space in an
                   7611: easy manner, and to retrieve it again on another call. It is expected
                   7612: that a handler would use this once at the beginning to retrieve data,
                   7613: and then again once at the end to send only the new data back.
                   7614: 
                   7615: The data is stored in the user's data directory on the user's
                   7616: homeserver under the ID of the course.
                   7617: 
                   7618: The hash that is returned by restore will have all of the previous
                   7619: value for all of the elements of the hash.
                   7620: 
                   7621: Example:
                   7622: 
                   7623:  #creating a hash
                   7624:  my %hash;
                   7625:  $hash{'foo'}='bar';
                   7626: 
                   7627:  #storing it
                   7628:  &Apache::lonnet::cstore(\%hash);
                   7629: 
                   7630:  #changing a value
                   7631:  $hash{'foo'}='notbar';
                   7632: 
                   7633:  #adding a new value
                   7634:  $hash{'bar'}='foo';
                   7635:  &Apache::lonnet::cstore(\%hash);
                   7636: 
                   7637:  #retrieving the hash
                   7638:  my %history=&Apache::lonnet::restore();
                   7639: 
                   7640:  #print the hash
                   7641:  foreach my $key (sort(keys(%history))) {
                   7642:    print("\%history{$key} = $history{$key}");
                   7643:  }
                   7644: 
                   7645: Will print out:
1.191     harris41 7646: 
1.394     bowersj2 7647:  %history{1:foo} = bar
                   7648:  %history{1:keys} = foo:timestamp
                   7649:  %history{1:timestamp} = 990455579
                   7650:  %history{2:bar} = foo
                   7651:  %history{2:foo} = notbar
                   7652:  %history{2:keys} = foo:bar:timestamp
                   7653:  %history{2:timestamp} = 990455580
                   7654:  %history{bar} = foo
                   7655:  %history{foo} = notbar
                   7656:  %history{timestamp} = 990455580
                   7657:  %history{version} = 2
                   7658: 
                   7659: Note that the special hash entries C<keys>, C<version> and
                   7660: C<timestamp> were added to the hash. C<version> will be equal to the
                   7661: total number of versions of the data that have been stored. The
                   7662: C<timestamp> attribute will be the UNIX time the hash was
                   7663: stored. C<keys> is available in every historical section to list which
                   7664: keys were added or changed at a specific historical revision of a
                   7665: hash.
                   7666: 
                   7667: B<Warning>: do not store the hash that restore returns directly. This
                   7668: will cause a mess since it will restore the historical keys as if the
                   7669: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7670: 
1.394     bowersj2 7671: Calling convention:
1.191     harris41 7672: 
1.394     bowersj2 7673:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7674:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7675: 
1.394     bowersj2 7676: For more detailed information, see lonnet specific documentation.
1.191     harris41 7677: 
1.394     bowersj2 7678: =head1 RETURN MESSAGES
1.191     harris41 7679: 
1.394     bowersj2 7680: =over 4
1.191     harris41 7681: 
1.394     bowersj2 7682: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7683: 
1.394     bowersj2 7684: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7685: when the connection is brought back up
1.191     harris41 7686: 
1.394     bowersj2 7687: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7688: for later delivery
1.191     harris41 7689: 
1.394     bowersj2 7690: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7691: 
1.394     bowersj2 7692: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7693: that was requested
1.191     harris41 7694: 
1.243     albertel 7695: =back
1.191     harris41 7696: 
1.243     albertel 7697: =head1 PUBLIC SUBROUTINES
1.191     harris41 7698: 
1.243     albertel 7699: =head2 Session Environment Functions
1.191     harris41 7700: 
1.243     albertel 7701: =over 4
1.191     harris41 7702: 
1.394     bowersj2 7703: =item * 
                   7704: X<appenv()>
                   7705: B<appenv(%hash)>: the value of %hash is written to
                   7706: the user envirnoment file, and will be restored for each access this
1.620     albertel 7707: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7708: process
1.191     harris41 7709: 
                   7710: =item *
1.394     bowersj2 7711: X<delenv()>
                   7712: B<delenv($regexp)>: removes all items from the session
                   7713: environment file that matches the regular expression in $regexp. The
1.620     albertel 7714: values are also delted from the current processes %env.
1.191     harris41 7715: 
1.795     albertel 7716: =item * get_env_multiple($name) 
                   7717: 
                   7718: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7719: values may be defined and end up as an array ref.
                   7720: 
                   7721: returns an array of values
                   7722: 
1.243     albertel 7723: =back
                   7724: 
                   7725: =head2 User Information
1.191     harris41 7726: 
1.243     albertel 7727: =over 4
1.191     harris41 7728: 
                   7729: =item *
1.394     bowersj2 7730: X<queryauthenticate()>
                   7731: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7732: authentication scheme
                   7733: 
                   7734: =item *
1.394     bowersj2 7735: X<authenticate()>
                   7736: B<authenticate($uname,$upass,$udom)>: try to
                   7737: authenticate user from domain's lib servers (first use the current
                   7738: one). C<$upass> should be the users password.
1.191     harris41 7739: 
                   7740: =item *
1.394     bowersj2 7741: X<homeserver()>
                   7742: B<homeserver($uname,$udom)>: find the server which has
                   7743: the user's directory and files (there must be only one), this caches
                   7744: the answer, and also caches if there is a borken connection.
1.191     harris41 7745: 
                   7746: =item *
1.394     bowersj2 7747: X<idget()>
                   7748: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7749: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7750: username, and only 1 username per ID in a specific domain) (returns
                   7751: hash: id=>name,id=>name)
1.191     harris41 7752: 
                   7753: =item *
1.394     bowersj2 7754: X<idrget()>
                   7755: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7756: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7757: 
                   7758: =item *
1.394     bowersj2 7759: X<idput()>
                   7760: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7761: 
                   7762: =item *
1.394     bowersj2 7763: X<rolesinit()>
                   7764: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7765: 
                   7766: =item *
1.551     albertel 7767: X<getsection()>
                   7768: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7769: course $cname, return section name/number or '' for "not in course"
                   7770: and '-1' for "no section"
                   7771: 
                   7772: =item *
1.394     bowersj2 7773: X<userenvironment()>
                   7774: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7775: passed in @what from the requested user's environment, returns a hash
                   7776: 
                   7777: =back
                   7778: 
                   7779: =head2 User Roles
                   7780: 
                   7781: =over 4
                   7782: 
                   7783: =item *
                   7784: 
1.810     raeburn  7785: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7786:  F: full access
                   7787:  U,I,K: authentication modes (cxx only)
                   7788:  '': forbidden
                   7789:  1: user needs to choose course
                   7790:  2: browse allowed
1.766     albertel 7791:  A: passphrase authentication needed
1.243     albertel 7792: 
                   7793: =item *
                   7794: 
                   7795: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7796: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7797: and course level
                   7798: 
                   7799: =item *
                   7800: 
                   7801: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7802: explanation of a user role term
                   7803: 
                   7804: =back
                   7805: 
                   7806: =head2 User Modification
                   7807: 
                   7808: =over 4
                   7809: 
                   7810: =item *
                   7811: 
                   7812: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7813: user for the level given by URL.  Optional start and end dates (leave empty
                   7814: string or zero for "no date")
1.191     harris41 7815: 
                   7816: =item *
                   7817: 
1.243     albertel 7818: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7819: change a users, password, possible return values are: ok,
                   7820: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7821: refused
1.191     harris41 7822: 
                   7823: =item *
                   7824: 
1.243     albertel 7825: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7826: 
                   7827: =item *
                   7828: 
1.243     albertel 7829: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7830: modify user
1.191     harris41 7831: 
                   7832: =item *
                   7833: 
1.286     matthew  7834: modifystudent
                   7835: 
                   7836: modify a students enrollment and identification information.
                   7837: The course id is resolved based on the current users environment.  
                   7838: This means the envoking user must be a course coordinator or otherwise
                   7839: associated with a course.
                   7840: 
1.297     matthew  7841: This call is essentially a wrapper for lonnet::modifyuser and
                   7842: lonnet::modify_student_enrollment
1.286     matthew  7843: 
                   7844: Inputs: 
                   7845: 
                   7846: =over 4
                   7847: 
                   7848: =item B<$udom> Students loncapa domain
                   7849: 
                   7850: =item B<$uname> Students loncapa login name
                   7851: 
                   7852: =item B<$uid> Students id/student number
                   7853: 
                   7854: =item B<$umode> Students authentication mode
                   7855: 
                   7856: =item B<$upass> Students password
                   7857: 
                   7858: =item B<$first> Students first name
                   7859: 
                   7860: =item B<$middle> Students middle name
                   7861: 
                   7862: =item B<$last> Students last name
                   7863: 
                   7864: =item B<$gene> Students generation
                   7865: 
                   7866: =item B<$usec> Students section in course
                   7867: 
                   7868: =item B<$end> Unix time of the roles expiration
                   7869: 
                   7870: =item B<$start> Unix time of the roles start date
                   7871: 
                   7872: =item B<$forceid> If defined, allow $uid to be changed
                   7873: 
                   7874: =item B<$desiredhome> server to use as home server for student
                   7875: 
                   7876: =back
1.297     matthew  7877: 
                   7878: =item *
                   7879: 
                   7880: modify_student_enrollment
                   7881: 
                   7882: Change a students enrollment status in a class.  The environment variable
                   7883: 'role.request.course' must be defined for this function to proceed.
                   7884: 
                   7885: Inputs:
                   7886: 
                   7887: =over 4
                   7888: 
                   7889: =item $udom, students domain
                   7890: 
                   7891: =item $uname, students name
                   7892: 
                   7893: =item $uid, students user id
                   7894: 
                   7895: =item $first, students first name
                   7896: 
                   7897: =item $middle
                   7898: 
                   7899: =item $last
                   7900: 
                   7901: =item $gene
                   7902: 
                   7903: =item $usec
                   7904: 
                   7905: =item $end
                   7906: 
                   7907: =item $start
                   7908: 
                   7909: =back
                   7910: 
1.191     harris41 7911: 
                   7912: =item *
                   7913: 
1.243     albertel 7914: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7915: custom role; give a custom role to a user for the level given by URL.  Specify
                   7916: name and domain of role author, and role name
1.191     harris41 7917: 
                   7918: =item *
                   7919: 
1.243     albertel 7920: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7921: 
                   7922: =item *
                   7923: 
1.243     albertel 7924: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7925: 
                   7926: =back
                   7927: 
                   7928: =head2 Course Infomation
                   7929: 
                   7930: =over 4
1.191     harris41 7931: 
                   7932: =item *
                   7933: 
1.631     albertel 7934: coursedescription($courseid) : returns a hash of information about the
                   7935: specified course id, including all environment settings for the
                   7936: course, the description of the course will be in the hash under the
                   7937: key 'description'
1.191     harris41 7938: 
                   7939: =item *
                   7940: 
1.624     albertel 7941: resdata($name,$domain,$type,@which) : request for current parameter
                   7942: setting for a specific $type, where $type is either 'course' or 'user',
                   7943: @what should be a list of parameters to ask about. This routine caches
                   7944: answers for 5 minutes.
1.243     albertel 7945: 
                   7946: =back
                   7947: 
                   7948: =head2 Course Modification
                   7949: 
                   7950: =over 4
1.191     harris41 7951: 
                   7952: =item *
                   7953: 
1.243     albertel 7954: writecoursepref($courseid,%prefs) : write preferences (environment
                   7955: database) for a course
1.191     harris41 7956: 
                   7957: =item *
                   7958: 
1.243     albertel 7959: createcourse($udom,$description,$url) : make/modify course
                   7960: 
                   7961: =back
                   7962: 
                   7963: =head2 Resource Subroutines
                   7964: 
                   7965: =over 4
1.191     harris41 7966: 
                   7967: =item *
                   7968: 
1.243     albertel 7969: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7970: 
                   7971: =item *
                   7972: 
1.243     albertel 7973: repcopy($filename) : subscribes to the requested file, and attempts to
                   7974: replicate from the owning library server, Might return
1.607     raeburn  7975: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7976: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7977: resource. Expects the local filesystem pathname
                   7978: (/home/httpd/html/res/....)
                   7979: 
                   7980: =back
                   7981: 
                   7982: =head2 Resource Information
                   7983: 
                   7984: =over 4
1.191     harris41 7985: 
                   7986: =item *
                   7987: 
1.243     albertel 7988: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7989: a vairety of different possible values, $varname should be a request
                   7990: string, and the other parameters can be used to specify who and what
                   7991: one is asking about.
                   7992: 
                   7993: Possible values for $varname are environment.lastname (or other item
                   7994: from the envirnment hash), user.name (or someother aspect about the
                   7995: user), resource.0.maxtries (or some other part and parameter of a
                   7996: resource)
1.204     albertel 7997: 
                   7998: =item *
                   7999: 
1.243     albertel 8000: directcondval($number) : get current value of a condition; reads from a state
                   8001: string
1.204     albertel 8002: 
                   8003: =item *
                   8004: 
1.243     albertel 8005: condval($condidx) : value of condition index based on state
1.204     albertel 8006: 
                   8007: =item *
                   8008: 
1.243     albertel 8009: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8010: resource's metadata, $what should be either a specific key, or either
                   8011: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8012: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8013: 
                   8014: this function automatically caches all requests
1.191     harris41 8015: 
                   8016: =item *
                   8017: 
1.243     albertel 8018: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8019: network of library servers; returns file handle of where SQL and regex results
                   8020: will be stored for query
1.191     harris41 8021: 
                   8022: =item *
                   8023: 
1.243     albertel 8024: symbread($filename) : return symbolic list entry (filename argument optional);
                   8025: returns the data handle
1.191     harris41 8026: 
                   8027: =item *
                   8028: 
1.243     albertel 8029: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8030: a possible symb for the URL in $thisfn, and if is an encryypted
                   8031: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8032: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8033: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8034: 
1.191     harris41 8035: 
                   8036: =item *
                   8037: 
1.243     albertel 8038: symbclean($symb) : removes versions numbers from a symb, returns the
                   8039: cleaned symb
1.191     harris41 8040: 
                   8041: =item *
                   8042: 
1.243     albertel 8043: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8044: course map, user must be in a course for it to work.
1.191     harris41 8045: 
                   8046: =item *
                   8047: 
1.243     albertel 8048: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8049: 
                   8050: =item *
                   8051: 
1.243     albertel 8052: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8053: a random seed, all arguments are optional, if they aren't sent it uses the
                   8054: environment to derive them. Note: if symb isn't sent and it can't get one
                   8055: from &symbread it will use the current time as its return value
1.191     harris41 8056: 
                   8057: =item *
                   8058: 
1.243     albertel 8059: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8060: unfakeable, receipt
1.191     harris41 8061: 
                   8062: =item *
                   8063: 
1.620     albertel 8064: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8065: 
                   8066: =item *
                   8067: 
1.243     albertel 8068: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8069: 
                   8070: =item *
                   8071: 
1.243     albertel 8072: 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 8073: 
                   8074: =item *
                   8075: 
1.243     albertel 8076: 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 8077: 
                   8078: =item *
                   8079: 
1.243     albertel 8080: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8081: 
                   8082: =item *
                   8083: 
1.243     albertel 8084: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8085: forcing spreadsheet to reevaluate the resource scores next time.
                   8086: 
                   8087: =back
                   8088: 
                   8089: =head2 Storing/Retreiving Data
                   8090: 
                   8091: =over 4
1.191     harris41 8092: 
                   8093: =item *
                   8094: 
1.243     albertel 8095: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8096: for this url; hashref needs to be given and should be a \%hashname; the
                   8097: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8098: be derived from the env
1.191     harris41 8099: 
                   8100: =item *
                   8101: 
1.243     albertel 8102: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8103: uses critical subroutine
1.191     harris41 8104: 
                   8105: =item *
                   8106: 
1.243     albertel 8107: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8108: all args are optional
1.191     harris41 8109: 
                   8110: =item *
                   8111: 
1.717     albertel 8112: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8113: dumps the complete (or key matching regexp) namespace into a hash
                   8114: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8115: normally &store()ed into
                   8116: 
                   8117: $range should be either an integer '100' (give me the first 100
                   8118:                                            matching records)
                   8119:               or be  two integers sperated by a - with no spaces
                   8120:                  '30-50' (give me the 30th through the 50th matching
                   8121:                           records)
                   8122: 
                   8123: 
                   8124: =item *
                   8125: 
                   8126: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8127: replaces a &store() version of data with a replacement set of data
                   8128: for a particular resource in a namespace passed in the $storehash hash 
                   8129: reference
                   8130: 
                   8131: =item *
                   8132: 
1.243     albertel 8133: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8134: works very similar to store/cstore, but all data is stored in a
                   8135: temporary location and can be reset using tmpreset, $storehash should
                   8136: be a hash reference, returns nothing on success
1.191     harris41 8137: 
                   8138: =item *
                   8139: 
1.243     albertel 8140: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8141: similar to restore, but all data is stored in a temporary location and
                   8142: can be reset using tmpreset. Returns a hash of values on success,
                   8143: error string otherwise.
1.191     harris41 8144: 
                   8145: =item *
                   8146: 
1.243     albertel 8147: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8148: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8149: 
                   8150: =item *
                   8151: 
1.243     albertel 8152: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8153: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8154: 
                   8155: =item *
                   8156: 
1.243     albertel 8157: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8158: namesp ($udom and $uname are optional)
1.191     harris41 8159: 
                   8160: =item *
                   8161: 
1.702     albertel 8162: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8163: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8164: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8165: 
1.702     albertel 8166: $range should be either an integer '100' (give me the first 100
                   8167:                                            matching records)
                   8168:               or be  two integers sperated by a - with no spaces
                   8169:                  '30-50' (give me the 30th through the 50th matching
                   8170:                           records)
1.449     matthew  8171: =item *
                   8172: 
                   8173: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8174: $store can be a scalar, an array reference, or if the amount to be 
                   8175: incremented is > 1, a hash reference.
                   8176: 
                   8177: ($udom and $uname are optional)
1.191     harris41 8178: 
                   8179: =item *
                   8180: 
1.243     albertel 8181: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8182: ($udom and $uname are optional)
1.191     harris41 8183: 
                   8184: =item *
                   8185: 
1.243     albertel 8186: cput($namespace,$storehash,$udom,$uname) : critical put
                   8187: ($udom and $uname are optional)
1.191     harris41 8188: 
                   8189: =item *
                   8190: 
1.748     albertel 8191: newput($namespace,$storehash,$udom,$uname) :
                   8192: 
                   8193: Attempts to store the items in the $storehash, but only if they don't
                   8194: currently exist, if this succeeds you can be certain that you have 
                   8195: successfully created a new key value pair in the $namespace db.
                   8196: 
                   8197: 
                   8198: Args:
                   8199:  $namespace: name of database to store values to
                   8200:  $storehash: hashref to store to the db
                   8201:  $udom: (optional) domain of user containing the db
                   8202:  $uname: (optional) name of user caontaining the db
                   8203: 
                   8204: Returns:
                   8205:  'ok' -> succeeded in storing all keys of $storehash
                   8206:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8207:                         least <key> already existed in the db (other
                   8208:                         requested keys may also already exist)
                   8209:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8210:  'con_lost' -> unable to contact request server
                   8211:  'refused' -> action was not allowed by remote machine
                   8212: 
                   8213: 
                   8214: =item *
                   8215: 
1.243     albertel 8216: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8217: reference filled in from namesp (encrypts the return communication)
                   8218: ($udom and $uname are optional)
1.191     harris41 8219: 
                   8220: =item *
                   8221: 
1.243     albertel 8222: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8223: critical subroutine
                   8224: 
1.806     raeburn  8225: =item *
                   8226: 
                   8227: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8228: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8229: 
                   8230: =item *
                   8231: 
                   8232: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8233: 
1.243     albertel 8234: =back
                   8235: 
                   8236: =head2 Network Status Functions
                   8237: 
                   8238: =over 4
1.191     harris41 8239: 
                   8240: =item *
                   8241: 
                   8242: dirlist($uri) : return directory list based on URI
                   8243: 
                   8244: =item *
                   8245: 
1.243     albertel 8246: spareserver() : find server with least workload from spare.tab
                   8247: 
                   8248: =back
                   8249: 
                   8250: =head2 Apache Request
                   8251: 
                   8252: =over 4
1.191     harris41 8253: 
                   8254: =item *
                   8255: 
1.243     albertel 8256: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8257: localhost, posts hash
                   8258: 
                   8259: =back
                   8260: 
                   8261: =head2 Data to String to Data
                   8262: 
                   8263: =over 4
1.191     harris41 8264: 
                   8265: =item *
                   8266: 
1.243     albertel 8267: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8268: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8269: 
                   8270: =item *
                   8271: 
1.243     albertel 8272: hashref2str($hashref) : convert a hashref into a string complete with
                   8273: escaping and '=' and '&' separators, supports elements that are
                   8274: arrayrefs and hashrefs
1.191     harris41 8275: 
                   8276: =item *
                   8277: 
1.243     albertel 8278: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8279: with escaping and '&' separators, supports elements that are arrayrefs
                   8280: and hashrefs
1.191     harris41 8281: 
                   8282: =item *
                   8283: 
1.243     albertel 8284: str2hash($string) : convert string to hash using unescaping and
                   8285: splitting on '=' and '&', supports elements that are arrayrefs and
                   8286: hashrefs
1.191     harris41 8287: 
                   8288: =item *
                   8289: 
1.243     albertel 8290: str2array($string) : convert string to hash using unescaping and
                   8291: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8292: 
                   8293: =back
                   8294: 
                   8295: =head2 Logging Routines
                   8296: 
                   8297: =over 4
                   8298: 
                   8299: These routines allow one to make log messages in the lonnet.log and
                   8300: lonnet.perm logfiles.
1.191     harris41 8301: 
                   8302: =item *
                   8303: 
1.243     albertel 8304: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8305: 
                   8306: =item *
                   8307: 
1.243     albertel 8308: logthis() : append message to the normal lonnet.log file, it gets
                   8309: preiodically rolled over and deleted.
1.191     harris41 8310: 
                   8311: =item *
                   8312: 
1.243     albertel 8313: logperm() : append a permanent message to lonnet.perm.log, this log
                   8314: file never gets deleted by any automated portion of the system, only
                   8315: messages of critical importance should go in here.
                   8316: 
                   8317: =back
                   8318: 
                   8319: =head2 General File Helper Routines
                   8320: 
                   8321: =over 4
1.191     harris41 8322: 
                   8323: =item *
                   8324: 
1.481     raeburn  8325: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8326: (a) files in /uploaded
                   8327:   (i) If a local copy of the file exists - 
                   8328:       compares modification date of local copy with last-modified date for 
                   8329:       definitive version stored on home server for course. If local copy is 
                   8330:       stale, requests a new version from the home server and stores it. 
                   8331:       If the original has been removed from the home server, then local copy 
                   8332:       is unlinked.
                   8333:   (ii) If local copy does not exist -
                   8334:       requests the file from the home server and stores it. 
                   8335:   
                   8336:   If $caller is 'uploadrep':  
                   8337:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8338:     for request for files originally uploaded via DOCS. 
                   8339:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8340:   
                   8341:   Otherwise:
                   8342:      This indicates a call from the content generation phase of the request.
                   8343:      -  returns the entire contents of the file or -1.
                   8344:      
                   8345: (b) files in /res
                   8346:    - returns the entire contents of a file or -1; 
                   8347:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8348: 
1.712     albertel 8349: 
                   8350: =item *
                   8351: 
                   8352: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8353:                   reference
                   8354: 
                   8355: returns either a stat() list of data about the file or an empty list
                   8356: if the file doesn't exist or couldn't find out about it (connection
                   8357: problems or user unknown)
                   8358: 
1.191     harris41 8359: =item *
                   8360: 
1.243     albertel 8361: filelocation($dir,$file) : returns file system location of a file
                   8362: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8363: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8364: and a file of ../bob will become /a/bob)
1.191     harris41 8365: 
                   8366: =item *
                   8367: 
                   8368: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8369: filelocation except for hrefs
                   8370: 
                   8371: =item *
                   8372: 
                   8373: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8374: 
1.243     albertel 8375: =back
                   8376: 
1.608     albertel 8377: =head2 Usererfile file routines (/uploaded*)
                   8378: 
                   8379: =over 4
                   8380: 
                   8381: =item *
                   8382: 
                   8383: userfileupload(): main rotine for putting a file in a user or course's
                   8384:                   filespace, arguments are,
                   8385: 
1.620     albertel 8386:  formname - required - this is the name of the element in $env where the
1.608     albertel 8387:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8388:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8389:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8390:  coursedoc - if true, store the file in the course of the active role
                   8391:              of the current user
                   8392:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8393:          if undefined, it will be placed in "unknown"
                   8394: 
                   8395:  (This routine calls clean_filename() to remove any dangerous
                   8396:  characters from the filename, and then calls finuserfileupload() to
                   8397:  complete the transaction)
                   8398: 
                   8399:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8400:  and /adm/notfound.html if unsuccessful
                   8401: 
                   8402: =item *
                   8403: 
                   8404: clean_filename(): routine for cleaing a filename up for storage in
                   8405:                  userfile space, argument is:
                   8406: 
                   8407:  filename - proposed filename
                   8408: 
                   8409: returns: the new clean filename
                   8410: 
                   8411: =item *
                   8412: 
                   8413: finishuserfileupload(): routine that creaes and sends the file to
                   8414: userspace, probably shouldn't be called directly
                   8415: 
                   8416:   docuname: username or courseid of destination for the file
                   8417:   docudom: domain of user/course of destination for the file
                   8418:   formname: same as for userfileupload()
                   8419:   fname: filename (inculding subdirectories) for the file
                   8420: 
                   8421:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8422:  and /adm/notfound.html if unsuccessful
                   8423: 
                   8424: =item *
                   8425: 
                   8426: renameuserfile(): renames an existing userfile to a new name
                   8427: 
                   8428:   Args:
                   8429:    docuname: username or courseid of destination for the file
                   8430:    docudom: domain of user/course of destination for the file
                   8431:    old: current file name (including any subdirs under userfiles)
                   8432:    new: desired file name (including any subdirs under userfiles)
                   8433: 
                   8434: =item *
                   8435: 
                   8436: mkdiruserfile(): creates a directory is a userfiles dir
                   8437: 
                   8438:   Args:
                   8439:    docuname: username or courseid of destination for the file
                   8440:    docudom: domain of user/course of destination for the file
                   8441:    dir: dir to create (including any subdirs under userfiles)
                   8442: 
                   8443: =item *
                   8444: 
                   8445: removeuserfile(): removes a file that exists in userfiles
                   8446: 
                   8447:   Args:
                   8448:    docuname: username or courseid of destination for the file
                   8449:    docudom: domain of user/course of destination for the file
                   8450:    fname: filname to delete (including any subdirs under userfiles)
                   8451: 
                   8452: =item *
                   8453: 
                   8454: removeuploadedurl(): convience function for removeuserfile()
                   8455: 
                   8456:   Args:
                   8457:    url:  a full /uploaded/... url to delete
                   8458: 
1.747     albertel 8459: =item * 
                   8460: 
                   8461: get_portfile_permissions():
                   8462:   Args:
                   8463:     domain: domain of user or course contain the portfolio files
                   8464:     user: name of user or num of course contain the portfolio files
                   8465:   Returns:
                   8466:     hashref of a dump of the proper file_permissions.db
                   8467:    
                   8468: 
                   8469: =item * 
                   8470: 
                   8471: get_access_controls():
                   8472: 
                   8473: Args:
                   8474:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8475:   group: (optional) the group you want the files associated with
                   8476:   file: (optional) the file you want access info on
                   8477: 
                   8478: Returns:
1.749     raeburn  8479:     a hash (keys are file names) of hashes containing
                   8480:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8481:         values are XML containing access control settings (see below) 
1.747     albertel 8482: 
                   8483: Internal notes:
                   8484: 
1.749     raeburn  8485:  access controls are stored in file_permissions.db as key=value pairs.
                   8486:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8487:         where scope -> public,guest,course,group,domains or users.
                   8488:               end -> UNIX time for end of access (0 -> no end date)
                   8489:               start -> UNIX time for start of access
                   8490: 
                   8491:     value -> XML description of access control
                   8492:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8493:             <start></start>
                   8494:             <end></end>
                   8495: 
                   8496:             <password></password>  for scope type = guest
                   8497: 
                   8498:             <domain></domain>     for scope type = course or group
                   8499:             <number></number>
                   8500:             <roles id="">
                   8501:              <role></role>
                   8502:              <access></access>
                   8503:              <section></section>
                   8504:              <group></group>
                   8505:             </roles>
                   8506: 
                   8507:             <dom></dom>         for scope type = domains
                   8508: 
                   8509:             <users>             for scope type = users
                   8510:              <user>
                   8511:               <uname></uname>
                   8512:               <udom></udom>
                   8513:              </user>
                   8514:             </users>
                   8515:            </scope> 
                   8516:               
                   8517:  Access data is also aggregated for each file in an additional key=value pair:
                   8518:  key -> path to file/file_name\0accesscontrol 
                   8519:  value -> reference to hash
                   8520:           hash contains key = value pairs
                   8521:           where key = uniqueID:scope_end_start
                   8522:                 value = UNIX time record was last updated
                   8523: 
                   8524:           Used to improve speed of look-ups of access controls for each file.  
                   8525:  
                   8526:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8527: 
                   8528: modify_access_controls():
                   8529: 
                   8530: Modifies access controls for a portfolio file
                   8531: Args
                   8532: 1. file name
                   8533: 2. reference to hash of required changes,
                   8534: 3. domain
                   8535: 4. username
                   8536:   where domain,username are the domain of the portfolio owner 
                   8537:   (either a user or a course) 
                   8538: 
                   8539: Returns:
                   8540: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8541: 2. result of deletions ('ok' or 'error', with error message).
                   8542: 3. reference to hash of any new or updated access controls.
                   8543: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8544:    key = integer (inbound ID)
                   8545:    value = uniqueID  
1.747     albertel 8546: 
1.608     albertel 8547: =back
                   8548: 
1.243     albertel 8549: =head2 HTTP Helper Routines
                   8550: 
                   8551: =over 4
                   8552: 
1.191     harris41 8553: =item *
                   8554: 
                   8555: escape() : unpack non-word characters into CGI-compatible hex codes
                   8556: 
                   8557: =item *
                   8558: 
                   8559: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8560: 
1.243     albertel 8561: =back
                   8562: 
                   8563: =head1 PRIVATE SUBROUTINES
                   8564: 
                   8565: =head2 Underlying communication routines (Shouldn't call)
                   8566: 
                   8567: =over 4
                   8568: 
                   8569: =item *
                   8570: 
                   8571: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8572: 
                   8573: =item *
                   8574: 
                   8575: reply() : uses subreply to send a message to remote machine, logs all failures
                   8576: 
                   8577: =item *
                   8578: 
                   8579: critical() : passes a critical message to another server; if cannot
                   8580: get through then place message in connection buffer directory and
                   8581: returns con_delayed, if incapable of saving message, returns
                   8582: con_failed
                   8583: 
                   8584: =item *
                   8585: 
                   8586: reconlonc() : tries to reconnect lonc client processes.
                   8587: 
                   8588: =back
                   8589: 
                   8590: =head2 Resource Access Logging
                   8591: 
                   8592: =over 4
                   8593: 
                   8594: =item *
                   8595: 
                   8596: flushcourselogs() : flush (save) buffer logs and access logs
                   8597: 
                   8598: =item *
                   8599: 
                   8600: courselog($what) : save message for course in hash
                   8601: 
                   8602: =item *
                   8603: 
                   8604: courseacclog($what) : save message for course using &courselog().  Perform
                   8605: special processing for specific resource types (problems, exams, quizzes, etc).
                   8606: 
1.191     harris41 8607: =item *
                   8608: 
                   8609: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8610: as a PerlChildExitHandler
1.243     albertel 8611: 
                   8612: =back
                   8613: 
                   8614: =head2 Other
                   8615: 
                   8616: =over 4
                   8617: 
                   8618: =item *
                   8619: 
                   8620: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8621: 
                   8622: =back
                   8623: 
                   8624: =cut

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