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

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

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