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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.635   ! albertel    4: # $Id: lonnet.pm,v 1.634 2005/05/05 20:55:04 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.349     www        40:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
1.599     albertel   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
                     42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.619     albertel   43:    %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir $_64bit
                     44:    %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.8       www        48: use Apache::Constants qw(:common :http);
1.208     albertel   49: use HTML::LCParser;
1.88      www        50: use Fcntl qw(:flock);
1.414     www        51: use Apache::lonlocal;
1.557     albertel   52: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   53: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   54: use Cache::Memcached;
1.195     www        55: my $readit;
1.550     foxr       56: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   57: 
1.619     albertel   58: require Exporter;
                     59: 
                     60: our @ISA = qw (Exporter);
                     61: our @EXPORT = qw(%env);
                     62: 
1.449     matthew    63: =pod
                     64: 
                     65: =head1 Package Variables
                     66: 
                     67: These are largely undocumented, so if you decipher one please note it here.
                     68: 
                     69: =over 4
                     70: 
                     71: =item $processmarker
                     72: 
                     73: Contains the time this process was started and this servers host id.
                     74: 
                     75: =item $dumpcount
                     76: 
                     77: Counts the number of times a message log flush has been attempted (regardless
                     78: of success) by this process.  Used as part of the filename when messages are
                     79: delayed.
                     80: 
                     81: =back
                     82: 
                     83: =cut
                     84: 
                     85: 
1.1       albertel   86: # --------------------------------------------------------------------- Logging
                     87: 
1.163     harris41   88: sub logtouch {
                     89:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel   90:     unless (-e "$execdir/logs/lonnet.log") {	
                     91: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41   92: 	close $fh;
                     93:     }
                     94:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                     95:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                     96: }
                     97: 
1.1       albertel   98: sub logthis {
                     99:     my $message=shift;
                    100:     my $execdir=$perlvar{'lonDaemons'};
                    101:     my $now=time;
                    102:     my $local=localtime($now);
1.448     albertel  103:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    104: 	print $fh "$local ($$): $message\n";
                    105: 	close($fh);
                    106:     }
1.1       albertel  107:     return 1;
                    108: }
                    109: 
                    110: sub logperm {
                    111:     my $message=shift;
                    112:     my $execdir=$perlvar{'lonDaemons'};
                    113:     my $now=time;
                    114:     my $local=localtime($now);
1.448     albertel  115:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    116: 	print $fh "$now:$message:$local\n";
                    117: 	close($fh);
                    118:     }
1.1       albertel  119:     return 1;
                    120: }
                    121: 
                    122: # -------------------------------------------------- Non-critical communication
                    123: sub subreply {
                    124:     my ($cmd,$server)=@_;
                    125:     my $peerfile="$perlvar{'lonSockDir'}/$server";
1.549     foxr      126:     #
                    127:     #  With loncnew process trimming, there's a timing hole between lonc server
                    128:     #  process exit and the master server picking up the listen on the AF_UNIX
                    129:     #  socket.  In that time interval, a lock file will exist:
                    130: 
                    131:     my $lockfile=$peerfile.".lock";
                    132:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    133: 	sleep(1);
                    134:     }
                    135:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      136:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      137:     #
1.550     foxr      138:     #   We'll give the connection a few tries before abandoning it.  If
                    139:     #   connection is not possible, we'll con_lost back to the client.
                    140:     #   
                    141:     my $client;
                    142:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    143: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    144: 				      Type    => SOCK_STREAM,
                    145: 				      Timeout => 10);
                    146: 	if($client) {
                    147: 	    last;		# Connected!
                    148: 	}
                    149: 	sleep(1);		# Try again later if failed connection.
                    150:     }
                    151:     my $answer;
                    152:     if ($client) {
                    153: 	print $client "$cmd\n";
                    154: 	$answer=<$client>;
                    155: 	if (!$answer) { $answer="con_lost"; }
                    156: 	chomp($answer);
                    157:     } else {
                    158: 	$answer = 'con_lost';	# Failed connection.
                    159:     }
1.1       albertel  160:     return $answer;
                    161: }
                    162: 
                    163: sub reply {
                    164:     my ($cmd,$server)=@_;
1.205     www       165:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  166:     my $answer=subreply($cmd,$server);
1.65      www       167:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.12      www       168:        &logthis("<font color=blue>WARNING:".
                    169:                 " $cmd to $server returned $answer</font>");
                    170:     }
1.1       albertel  171:     return $answer;
                    172: }
                    173: 
                    174: # ----------------------------------------------------------- Send USR1 to lonc
                    175: 
                    176: sub reconlonc {
                    177:     my $peerfile=shift;
                    178:     &logthis("Trying to reconnect for $peerfile");
                    179:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  180:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  181: 	my $loncpid=<$fh>;
                    182:         chomp($loncpid);
                    183:         if (kill 0 => $loncpid) {
                    184: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    185:             kill USR1 => $loncpid;
                    186:             sleep 1;
                    187:             if (-e "$peerfile") { return; }
                    188:             &logthis("$peerfile still not there, give it another try");
                    189:             sleep 5;
                    190:             if (-e "$peerfile") { return; }
1.12      www       191:             &logthis(
                    192:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  193:         } else {
1.12      www       194: 	    &logthis(
                    195:                "<font color=blue>WARNING:".
                    196:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  197:         }
                    198:     } else {
1.12      www       199:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
1.1       albertel  200:     }
                    201: }
                    202: 
                    203: # ------------------------------------------------------ Critical communication
1.12      www       204: 
1.1       albertel  205: sub critical {
                    206:     my ($cmd,$server)=@_;
1.89      www       207:     unless ($hostname{$server}) {
                    208:         &logthis("<font color=blue>WARNING:".
                    209:                " Critical message to unknown server ($server)</font>");
                    210:         return 'no_such_host';
                    211:     }
1.1       albertel  212:     my $answer=reply($cmd,$server);
                    213:     if ($answer eq 'con_lost') {
                    214: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  215: 	my $answer=reply($cmd,$server);
1.1       albertel  216:         if ($answer eq 'con_lost') {
                    217:             my $now=time;
                    218:             my $middlename=$cmd;
1.5       www       219:             $middlename=substr($middlename,0,16);
1.1       albertel  220:             $middlename=~s/\W//g;
                    221:             my $dfilename=
1.305     www       222:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    223:             $dumpcount++;
1.1       albertel  224:             {
1.448     albertel  225: 		my $dfh;
                    226: 		if (open($dfh,">$dfilename")) {
                    227: 		    print $dfh "$cmd\n"; 
                    228: 		    close($dfh);
                    229: 		}
1.1       albertel  230:             }
                    231:             sleep 2;
                    232:             my $wcmd='';
                    233:             {
1.448     albertel  234: 		my $dfh;
                    235: 		if (open($dfh,"<$dfilename")) {
                    236: 		    $wcmd=<$dfh>; 
                    237: 		    close($dfh);
                    238: 		}
1.1       albertel  239:             }
                    240:             chomp($wcmd);
1.7       www       241:             if ($wcmd eq $cmd) {
1.12      www       242: 		&logthis("<font color=blue>WARNING: ".
                    243:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  244:                 &logperm("D:$server:$cmd");
                    245: 	        return 'con_delayed';
                    246:             } else {
1.12      www       247:                 &logthis("<font color=red>CRITICAL:"
                    248:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  249:                 &logperm("F:$server:$cmd");
                    250:                 return 'con_failed';
                    251:             }
                    252:         }
                    253:     }
                    254:     return $answer;
1.405     albertel  255: }
                    256: 
1.374     www       257: # ------------------------------------------- Transfer profile into environment
                    258: 
                    259: sub transfer_profile_to_env {
                    260:     my ($lonidsdir,$handle)=@_;
                    261:     my @profile;
                    262:     {
1.448     albertel  263: 	open(my $idf,"$lonidsdir/$handle.id");
1.374     www       264: 	flock($idf,LOCK_SH);
                    265: 	@profile=<$idf>;
1.448     albertel  266: 	close($idf);
1.374     www       267:     }
                    268:     my $envi;
1.433     matthew   269:     my %Remove;
1.374     www       270:     for ($envi=0;$envi<=$#profile;$envi++) {
                    271: 	chomp($profile[$envi]);
                    272: 	my ($envname,$envvalue)=split(/=/,$profile[$envi]);
1.619     albertel  273: 	$env{$envname} = $envvalue;
1.433     matthew   274:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    275:             if ($time < time-300) {
                    276:                 $Remove{$key}++;
                    277:             }
                    278:         }
                    279:     }
1.619     albertel  280:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.433     matthew   281:     foreach my $expired_key (keys(%Remove)) {
                    282:         &delenv($expired_key);
1.374     www       283:     }
1.1       albertel  284: }
                    285: 
1.5       www       286: # ---------------------------------------------------------- Append Environment
                    287: 
                    288: sub appenv {
1.6       www       289:     my %newenv=@_;
1.191     harris41  290:     foreach (keys %newenv) {
1.35      www       291: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
                    292:             &logthis("<font color=blue>WARNING: ".
1.151     www       293:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
                    294:                 .'</font>');
1.35      www       295: 	    delete($newenv{$_});
                    296:         } else {
1.619     albertel  297:             $env{$_}=$newenv{$_};
1.35      www       298:         }
1.191     harris41  299:     }
1.95      www       300: 
                    301:     my $lockfh;
1.620     albertel  302:     unless (open($lockfh,"$env{'user.environment'}")) {
1.448     albertel  303: 	return 'error: '.$!;
1.95      www       304:     }
                    305:     unless (flock($lockfh,LOCK_EX)) {
                    306:          &logthis("<font color=blue>WARNING: ".
                    307:                   'Could not obtain exclusive lock in appenv: '.$!);
1.448     albertel  308:          close($lockfh);
1.95      www       309:          return 'error: '.$!;
                    310:     }
                    311: 
1.6       www       312:     my @oldenv;
                    313:     {
1.448     albertel  314: 	my $fh;
1.620     albertel  315: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  316: 	    return 'error: '.$!;
                    317: 	}
                    318: 	@oldenv=<$fh>;
                    319: 	close($fh);
1.6       www       320:     }
                    321:     for (my $i=0; $i<=$#oldenv; $i++) {
                    322:         chomp($oldenv[$i]);
1.9       www       323:         if ($oldenv[$i] ne '') {
1.448     albertel  324: 	    my ($name,$value)=split(/=/,$oldenv[$i]);
                    325: 	    unless (defined($newenv{$name})) {
                    326: 		$newenv{$name}=$value;
                    327: 	    }
1.9       www       328:         }
1.6       www       329:     }
                    330:     {
1.448     albertel  331: 	my $fh;
1.620     albertel  332: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  333: 	    return 'error';
                    334: 	}
                    335: 	my $newname;
                    336: 	foreach $newname (keys %newenv) {
                    337: 	    print $fh "$newname=$newenv{$newname}\n";
                    338: 	}
                    339: 	close($fh);
1.56      www       340:     }
1.448     albertel  341: 	
                    342:     close($lockfh);
1.56      www       343:     return 'ok';
                    344: }
                    345: # ----------------------------------------------------- Delete from Environment
                    346: 
                    347: sub delenv {
                    348:     my $delthis=shift;
                    349:     my %newenv=();
                    350:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
                    351:         &logthis("<font color=blue>WARNING: ".
                    352:                 "Attempt to delete from environment ".$delthis);
                    353:         return 'error';
                    354:     }
                    355:     my @oldenv;
                    356:     {
1.448     albertel  357: 	my $fh;
1.620     albertel  358: 	unless (open($fh,"$env{'user.environment'}")) {
1.448     albertel  359: 	    return 'error';
                    360: 	}
                    361: 	unless (flock($fh,LOCK_SH)) {
                    362: 	    &logthis("<font color=blue>WARNING: ".
                    363: 		     'Could not obtain shared lock in delenv: '.$!);
                    364: 	    close($fh);
                    365: 	    return 'error: '.$!;
                    366: 	}
                    367: 	@oldenv=<$fh>;
                    368: 	close($fh);
1.56      www       369:     }
                    370:     {
1.448     albertel  371: 	my $fh;
1.620     albertel  372: 	unless (open($fh,">$env{'user.environment'}")) {
1.448     albertel  373: 	    return 'error';
                    374: 	}
                    375: 	unless (flock($fh,LOCK_EX)) {
                    376: 	    &logthis("<font color=blue>WARNING: ".
                    377: 		     'Could not obtain exclusive lock in delenv: '.$!);
                    378: 	    close($fh);
                    379: 	    return 'error: '.$!;
                    380: 	}
                    381: 	foreach (@oldenv) {
1.473     matthew   382: 	    if ($_=~/^$delthis/) { 
                    383:                 my ($key,undef) = split('=',$_);
1.619     albertel  384:                 delete($env{$key});
1.473     matthew   385:             } else {
                    386:                 print $fh $_; 
                    387:             }
1.448     albertel  388: 	}
                    389: 	close($fh);
1.5       www       390:     }
                    391:     return 'ok';
1.369     albertel  392: }
                    393: 
                    394: # ------------------------------------------ Find out current server userload
                    395: # there is a copy in lond
                    396: sub userload {
                    397:     my $numusers=0;
                    398:     {
                    399: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    400: 	my $filename;
                    401: 	my $curtime=time;
                    402: 	while ($filename=readdir(LONIDS)) {
                    403: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  404: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  405: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  406: 	}
                    407: 	closedir(LONIDS);
                    408:     }
                    409:     my $userloadpercent=0;
                    410:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    411:     if ($maxuserload) {
1.371     albertel  412: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  413:     }
1.372     albertel  414:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  415:     return $userloadpercent;
1.283     www       416: }
                    417: 
                    418: # ------------------------------------------ Fight off request when overloaded
                    419: 
                    420: sub overloaderror {
                    421:     my ($r,$checkserver)=@_;
                    422:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    423:     my $loadavg;
                    424:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  425:        open(my $loadfile,'/proc/loadavg');
1.283     www       426:        $loadavg=<$loadfile>;
                    427:        $loadavg =~ s/\s.*//g;
1.285     matthew   428:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  429:        close($loadfile);
1.283     www       430:     } else {
                    431:        $loadavg=&reply('load',$checkserver);
                    432:     }
1.285     matthew   433:     my $overload=$loadavg-100;
1.283     www       434:     if ($overload>0) {
1.285     matthew   435: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       436:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       437:         return 413;
1.283     www       438:     }    
                    439:     return '';
1.5       www       440: }
1.1       albertel  441: 
                    442: # ------------------------------ Find server with least workload from spare.tab
1.11      www       443: 
1.1       albertel  444: sub spareserver {
1.370     albertel  445:     my ($loadpercent,$userloadpercent) = @_;
1.1       albertel  446:     my $tryserver;
                    447:     my $spareserver='';
1.370     albertel  448:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
                    449:     my $lowestserver=$loadpercent > $userloadpercent?
                    450: 	             $loadpercent :  $userloadpercent;
1.1       albertel  451:     foreach $tryserver (keys %spareid) {
1.411     albertel  452: 	my $loadans=reply('load',$tryserver);
                    453: 	my $userloadans=reply('userload',$tryserver);
                    454: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    455: 	    next; #didn't get a number from the server
                    456: 	}
                    457: 	my $answer;
                    458: 	if ($loadans =~ /\d/) {
                    459: 	    if ($userloadans =~ /\d/) {
                    460: 		#both are numbers, pick the bigger one
                    461: 		$answer=$loadans > $userloadans?
                    462: 		    $loadans :  $userloadans;
                    463: 	    } else {
                    464: 		$answer = $loadans;
                    465: 	    }
                    466: 	} else {
                    467: 	    $answer = $userloadans;
                    468: 	}
                    469: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
                    470: 	    $spareserver="http://$hostname{$tryserver}";
                    471: 	    $lowestserver=$answer;
                    472: 	}
1.370     albertel  473:     }
1.1       albertel  474:     return $spareserver;
1.202     matthew   475: }
                    476: 
                    477: # --------------------------------------------- Try to change a user's password
                    478: 
                    479: sub changepass {
                    480:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    481:     $currentpass = &escape($currentpass);
                    482:     $newpass     = &escape($newpass);
                    483:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    484: 		       $server);
                    485:     if (! $answer) {
                    486: 	&logthis("No reply on password change request to $server ".
                    487: 		 "by $uname in domain $udom.");
                    488:     } elsif ($answer =~ "^ok") {
                    489:         &logthis("$uname in $udom successfully changed their password ".
                    490: 		 "on $server.");
                    491:     } elsif ($answer =~ "^pwchange_failure") {
                    492: 	&logthis("$uname in $udom was unable to change their password ".
                    493: 		 "on $server.  The action was blocked by either lcpasswd ".
                    494: 		 "or pwchange");
                    495:     } elsif ($answer =~ "^non_authorized") {
                    496:         &logthis("$uname in $udom did not get their password correct when ".
                    497: 		 "attempting to change it on $server.");
                    498:     } elsif ($answer =~ "^auth_mode_error") {
                    499:         &logthis("$uname in $udom attempted to change their password despite ".
                    500: 		 "not being locally or internally authenticated on $server.");
                    501:     } elsif ($answer =~ "^unknown_user") {
                    502:         &logthis("$uname in $udom attempted to change their password ".
                    503: 		 "on $server but were unable to because $server is not ".
                    504: 		 "their home server.");
                    505:     } elsif ($answer =~ "^refused") {
                    506: 	&logthis("$server refused to change $uname in $udom password because ".
                    507: 		 "it was sent an unencrypted request to change the password.");
                    508:     }
                    509:     return $answer;
1.1       albertel  510: }
                    511: 
1.169     harris41  512: # ----------------------- Try to determine user's current authentication scheme
                    513: 
                    514: sub queryauthenticate {
                    515:     my ($uname,$udom)=@_;
1.456     albertel  516:     my $uhome=&homeserver($uname,$udom);
                    517:     if (!$uhome) {
                    518: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    519: 	return 'no_host';
                    520:     }
                    521:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    522:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    523: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  524:     }
1.456     albertel  525:     return $answer;
1.169     harris41  526: }
                    527: 
1.1       albertel  528: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       529: 
1.1       albertel  530: sub authenticate {
                    531:     my ($uname,$upass,$udom)=@_;
1.12      www       532:     $upass=escape($upass);
1.199     www       533:     $uname=~s/\W//g;
1.471     albertel  534:     my $uhome=&homeserver($uname,$udom);
                    535:     if (!$uhome) {
                    536: 	&logthis("User $uname at $udom is unknown in authenticate");
                    537: 	return 'no_host';
1.1       albertel  538:     }
1.471     albertel  539:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    540:     if ($answer eq 'authorized') {
                    541: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    542: 	return $uhome; 
                    543:     }
                    544:     if ($answer eq 'non_authorized') {
                    545: 	&logthis("User $uname at $udom rejected by $uhome");
                    546: 	return 'no_host'; 
1.9       www       547:     }
1.471     albertel  548:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  549:     return 'no_host';
                    550: }
                    551: 
                    552: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       553: 
1.599     albertel  554: my %homecache;
1.1       albertel  555: sub homeserver {
1.230     stredwic  556:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  557:     my $index="$uname:$udom";
1.426     albertel  558: 
1.599     albertel  559:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  560:     my $tryserver;
                    561:     foreach $tryserver (keys %libserv) {
1.230     stredwic  562:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  563: 		 exists($badServerCache{$tryserver}));
1.1       albertel  564: 	if ($hostdom{$tryserver} eq $udom) {
                    565:            my $answer=reply("home:$udom:$uname",$tryserver);
                    566:            if ($answer eq 'found') { 
1.599     albertel  567: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  568:            } elsif ($answer eq 'no_host') {
                    569: 	       $badServerCache{$tryserver}=1;
1.221     matthew   570:            }
1.1       albertel  571:        }
                    572:     }    
                    573:     return 'no_host';
1.70      www       574: }
                    575: 
                    576: # ------------------------------------- Find the usernames behind a list of IDs
                    577: 
                    578: sub idget {
                    579:     my ($udom,@ids)=@_;
                    580:     my %returnhash=();
                    581:     
                    582:     my $tryserver;
                    583:     foreach $tryserver (keys %libserv) {
                    584:        if ($hostdom{$tryserver} eq $udom) {
                    585: 	  my $idlist=join('&',@ids);
                    586:           $idlist=~tr/A-Z/a-z/; 
                    587: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    588:           my @answer=();
1.76      www       589:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       590: 	      @answer=split(/\&/,$reply);
                    591:           }                    ;
                    592:           my $i;
                    593:           for ($i=0;$i<=$#ids;$i++) {
                    594:               if ($answer[$i]) {
                    595: 		  $returnhash{$ids[$i]}=$answer[$i];
                    596:               } 
                    597:           }
                    598:        }
                    599:     }    
                    600:     return %returnhash;
                    601: }
                    602: 
                    603: # ------------------------------------- Find the IDs behind a list of usernames
                    604: 
                    605: sub idrget {
                    606:     my ($udom,@unames)=@_;
                    607:     my %returnhash=();
1.191     harris41  608:     foreach (@unames) {
1.70      www       609:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  610:     }
1.70      www       611:     return %returnhash;
                    612: }
                    613: 
                    614: # ------------------------------- Store away a list of names and associated IDs
                    615: 
                    616: sub idput {
                    617:     my ($udom,%ids)=@_;
                    618:     my %servers=();
1.191     harris41  619:     foreach (keys %ids) {
1.487     albertel  620: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       621:         my $uhom=&homeserver($_,$udom);
                    622:         if ($uhom ne 'no_host') {
                    623:             my $id=&escape($ids{$_});
                    624:             $id=~tr/A-Z/a-z/;
                    625:             my $unam=&escape($_);
                    626: 	    if ($servers{$uhom}) {
                    627: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    628:             } else {
                    629:                 $servers{$uhom}=$id.'='.$unam;
                    630:             }
                    631:         }
1.191     harris41  632:     }
                    633:     foreach (keys %servers) {
1.70      www       634:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  635:     }
1.344     www       636: }
                    637: 
                    638: # --------------------------------------------------- Assign a key to a student
                    639: 
                    640: sub assign_access_key {
1.364     www       641: #
                    642: # a valid key looks like uname:udom#comments
                    643: # comments are being appended
                    644: #
1.498     www       645:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    646:     $kdom=
1.620     albertel  647:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       648:     $knum=
1.620     albertel  649:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       650:     $cdom=
1.620     albertel  651:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       652:     $cnum=
1.620     albertel  653:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    654:     $udom=$env{'user.name'} unless (defined($udom));
                    655:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       656:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       657:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  658:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       659:                                                   # assigned to this person
                    660:                                                   # - this should not happen,
1.345     www       661:                                                   # unless something went wrong
                    662:                                                   # the first time around
                    663: # ready to assign
1.364     www       664:         $logentry=$1.'; '.$logentry;
1.496     www       665:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       666:                                                  $kdom,$knum) eq 'ok') {
1.345     www       667: # key now belongs to user
1.346     www       668: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       669:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    670:                 &appenv('environment.'.$envkey => $ckey);
                    671:                 return 'ok';
                    672:             } else {
                    673:                 return 
                    674:   'error: Count not permanently assign key, will need to be re-entered later.';
                    675: 	    }
                    676:         } else {
                    677:             return 'error: Could not assign key, try again later.';
                    678:         }
1.364     www       679:     } elsif (!$existing{$ckey}) {
1.345     www       680: # the key does not exist
                    681: 	return 'error: The key does not exist';
                    682:     } else {
                    683: # the key is somebody else's
                    684: 	return 'error: The key is already in use';
                    685:     }
1.344     www       686: }
                    687: 
1.364     www       688: # ------------------------------------------ put an additional comment on a key
                    689: 
                    690: sub comment_access_key {
                    691: #
                    692: # a valid key looks like uname:udom#comments
                    693: # comments are being appended
                    694: #
                    695:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    696:     $cdom=
1.620     albertel  697:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       698:     $cnum=
1.620     albertel  699:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       700:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    701:     if ($existing{$ckey}) {
                    702:         $existing{$ckey}.='; '.$logentry;
                    703: # ready to assign
1.367     www       704:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       705:                                                  $cdom,$cnum) eq 'ok') {
                    706: 	    return 'ok';
                    707:         } else {
                    708: 	    return 'error: Count not store comment.';
                    709:         }
                    710:     } else {
                    711: # the key does not exist
                    712: 	return 'error: The key does not exist';
                    713:     }
                    714: }
                    715: 
1.344     www       716: # ------------------------------------------------------ Generate a set of keys
                    717: 
                    718: sub generate_access_keys {
1.364     www       719:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       720:     $cdom=
1.620     albertel  721:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       722:     $cnum=
1.620     albertel  723:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       724:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       725:     unless (($cdom) && ($cnum)) { return 0; }
                    726:     if ($number>10000) { return 0; }
                    727:     sleep(2); # make sure don't get same seed twice
                    728:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    729:     my $total=0;
                    730:     for (my $i=1;$i<=$number;$i++) {
                    731:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    732:                   sprintf("%lx",int(100000*rand)).'-'.
                    733:                   sprintf("%lx",int(100000*rand));
                    734:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    735:        $newkey=~s/0/h/g; # and also 0 and O
                    736:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    737:        if ($existing{$newkey}) {
                    738:            $i--;
                    739:        } else {
1.364     www       740: 	  if (&put('accesskeys',
                    741:               { $newkey => '# generated '.localtime().
1.620     albertel  742:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       743:                            '; '.$logentry },
                    744: 		   $cdom,$cnum) eq 'ok') {
1.344     www       745:               $total++;
                    746: 	  }
                    747:        }
                    748:     }
1.620     albertel  749:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       750:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    751:     return $total;
                    752: }
                    753: 
                    754: # ------------------------------------------------------- Validate an accesskey
                    755: 
                    756: sub validate_access_key {
                    757:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    758:     $cdom=
1.620     albertel  759:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       760:     $cnum=
1.620     albertel  761:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    762:     $udom=$env{'user.domain'} unless (defined($udom));
                    763:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       764:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  765:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       766: }
                    767: 
                    768: # ------------------------------------- Find the section of student in a course
1.298     matthew   769: 
                    770: sub getsection {
                    771:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  772:     my $cachetime=1800;
1.298     matthew   773:     $courseid=~s/\_/\//g;
                    774:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  775: 
                    776:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  777:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  778:     if (defined($cached)) { return $result; }
                    779: 
1.298     matthew   780:     my %Pending; 
                    781:     my %Expired;
                    782:     #
                    783:     # Each role can either have not started yet (pending), be active, 
                    784:     #    or have expired.
                    785:     #
                    786:     # If there is an active role, we are done.
                    787:     #
                    788:     # If there is more than one role which has not started yet, 
                    789:     #     choose the one which will start sooner
                    790:     # If there is one role which has not started yet, return it.
                    791:     #
                    792:     # If there is more than one expired role, choose the one which ended last.
                    793:     # If there is a role which has expired, return it.
                    794:     #
                    795:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    796:                         &homeserver($unam,$udom)))) {
                    797:         my ($key,$value)=split(/\=/,$_);
                    798:         $key=&unescape($key);
1.479     albertel  799:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   800:         my $section=$1;
                    801:         if ($key eq $courseid.'_st') { $section=''; }
                    802:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    803:         my $now=time;
1.548     albertel  804:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   805:             $Expired{$end}=$section;
                    806:             next;
                    807:         }
1.548     albertel  808:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   809:             $Pending{$start}=$section;
                    810:             next;
                    811:         }
1.599     albertel  812:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   813:     }
                    814:     #
                    815:     # Presumedly there will be few matching roles from the above
                    816:     # loop and the sorting time will be negligible.
                    817:     if (scalar(keys(%Pending))) {
                    818:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  819:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   820:     } 
                    821:     if (scalar(keys(%Expired))) {
                    822:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    823:         my $time = pop(@sorted);
1.599     albertel  824:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   825:     }
1.599     albertel  826:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   827: }
1.70      www       828: 
1.599     albertel  829: sub save_cache {
1.628     albertel  830:     my ($r)=@_;
                    831:     if (! $r->is_initial_req()) { return DECLINED; }
1.599     albertel  832:     &purge_remembered();
1.620     albertel  833:     undef(%env);
1.628     albertel  834:     return OK;
1.599     albertel  835: }
1.452     albertel  836: 
1.599     albertel  837: my $to_remember=-1;
                    838: my %remembered;
                    839: my %accessed;
                    840: my $kicks=0;
                    841: my $hits=0;
                    842: sub devalidate_cache_new {
                    843:     my ($name,$id,$debug) = @_;
                    844:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    845:     $id=&escape($name.':'.$id);
                    846:     $memcache->delete($id);
                    847:     delete($remembered{$id});
                    848:     delete($accessed{$id});
                    849: }
                    850: 
                    851: sub is_cached_new {
                    852:     my ($name,$id,$debug) = @_;
                    853:     $id=&escape($name.':'.$id);
                    854:     if (exists($remembered{$id})) {
                    855: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    856: 	$accessed{$id}=[&gettimeofday()];
                    857: 	$hits++;
                    858: 	return ($remembered{$id},1);
                    859:     }
                    860:     my $value = $memcache->get($id);
                    861:     if (!(defined($value))) {
                    862: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  863: 	return (undef,undef);
1.416     albertel  864:     }
1.599     albertel  865:     if ($value eq '__undef__') {
                    866: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    867: 	$value=undef;
                    868:     }
                    869:     &make_room($id,$value,$debug);
                    870:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    871:     return ($value,1);
                    872: }
                    873: 
                    874: sub do_cache_new {
                    875:     my ($name,$id,$value,$time,$debug) = @_;
                    876:     $id=&escape($name.':'.$id);
                    877:     my $setvalue=$value;
                    878:     if (!defined($setvalue)) {
                    879: 	$setvalue='__undef__';
                    880:     }
1.623     albertel  881:     if (!defined($time) ) {
                    882: 	$time=600;
                    883:     }
1.599     albertel  884:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  885:     $memcache->set($id,$setvalue,$time);
                    886:     # need to make a copy of $value
                    887:     #&make_room($id,$value,$debug);
1.599     albertel  888:     return $value;
                    889: }
                    890: 
                    891: sub make_room {
                    892:     my ($id,$value,$debug)=@_;
                    893:     $remembered{$id}=$value;
                    894:     if ($to_remember<0) { return; }
                    895:     $accessed{$id}=[&gettimeofday()];
                    896:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    897:     my $to_kick;
                    898:     my $max_time=0;
                    899:     foreach my $other (keys(%accessed)) {
                    900: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    901: 	    $to_kick=$other;
                    902: 	    $max_time=&tv_interval($accessed{$other});
                    903: 	}
                    904:     }
                    905:     delete($remembered{$to_kick});
                    906:     delete($accessed{$to_kick});
                    907:     $kicks++;
                    908:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  909:     return;
                    910: }
                    911: 
1.599     albertel  912: sub purge_remembered {
1.604     albertel  913:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    914:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  915:     undef(%remembered);
                    916:     undef(%accessed);
1.428     albertel  917: }
1.70      www       918: # ------------------------------------- Read an entry from a user's environment
                    919: 
                    920: sub userenvironment {
                    921:     my ($udom,$unam,@what)=@_;
                    922:     my %returnhash=();
                    923:     my @answer=split(/\&/,
                    924:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    925:                       &homeserver($unam,$udom)));
                    926:     my $i;
                    927:     for ($i=0;$i<=$#what;$i++) {
                    928: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    929:     }
                    930:     return %returnhash;
1.1       albertel  931: }
                    932: 
1.617     albertel  933: # ---------------------------------------------------------- Get a studentphoto
                    934: sub studentphoto {
                    935:     my ($udom,$unam,$ext) = @_;
                    936:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                    937:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext",$home);
                    938:     my $url="/uploaded/$udom/$unam/internal/studentphoto.".$ext;
                    939:     if ($ret ne 'ok') {
                    940: 	return '/adm/lonKaputt/lonlogo_broken.gif';
                    941:     }
                    942:     my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                    943:     return $tokenurl;
                    944: }
                    945: 
1.263     www       946: # -------------------------------------------------------------------- New chat
                    947: 
                    948: sub chatsend {
                    949:     my ($newentry,$anon)=@_;
1.620     albertel  950:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                    951:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                    952:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www       953:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel  954: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.263     www       955: 		   &escape($newentry)),$chome);
1.292     www       956: }
                    957: 
                    958: # ------------------------------------------ Find current version of a resource
                    959: 
                    960: sub getversion {
                    961:     my $fname=&clutter(shift);
                    962:     unless ($fname=~/^\/res\//) { return -1; }
                    963:     return &currentversion(&filelocation('',$fname));
                    964: }
                    965: 
                    966: sub currentversion {
                    967:     my $fname=shift;
1.599     albertel  968:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www       969:     if (defined($cached)) { return $result; }
1.292     www       970:     my $author=$fname;
                    971:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    972:     my ($udom,$uname)=split(/\//,$author);
                    973:     my $home=homeserver($uname,$udom);
                    974:     if ($home eq 'no_host') { 
                    975:         return -1; 
                    976:     }
                    977:     my $answer=reply("currentversion:$fname",$home);
                    978:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    979: 	return -1;
                    980:     }
1.599     albertel  981:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www       982: }
                    983: 
1.1       albertel  984: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www       985: 
1.1       albertel  986: sub subscribe {
                    987:     my $fname=shift;
1.312     www       988:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel  989:     $fname=~s/[\n\r]//g;
1.1       albertel  990:     my $author=$fname;
                    991:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                    992:     my ($udom,$uname)=split(/\//,$author);
                    993:     my $home=homeserver($uname,$udom);
1.335     albertel  994:     if ($home eq 'no_host') {
                    995:         return 'not_found';
1.1       albertel  996:     }
                    997:     my $answer=reply("sub:$fname",$home);
1.64      www       998:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                    999: 	$answer.=' by '.$home;
                   1000:     }
1.1       albertel 1001:     return $answer;
                   1002: }
                   1003:     
1.8       www      1004: # -------------------------------------------------------------- Replicate file
                   1005: 
                   1006: sub repcopy {
                   1007:     my $filename=shift;
1.23      www      1008:     $filename=~s/\/+/\//g;
1.607     raeburn  1009:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1010:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1011:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1012: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1013: 	return &repcopy_userfile($filename);
                   1014:     }
1.532     albertel 1015:     $filename=~s/[\n\r]//g;
1.8       www      1016:     my $transname="$filename.in.transfer";
1.607     raeburn  1017:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1018:     my $remoteurl=subscribe($filename);
1.64      www      1019:     if ($remoteurl =~ /^con_lost by/) {
                   1020: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1021:            return 'unavailable';
1.8       www      1022:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1023: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1024: 	   return 'not_found';
1.64      www      1025:     } elsif ($remoteurl =~ /^rejected by/) {
                   1026: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1027:            return 'forbidden';
1.20      www      1028:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1029:            return 'ok';
1.8       www      1030:     } else {
1.290     www      1031:         my $author=$filename;
                   1032:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1033:         my ($udom,$uname)=split(/\//,$author);
                   1034:         my $home=homeserver($uname,$udom);
                   1035:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1036:            my @parts=split(/\//,$filename);
                   1037:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1038:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1039:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1040: 	       return 'bad_request';
1.8       www      1041:            }
                   1042:            my $count;
                   1043:            for ($count=5;$count<$#parts;$count++) {
                   1044:                $path.="/$parts[$count]";
                   1045:                if ((-e $path)!=1) {
                   1046: 		   mkdir($path,0777);
                   1047:                }
                   1048:            }
                   1049:            my $ua=new LWP::UserAgent;
                   1050:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1051:            my $response=$ua->request($request,$transname);
                   1052:            if ($response->is_error()) {
                   1053: 	       unlink($transname);
                   1054:                my $message=$response->status_line;
1.12      www      1055:                &logthis("<font color=blue>WARNING:"
                   1056:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1057:                return 'unavailable';
1.8       www      1058:            } else {
1.16      www      1059: 	       if ($remoteurl!~/\.meta$/) {
                   1060:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1061:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1062:                   if ($mresponse->is_error()) {
                   1063: 		      unlink($filename.'.meta');
                   1064:                       &logthis(
                   1065:                      "<font color=yellow>INFO: No metadata: $filename</font>");
                   1066:                   }
                   1067: 	       }
1.8       www      1068:                rename($transname,$filename);
1.607     raeburn  1069:                return 'ok';
1.8       www      1070:            }
1.290     www      1071:        }
1.8       www      1072:     }
1.330     www      1073: }
                   1074: 
                   1075: # ------------------------------------------------ Get server side include body
                   1076: sub ssi_body {
1.381     albertel 1077:     my ($filelink,%form)=@_;
1.606     matthew  1078:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1079:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1080:     }
1.330     www      1081:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1082:                                      &ssi($filelink,%form));
1.565     albertel 1083:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1084:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1085:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1086:     return $output;
1.8       www      1087: }
                   1088: 
1.15      www      1089: # --------------------------------------------------------- Server Side Include
                   1090: 
                   1091: sub ssi {
                   1092: 
1.23      www      1093:     my ($fn,%form)=@_;
1.15      www      1094: 
                   1095:     my $ua=new LWP::UserAgent;
1.23      www      1096:     
                   1097:     my $request;
                   1098:     
                   1099:     if (%form) {
                   1100:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
1.201     albertel 1101:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1102:     } else {
                   1103:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
                   1104:     }
                   1105: 
1.15      www      1106:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1107:     my $response=$ua->request($request);
                   1108: 
1.324     www      1109:     return $response->content;
                   1110: }
                   1111: 
                   1112: sub externalssi {
                   1113:     my ($url)=@_;
                   1114:     my $ua=new LWP::UserAgent;
                   1115:     my $request=new HTTP::Request('GET',$url);
                   1116:     my $response=$ua->request($request);
1.15      www      1117:     return $response->content;
                   1118: }
1.254     www      1119: 
1.492     albertel 1120: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1121: 
                   1122: sub allowuploaded {
                   1123:     my ($srcurl,$url)=@_;
                   1124:     $url=&clutter(&declutter($url));
                   1125:     my $dir=$url;
                   1126:     $dir=~s/\/[^\/]+$//;
                   1127:     my %httpref=();
                   1128:     my $httpurl=&hreflocation('',$url);
                   1129:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1130:     &Apache::lonnet::appenv(%httpref);
1.254     www      1131: }
1.477     raeburn  1132: 
1.478     albertel 1133: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
                   1134: # input: action, courseID, current domain, home server for course, intended
                   1135: #        path to file, source of file.
1.485     raeburn  1136: # output: url to file (if action was uploaddoc), 
                   1137: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1138: #
1.478     albertel 1139: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1140: # course.
1.477     raeburn  1141: #
1.478     albertel 1142: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1143: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1144: #          course's home server.
1.477     raeburn  1145: #
1.478     albertel 1146: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1147: #          be copied from $source (current location) to 
                   1148: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1149: #         and will then be copied to
                   1150: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1151: #         course's home server.
1.485     raeburn  1152: #
1.481     raeburn  1153: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1154: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1155: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1156: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1157: #         in course's home server.
                   1158: 
1.477     raeburn  1159: 
                   1160: sub process_coursefile {
                   1161:     my ($action,$docuname,$docudom,$docuhome,$file,$source)=@_;
                   1162:     my $fetchresult;
                   1163:     if ($action eq 'propagate') {
                   1164:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file
                   1165:                             ,$docuhome);
1.481     raeburn  1166:     } else {
1.477     raeburn  1167:         my $fetchresult = '';
                   1168:         my $fpath = '';
                   1169:         my $fname = $file;
1.478     albertel 1170:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1171:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1172:         my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1173:         unless ($fpath eq '') {
1.478     albertel 1174:             my @parts=split('/',$fpath);
1.477     raeburn  1175:             foreach my $part (@parts) {
                   1176:                 $filepath.= '/'.$part;
                   1177:                 if ((-e $filepath)!=1) {
                   1178:                     mkdir($filepath,0777);
                   1179:                 }
                   1180:             }
                   1181:         }
1.481     raeburn  1182:         if ($action eq 'copy') {
                   1183:             if ($source eq '') {
                   1184:                 $fetchresult = 'no source file';
                   1185:                 return $fetchresult;
                   1186:             } else {
                   1187:                 my $destination = $filepath.'/'.$fname;
                   1188:                 rename($source,$destination);
                   1189:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1190:                                  $docuhome);
                   1191:             }
                   1192:         } elsif ($action eq 'uploaddoc') {
                   1193:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1194:             print $fh $env{'form.'.$source};
1.481     raeburn  1195:             close($fh);
1.477     raeburn  1196:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1197:                                  $docuhome);
1.481     raeburn  1198:             if ($fetchresult eq 'ok') {
                   1199:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1200:             } else {
                   1201:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1202:                         ' to host '.$docuhome.': '.$fetchresult);
                   1203:                 return '/adm/notfound.html';
                   1204:             }
1.477     raeburn  1205:         }
                   1206:     }
1.485     raeburn  1207:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1208:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1209:              ' to host '.$docuhome.': '.$fetchresult);
                   1210:     }
                   1211:     return $fetchresult;
                   1212: }
                   1213: 
1.531     albertel 1214: sub clean_filename {
                   1215:     my ($fname)=@_;
1.315     www      1216: # Replace Windows backslashes by forward slashes
1.257     www      1217:     $fname=~s/\\/\//g;
1.315     www      1218: # Get rid of everything but the actual filename
1.257     www      1219:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1220: # Replace spaces by underscores
                   1221:     $fname=~s/\s+/\_/g;
                   1222: # Replace all other weird characters by nothing
1.317     www      1223:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1224: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1225: # numbers
                   1226:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1227:     return $fname;
                   1228: }
                   1229: 
1.608     albertel 1230: # --------------- Take an uploaded file and put it into the userfiles directory
                   1231: # input: name of form element, coursedoc=1 means this is for the course
                   1232: # output: url of file in userspace
                   1233: 
                   1234: 
1.531     albertel 1235: sub userfileupload {
                   1236:     my ($formname,$coursedoc,$subdir)=@_;
                   1237:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1238:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1239:     $fname=&clean_filename($fname);
1.315     www      1240: # See if there is anything left
1.257     www      1241:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1242:     chop($env{'form.'.$formname});
1.523     raeburn  1243:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1244:         my $now = time;
                   1245:         my $filepath = 'tmp/helprequests/'.$now;
                   1246:         my @parts=split(/\//,$filepath);
                   1247:         my $fullpath = $perlvar{'lonDaemons'};
                   1248:         for (my $i=0;$i<@parts;$i++) {
                   1249:             $fullpath .= '/'.$parts[$i];
                   1250:             if ((-e $fullpath)!=1) {
                   1251:                 mkdir($fullpath,0777);
                   1252:             }
                   1253:         }
                   1254:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1255:         print $fh $env{'form.'.$formname};
1.523     raeburn  1256:         close($fh);
                   1257:         return $fullpath.'/'.$fname; 
                   1258:     }
1.258     www      1259: # Create the directory if not present
1.259     www      1260:     my $docuname='';
                   1261:     my $docudom='';
                   1262:     my $docuhome='';
1.493     albertel 1263:     $fname="$subdir/$fname";
1.259     www      1264:     if ($coursedoc) {
1.620     albertel 1265: 	$docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1266: 	$docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1267: 	$docuhome=$env{'course.'.$env{'request.course.id'}.'.home'};
                   1268:         if ($env{'form.folder'} =~ m/^default/) {
1.485     raeburn  1269:             return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
1.481     raeburn  1270:         } else {
1.620     albertel 1271:             $fname=$env{'form.folder'}.'/'.$fname;
1.485     raeburn  1272:             return &process_coursefile('uploaddoc',$docuname,$docudom,$docuhome,$fname,$formname);
1.481     raeburn  1273:         }
1.259     www      1274:     } else {
1.620     albertel 1275:         $docuname=$env{'user.name'};
                   1276:         $docudom=$env{'user.domain'};
                   1277:         $docuhome=$env{'user.home'};
1.485     raeburn  1278:         return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
1.259     www      1279:     }
1.271     www      1280: }
                   1281: 
                   1282: sub finishuserfileupload {
1.477     raeburn  1283:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
                   1284:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1285:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1286:     my ($fnamepath,$file);
                   1287:     $file=$fname;
                   1288:     if ($fname=~m|/|) {
                   1289:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1290: 	$path.=$fnamepath.'/';
                   1291:     }
1.259     www      1292:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1293:     my $count;
                   1294:     for ($count=4;$count<=$#parts;$count++) {
                   1295:         $filepath.="/$parts[$count]";
                   1296:         if ((-e $filepath)!=1) {
                   1297: 	    mkdir($filepath,0777);
                   1298:         }
                   1299:     }
                   1300: # Save the file
                   1301:     {
1.570     albertel 1302: 	open(FH,'>'.$filepath.'/'.$file);
1.620     albertel 1303: 	print FH $env{'form.'.$formname};
1.570     albertel 1304: 	close(FH);
1.258     www      1305:     }
1.259     www      1306: # Notify homeserver to grep it
                   1307: #
1.494     albertel 1308:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1309:     if ($fetchresult eq 'ok') {
1.259     www      1310: #
1.258     www      1311: # Return the URL to it
1.494     albertel 1312:         return '/uploaded/'.$path.$file;
1.263     www      1313:     } else {
1.494     albertel 1314:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1315: 		 ': '.$fetchresult);
1.263     www      1316:         return '/adm/notfound.html';
                   1317:     }    
1.493     albertel 1318: }
                   1319: 
                   1320: sub removeuploadedurl {
                   1321:     my ($url)=@_;
                   1322:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1323:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1324: }
                   1325: 
                   1326: sub removeuserfile {
                   1327:     my ($docuname,$docudom,$fname)=@_;
                   1328:     my $home=&homeserver($docuname,$docudom);
                   1329:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1330: }
1.15      www      1331: 
1.530     albertel 1332: sub mkdiruserfile {
                   1333:     my ($docuname,$docudom,$dir)=@_;
                   1334:     my $home=&homeserver($docuname,$docudom);
                   1335:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1336: }
                   1337: 
1.531     albertel 1338: sub renameuserfile {
                   1339:     my ($docuname,$docudom,$old,$new)=@_;
                   1340:     my $home=&homeserver($docuname,$docudom);
                   1341:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1342: 		  &escape("$new"),$home);
                   1343: }
                   1344: 
1.14      www      1345: # ------------------------------------------------------------------------- Log
                   1346: 
                   1347: sub log {
                   1348:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1349:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1350: }
                   1351: 
                   1352: # ------------------------------------------------------------------ Course Log
1.352     www      1353: #
                   1354: # This routine flushes several buffers of non-mission-critical nature
                   1355: #
1.157     www      1356: 
                   1357: sub flushcourselogs {
1.352     www      1358:     &logthis('Flushing log buffers');
                   1359: #
                   1360: # course logs
                   1361: # This is a log of all transactions in a course, which can be used
                   1362: # for data mining purposes
                   1363: #
                   1364: # It also collects the courseid database, which lists last transaction
                   1365: # times and course titles for all courseids
                   1366: #
                   1367:     my %courseidbuffer=();
1.191     harris41 1368:     foreach (keys %courselogs) {
1.157     www      1369:         my $crsid=$_;
1.352     www      1370:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1371: 		          &escape($courselogs{$crsid}),
                   1372: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1373: 	    delete $courselogs{$crsid};
                   1374:         } else {
                   1375:             &logthis('Failed to flush log buffer for '.$crsid);
                   1376:             if (length($courselogs{$crsid})>40000) {
                   1377:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
                   1378:                         " exceeded maximum size, deleting.</font>");
                   1379:                delete $courselogs{$crsid};
                   1380:             }
1.352     www      1381:         }
                   1382:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1383:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1384: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1385:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
1.352     www      1386:         } else {
                   1387:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1388: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.571     raeburn  1389:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
                   1390:         }
1.191     harris41 1391:     }
1.352     www      1392: #
                   1393: # Write course id database (reverse lookup) to homeserver of courses 
                   1394: # Is used in pickcourse
                   1395: #
                   1396:     foreach (keys %courseidbuffer) {
1.353     www      1397:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1398:     }
                   1399: #
                   1400: # File accesses
                   1401: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1402: #
1.449     matthew  1403:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1404:         if ($entry =~ /___count$/) {
                   1405:             my ($dom,$name);
                   1406:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1407:             if (! defined($dom) || $dom eq '' || 
                   1408:                 ! defined($name) || $name eq '') {
1.620     albertel 1409:                 my $cid = $env{'request.course.id'};
                   1410:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1411:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1412:             }
1.450     matthew  1413:             my $value = $accesshash{$entry};
                   1414:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1415:             my %temphash=($url => $value);
1.449     matthew  1416:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1417:             if ($result eq 'ok') {
                   1418:                 delete $accesshash{$entry};
                   1419:             } elsif ($result eq 'unknown_cmd') {
                   1420:                 # Target server has old code running on it.
1.450     matthew  1421:                 my %temphash=($entry => $value);
1.449     matthew  1422:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1423:                     delete $accesshash{$entry};
                   1424:                 }
                   1425:             }
                   1426:         } else {
1.458     matthew  1427:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1428:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1429:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1430:                 delete $accesshash{$entry};
                   1431:             }
1.185     www      1432:         }
1.191     harris41 1433:     }
1.352     www      1434: #
                   1435: # Roles
                   1436: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1437: #
1.349     www      1438:     foreach (keys %userrolehash) {
                   1439:         my $entry=$_;
1.351     www      1440:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1441: 	    split(/\:/,$entry);
                   1442:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1443:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1444:                 $rudom,$runame) eq 'ok') {
                   1445: 	    delete $userrolehash{$entry};
                   1446:         }
                   1447:     }
1.186     www      1448:     $dumpcount++;
1.157     www      1449: }
                   1450: 
                   1451: sub courselog {
                   1452:     my $what=shift;
1.158     www      1453:     $what=time.':'.$what;
1.620     albertel 1454:     unless ($env{'request.course.id'}) { return ''; }
                   1455:     $coursedombuf{$env{'request.course.id'}}=
                   1456:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1457:     $coursenumbuf{$env{'request.course.id'}}=
                   1458:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1459:     $coursehombuf{$env{'request.course.id'}}=
                   1460:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1461:     $coursedescrbuf{$env{'request.course.id'}}=
                   1462:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1463:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1464:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1465:     $courseownerbuf{$env{'request.course.id'}}=
                   1466:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   1467:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1468: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1469:     } else {
1.620     albertel 1470: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1471:     }
1.620     albertel 1472:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1473: 	&flushcourselogs();
                   1474:     }
1.158     www      1475: }
                   1476: 
                   1477: sub courseacclog {
                   1478:     my $fnsymb=shift;
1.620     albertel 1479:     unless ($env{'request.course.id'}) { return ''; }
                   1480:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.408     www      1481:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) {
1.187     www      1482:         $what.=':POST';
1.583     matthew  1483:         # FIXME: Probably ought to escape things....
1.620     albertel 1484: 	foreach (keys %env) {
1.158     www      1485:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1486: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1487:             }
1.191     harris41 1488:         }
1.583     matthew  1489:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1490:         # FIXME: We should not be depending on a form parameter that someone
                   1491:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1492:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1493:             $what.= ':POST';
                   1494:             # FIXME: Probably ought to escape things....
                   1495:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1496:                                  'crsdiscuss') {
1.620     albertel 1497:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1498:             }
                   1499:         }
1.158     www      1500:     }
                   1501:     &courselog($what);
1.149     www      1502: }
                   1503: 
1.185     www      1504: sub countacc {
                   1505:     my $url=&declutter(shift);
1.458     matthew  1506:     return if (! defined($url) || $url eq '');
1.620     albertel 1507:     unless ($env{'request.course.id'}) { return ''; }
                   1508:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1509:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1510:     $accesshash{$key}++;
1.185     www      1511: }
1.349     www      1512: 
1.361     www      1513: sub linklog {
                   1514:     my ($from,$to)=@_;
                   1515:     $from=&declutter($from);
                   1516:     $to=&declutter($to);
                   1517:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1518:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1519: }
                   1520:   
1.349     www      1521: sub userrolelog {
                   1522:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
                   1523:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
                   1524:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.469     www      1525:         ($trole=~/^cr/) || ($trole=~/^ta/)) {
1.350     www      1526:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1527:        $userrolehash
                   1528:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1529:                     =$tend.':'.$tstart;
                   1530:    }
1.351     www      1531: }
                   1532: 
                   1533: sub get_course_adv_roles {
                   1534:     my $cid=shift;
1.620     albertel 1535:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1536:     my %coursehash=&coursedescription($cid);
1.470     www      1537:     my %nothide=();
                   1538:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1539: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1540:     }
1.351     www      1541:     my %returnhash=();
                   1542:     my %dumphash=
                   1543:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1544:     my $now=time;
                   1545:     foreach (keys %dumphash) {
                   1546: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1547:         if (($tstart) && ($tstart<0)) { next; }
                   1548:         if (($tend) && ($tend<$now)) { next; }
                   1549:         if (($tstart) && ($now<$tstart)) { next; }
                   1550:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1551: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1552: 	if ((&privileged($username,$domain)) && 
                   1553: 	    (!$nothide{$username.':'.$domain})) { next; }
1.351     www      1554:         my $key=&plaintext($role);
                   1555:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1556:         if ($returnhash{$key}) {
                   1557: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1558:         } else {
                   1559:             $returnhash{$key}=$username.':'.$domain;
                   1560:         }
1.400     www      1561:      }
                   1562:     return %returnhash;
                   1563: }
                   1564: 
                   1565: sub get_my_roles {
                   1566:     my ($uname,$udom)=@_;
1.620     albertel 1567:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1568:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1569:     my %dumphash=
                   1570:             &dump('nohist_userroles',$udom,$uname);
                   1571:     my %returnhash=();
                   1572:     my $now=time;
                   1573:     foreach (keys %dumphash) {
                   1574: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1575:         if (($tstart) && ($tstart<0)) { next; }
                   1576:         if (($tend) && ($tend<$now)) { next; }
                   1577:         if (($tstart) && ($now<$tstart)) { next; }
                   1578:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1579: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1580:      }
                   1581:     return %returnhash;
1.399     www      1582: }
                   1583: 
                   1584: # ----------------------------------------------------- Frontpage Announcements
                   1585: #
                   1586: #
                   1587: 
                   1588: sub postannounce {
                   1589:     my ($server,$text)=@_;
                   1590:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1591:     unless ($text=~/\w/) { $text=''; }
                   1592:     return &reply('setannounce:'.&escape($text),$server);
                   1593: }
                   1594: 
                   1595: sub getannounce {
1.448     albertel 1596: 
                   1597:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1598: 	my $announcement='';
                   1599: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1600: 	close($fh);
1.399     www      1601: 	if ($announcement=~/\w/) { 
                   1602: 	    return 
                   1603:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1604:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1605: 	} else {
                   1606: 	    return '';
                   1607: 	}
                   1608:     } else {
                   1609: 	return '';
                   1610:     }
1.351     www      1611: }
1.353     www      1612: 
                   1613: # ---------------------------------------------------------- Course ID routines
                   1614: # Deal with domain's nohist_courseid.db files
                   1615: #
                   1616: 
                   1617: sub courseidput {
                   1618:     my ($domain,$what,$coursehome)=@_;
                   1619:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1620: }
                   1621: 
                   1622: sub courseiddump {
1.622     raeburn  1623:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
1.353     www      1624:     my %returnhash=();
1.355     www      1625:     unless ($domfilter) { $domfilter=''; }
1.353     www      1626:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1627:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1628: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1629: 	        foreach (
                   1630:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1631: 			       $sincefilter.':'.&escape($descfilter).':'.
1.622     raeburn  1632:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
1.354     www      1633:                                $tryserver))) {
1.506     raeburn  1634: 		    my ($key,$value)=split(/\=/,$_);
                   1635:                     if (($key) && ($value)) {
1.516     raeburn  1636: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1637:                     }
1.353     www      1638:                 }
                   1639:             }
                   1640:         }
                   1641:     }
                   1642:     return %returnhash;
                   1643: }
                   1644: 
                   1645: #
1.149     www      1646: # ----------------------------------------------------------- Check out an item
                   1647: 
1.504     albertel 1648: sub get_first_access {
                   1649:     my ($type,$argsymb)=@_;
                   1650:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   1651:     if ($argsymb) { $symb=$argsymb; }
                   1652:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 1653:     if ($type eq 'map') {
                   1654: 	$res=&symbread($map);
                   1655:     } else {
                   1656: 	$res=$symb;
                   1657:     }
                   1658:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   1659:     return $times{"$courseid\0$res"};
1.504     albertel 1660: }
                   1661: 
                   1662: sub set_first_access {
                   1663:     my ($type)=@_;
                   1664:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
                   1665:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 1666:     if ($type eq 'map') {
                   1667: 	$res=&symbread($map);
                   1668:     } else {
                   1669: 	$res=$symb;
                   1670:     }
                   1671:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 1672:     if (!$firstaccess) {
1.588     albertel 1673: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 1674:     }
                   1675:     return 'already_set';
1.504     albertel 1676: }
                   1677: 
1.149     www      1678: sub checkout {
                   1679:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   1680:     my $now=time;
                   1681:     my $lonhost=$perlvar{'lonHostID'};
                   1682:     my $infostr=&escape(
1.234     www      1683:                  'CHECKOUTTOKEN&'.
1.149     www      1684:                  $tuname.'&'.
                   1685:                  $tudom.'&'.
                   1686:                  $tcrsid.'&'.
                   1687:                  $symb.'&'.
                   1688: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   1689:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      1690:     if ($token=~/^error\:/) { 
                   1691:         &logthis("<font color=blue>WARNING: ".
                   1692:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1693:                  "</font>");
                   1694:         return ''; 
                   1695:     }
                   1696: 
1.149     www      1697:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   1698:     $token=~tr/a-z/A-Z/;
                   1699: 
1.153     www      1700:     my %infohash=('resource.0.outtoken' => $token,
                   1701:                   'resource.0.checkouttime' => $now,
                   1702:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      1703: 
                   1704:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1705:        return '';
1.151     www      1706:     } else {
                   1707:         &logthis("<font color=blue>WARNING: ".
                   1708:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1709:                  "</font>");
1.149     www      1710:     }    
                   1711: 
                   1712:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1713:                          &escape('Checkout '.$infostr.' - '.
                   1714:                                                  $token)) ne 'ok') {
                   1715: 	return '';
1.151     www      1716:     } else {
                   1717:         &logthis("<font color=blue>WARNING: ".
                   1718:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   1719:                  "</font>");
1.149     www      1720:     }
1.151     www      1721:     return $token;
1.149     www      1722: }
                   1723: 
                   1724: # ------------------------------------------------------------ Check in an item
                   1725: 
                   1726: sub checkin {
                   1727:     my $token=shift;
1.150     www      1728:     my $now=time;
                   1729:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   1730:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 1731:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      1732:     $dtoken=~s/\W/\_/g;
1.234     www      1733:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      1734:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   1735: 
1.154     www      1736:     unless (($tuname) && ($tudom)) {
                   1737:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   1738:         return '';
                   1739:     }
                   1740:     
                   1741:     unless (&allowed('mgr',$tcrsid)) {
                   1742:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 1743:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      1744:         return '';
                   1745:     }
                   1746: 
1.153     www      1747:     my %infohash=('resource.0.intoken' => $token,
                   1748:                   'resource.0.checkintime' => $now,
                   1749:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      1750: 
                   1751:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   1752:        return '';
                   1753:     }    
                   1754: 
                   1755:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   1756:                          &escape('Checkin - '.$token)) ne 'ok') {
                   1757: 	return '';
                   1758:     }
                   1759: 
                   1760:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      1761: }
                   1762: 
                   1763: # --------------------------------------------- Set Expire Date for Spreadsheet
                   1764: 
                   1765: sub expirespread {
                   1766:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 1767:     my $cid=$env{'request.course.id'}; 
1.110     www      1768:     if ($cid) {
                   1769:        my $now=time;
                   1770:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 1771:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   1772:                             $env{'course.'.$cid.'.num'}.
1.110     www      1773: 	        	    ':nohist_expirationdates:'.
                   1774:                             &escape($key).'='.$now,
1.620     albertel 1775:                             $env{'course.'.$cid.'.home'})
1.110     www      1776:     }
                   1777:     return 'ok';
1.14      www      1778: }
                   1779: 
1.109     www      1780: # ----------------------------------------------------- Devalidate Spreadsheets
                   1781: 
                   1782: sub devalidate {
1.325     www      1783:     my ($symb,$uname,$udom)=@_;
1.620     albertel 1784:     my $cid=$env{'request.course.id'}; 
1.109     www      1785:     if ($cid) {
1.391     matthew  1786:         # delete the stored spreadsheets for
                   1787:         # - the student level sheet of this user in course's homespace
                   1788:         # - the assessment level sheet for this resource 
                   1789:         #   for this user in user's homespace
1.553     albertel 1790: 	# - current conditional state info
1.325     www      1791: 	my $key=$uname.':'.$udom.':';
1.109     www      1792:         my $status=
1.299     matthew  1793: 	    &del('nohist_calculatedsheets',
1.391     matthew  1794: 		 [$key.'studentcalc:'],
1.620     albertel 1795: 		 $env{'course.'.$cid.'.domain'},
                   1796: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 1797: 		.' '.
                   1798: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  1799: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      1800:         unless ($status eq 'ok ok') {
                   1801:            &logthis('Could not devalidate spreadsheet '.
1.325     www      1802:                     $uname.' at '.$udom.' for '.
1.109     www      1803: 		    $symb.': '.$status);
1.133     albertel 1804:         }
1.553     albertel 1805: 	&delenv('user.state.'.$cid);
1.109     www      1806:     }
                   1807: }
                   1808: 
1.265     albertel 1809: sub get_scalar {
                   1810:     my ($string,$end) = @_;
                   1811:     my $value;
                   1812:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   1813: 	$value = $1;
                   1814:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   1815: 	$value = $1;
                   1816:     }
                   1817:     return &unescape($value);
                   1818: }
                   1819: 
                   1820: sub array2str {
                   1821:   my (@array) = @_;
                   1822:   my $result=&arrayref2str(\@array);
                   1823:   $result=~s/^__ARRAY_REF__//;
                   1824:   $result=~s/__END_ARRAY_REF__$//;
                   1825:   return $result;
                   1826: }
                   1827: 
1.204     albertel 1828: sub arrayref2str {
                   1829:   my ($arrayref) = @_;
1.265     albertel 1830:   my $result='__ARRAY_REF__';
1.204     albertel 1831:   foreach my $elem (@$arrayref) {
1.265     albertel 1832:     if(ref($elem) eq 'ARRAY') {
                   1833:       $result.=&arrayref2str($elem).'&';
                   1834:     } elsif(ref($elem) eq 'HASH') {
                   1835:       $result.=&hashref2str($elem).'&';
                   1836:     } elsif(ref($elem)) {
                   1837:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 1838:     } else {
                   1839:       $result.=&escape($elem).'&';
                   1840:     }
                   1841:   }
                   1842:   $result=~s/\&$//;
1.265     albertel 1843:   $result .= '__END_ARRAY_REF__';
1.204     albertel 1844:   return $result;
                   1845: }
                   1846: 
1.168     albertel 1847: sub hash2str {
1.204     albertel 1848:   my (%hash) = @_;
                   1849:   my $result=&hashref2str(\%hash);
1.265     albertel 1850:   $result=~s/^__HASH_REF__//;
                   1851:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 1852:   return $result;
                   1853: }
                   1854: 
                   1855: sub hashref2str {
                   1856:   my ($hashref)=@_;
1.265     albertel 1857:   my $result='__HASH_REF__';
1.495     albertel 1858:   foreach (sort(keys(%$hashref))) {
1.204     albertel 1859:     if (ref($_) eq 'ARRAY') {
1.265     albertel 1860:       $result.=&arrayref2str($_).'=';
1.204     albertel 1861:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 1862:       $result.=&hashref2str($_).'=';
1.204     albertel 1863:     } elsif (ref($_)) {
1.265     albertel 1864:       $result.='=';
                   1865:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 1866:     } else {
1.265     albertel 1867: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 1868:     }
                   1869: 
1.265     albertel 1870:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   1871:       $result.=&arrayref2str($hashref->{$_}).'&';
                   1872:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   1873:       $result.=&hashref2str($hashref->{$_}).'&';
                   1874:     } elsif(ref($hashref->{$_})) {
                   1875:        $result.='&';
                   1876:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 1877:     } else {
1.265     albertel 1878:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 1879:     }
                   1880:   }
1.168     albertel 1881:   $result=~s/\&$//;
1.265     albertel 1882:   $result .= '__END_HASH_REF__';
1.168     albertel 1883:   return $result;
                   1884: }
                   1885: 
                   1886: sub str2hash {
1.265     albertel 1887:     my ($string)=@_;
                   1888:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   1889:     return %$hash;
                   1890: }
                   1891: 
                   1892: sub str2hashref {
1.168     albertel 1893:   my ($string) = @_;
1.265     albertel 1894: 
                   1895:   my %hash;
                   1896: 
                   1897:   if($string !~ /^__HASH_REF__/) {
                   1898:       if (! ($string eq '' || !defined($string))) {
                   1899: 	  $hash{'error'}='Not hash reference';
                   1900:       }
                   1901:       return (\%hash, $string);
                   1902:   }
                   1903: 
                   1904:   $string =~ s/^__HASH_REF__//;
                   1905: 
                   1906:   while($string !~ /^__END_HASH_REF__/) {
                   1907:       #key
                   1908:       my $key='';
                   1909:       if($string =~ /^__HASH_REF__/) {
                   1910:           ($key, $string)=&str2hashref($string);
                   1911:           if(defined($key->{'error'})) {
                   1912:               $hash{'error'}='Bad data';
                   1913:               return (\%hash, $string);
                   1914:           }
                   1915:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1916:           ($key, $string)=&str2arrayref($string);
                   1917:           if($key->[0] eq 'Array reference error') {
                   1918:               $hash{'error'}='Bad data';
                   1919:               return (\%hash, $string);
                   1920:           }
                   1921:       } else {
                   1922:           $string =~ s/^(.*?)=//;
1.267     albertel 1923: 	  $key=&unescape($1);
1.265     albertel 1924:       }
                   1925:       $string =~ s/^=//;
                   1926: 
                   1927:       #value
                   1928:       my $value='';
                   1929:       if($string =~ /^__HASH_REF__/) {
                   1930:           ($value, $string)=&str2hashref($string);
                   1931:           if(defined($value->{'error'})) {
                   1932:               $hash{'error'}='Bad data';
                   1933:               return (\%hash, $string);
                   1934:           }
                   1935:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1936:           ($value, $string)=&str2arrayref($string);
                   1937:           if($value->[0] eq 'Array reference error') {
                   1938:               $hash{'error'}='Bad data';
                   1939:               return (\%hash, $string);
                   1940:           }
                   1941:       } else {
                   1942: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   1943:       }
                   1944:       $string =~ s/^&//;
                   1945: 
                   1946:       $hash{$key}=$value;
1.204     albertel 1947:   }
1.265     albertel 1948: 
                   1949:   $string =~ s/^__END_HASH_REF__//;
                   1950: 
                   1951:   return (\%hash, $string);
1.204     albertel 1952: }
                   1953: 
                   1954: sub str2array {
1.265     albertel 1955:     my ($string)=@_;
                   1956:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   1957:     return @$array;
                   1958: }
                   1959: 
                   1960: sub str2arrayref {
1.204     albertel 1961:   my ($string) = @_;
1.265     albertel 1962:   my @array;
                   1963: 
                   1964:   if($string !~ /^__ARRAY_REF__/) {
                   1965:       if (! ($string eq '' || !defined($string))) {
                   1966: 	  $array[0]='Array reference error';
                   1967:       }
                   1968:       return (\@array, $string);
                   1969:   }
                   1970: 
                   1971:   $string =~ s/^__ARRAY_REF__//;
                   1972: 
                   1973:   while($string !~ /^__END_ARRAY_REF__/) {
                   1974:       my $value='';
                   1975:       if($string =~ /^__HASH_REF__/) {
                   1976:           ($value, $string)=&str2hashref($string);
                   1977:           if(defined($value->{'error'})) {
                   1978:               $array[0] ='Array reference error';
                   1979:               return (\@array, $string);
                   1980:           }
                   1981:       } elsif($string =~ /^__ARRAY_REF__/) {
                   1982:           ($value, $string)=&str2arrayref($string);
                   1983:           if($value->[0] eq 'Array reference error') {
                   1984:               $array[0] ='Array reference error';
                   1985:               return (\@array, $string);
                   1986:           }
                   1987:       } else {
                   1988: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   1989:       }
                   1990:       $string =~ s/^&//;
                   1991: 
                   1992:       push(@array, $value);
1.191     harris41 1993:   }
1.265     albertel 1994: 
                   1995:   $string =~ s/^__END_ARRAY_REF__//;
                   1996: 
                   1997:   return (\@array, $string);
1.168     albertel 1998: }
                   1999: 
1.167     albertel 2000: # -------------------------------------------------------------------Temp Store
                   2001: 
1.168     albertel 2002: sub tmpreset {
                   2003:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2004:   if (!$symb) {
                   2005:     $symb=&symbread();
1.620     albertel 2006:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2007:   }
                   2008:   $symb=escape($symb);
                   2009: 
1.620     albertel 2010:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2011:   $namespace=~s/\//\_/g;
                   2012:   $namespace=~s/\W//g;
                   2013: 
1.620     albertel 2014:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2015:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2016:   if ($domain eq 'public' && $stuname eq 'public') {
                   2017:       $stuname=$ENV{'REMOTE_ADDR'};
                   2018:   }
1.168     albertel 2019:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2020:   my %hash;
                   2021:   if (tie(%hash,'GDBM_File',
                   2022: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2023: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2024:     foreach my $key (keys %hash) {
1.180     albertel 2025:       if ($key=~ /:$symb/) {
1.168     albertel 2026: 	delete($hash{$key});
                   2027:       }
                   2028:     }
                   2029:   }
                   2030: }
                   2031: 
1.167     albertel 2032: sub tmpstore {
1.168     albertel 2033:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2034: 
                   2035:   if (!$symb) {
                   2036:     $symb=&symbread();
1.620     albertel 2037:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2038:   }
                   2039:   $symb=escape($symb);
                   2040: 
                   2041:   if (!$namespace) {
                   2042:     # I don't think we would ever want to store this for a course.
                   2043:     # it seems this will only be used if we don't have a course.
1.620     albertel 2044:     #$namespace=$env{'request.course.id'};
1.168     albertel 2045:     #if (!$namespace) {
1.620     albertel 2046:       $namespace=$env{'request.state'};
1.168     albertel 2047:     #}
                   2048:   }
                   2049:   $namespace=~s/\//\_/g;
                   2050:   $namespace=~s/\W//g;
1.620     albertel 2051:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2052:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2053:   if ($domain eq 'public' && $stuname eq 'public') {
                   2054:       $stuname=$ENV{'REMOTE_ADDR'};
                   2055:   }
1.168     albertel 2056:   my $now=time;
                   2057:   my %hash;
                   2058:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2059:   if (tie(%hash,'GDBM_File',
                   2060: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2061: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2062:     $hash{"version:$symb"}++;
                   2063:     my $version=$hash{"version:$symb"};
                   2064:     my $allkeys=''; 
                   2065:     foreach my $key (keys(%$storehash)) {
                   2066:       $allkeys.=$key.':';
1.591     albertel 2067:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2068:     }
                   2069:     $hash{"$version:$symb:timestamp"}=$now;
                   2070:     $allkeys.='timestamp';
                   2071:     $hash{"$version:keys:$symb"}=$allkeys;
                   2072:     if (untie(%hash)) {
                   2073:       return 'ok';
                   2074:     } else {
                   2075:       return "error:$!";
                   2076:     }
                   2077:   } else {
                   2078:     return "error:$!";
                   2079:   }
                   2080: }
1.167     albertel 2081: 
1.168     albertel 2082: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2083: 
1.168     albertel 2084: sub tmprestore {
                   2085:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2086: 
1.168     albertel 2087:   if (!$symb) {
                   2088:     $symb=&symbread();
1.620     albertel 2089:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2090:   }
                   2091:   $symb=escape($symb);
                   2092: 
1.620     albertel 2093:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2094: 
1.620     albertel 2095:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2096:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2097:   if ($domain eq 'public' && $stuname eq 'public') {
                   2098:       $stuname=$ENV{'REMOTE_ADDR'};
                   2099:   }
1.168     albertel 2100:   my %returnhash;
                   2101:   $namespace=~s/\//\_/g;
                   2102:   $namespace=~s/\W//g;
                   2103:   my %hash;
                   2104:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2105:   if (tie(%hash,'GDBM_File',
                   2106: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2107: 	  &GDBM_READER(),0640)) {
1.168     albertel 2108:     my $version=$hash{"version:$symb"};
                   2109:     $returnhash{'version'}=$version;
                   2110:     my $scope;
                   2111:     for ($scope=1;$scope<=$version;$scope++) {
                   2112:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2113:       my @keys=split(/:/,$vkeys);
                   2114:       my $key;
                   2115:       $returnhash{"$scope:keys"}=$vkeys;
                   2116:       foreach $key (@keys) {
1.591     albertel 2117: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2118: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2119:       }
                   2120:     }
1.168     albertel 2121:     if (!(untie(%hash))) {
                   2122:       return "error:$!";
                   2123:     }
                   2124:   } else {
                   2125:     return "error:$!";
                   2126:   }
                   2127:   return %returnhash;
1.167     albertel 2128: }
                   2129: 
1.9       www      2130: # ----------------------------------------------------------------------- Store
                   2131: 
                   2132: sub store {
1.124     www      2133:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2134:     my $home='';
                   2135: 
1.168     albertel 2136:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2137: 
1.213     www      2138:     $symb=&symbclean($symb);
1.122     albertel 2139:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2140: 
1.620     albertel 2141:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2142:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2143: 
                   2144:     &devalidate($symb,$stuname,$domain);
1.109     www      2145: 
                   2146:     $symb=escape($symb);
1.187     www      2147:     if (!$namespace) { 
1.620     albertel 2148:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2149:           return ''; 
                   2150:        } 
                   2151:     }
1.620     albertel 2152:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2153: 
                   2154:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2155:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2156: 
1.12      www      2157:     my $namevalue='';
1.191     harris41 2158:     foreach (keys %$storehash) {
1.591     albertel 2159:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2160:     }
1.12      www      2161:     $namevalue=~s/\&$//;
1.187     www      2162:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2163:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2164: }
                   2165: 
1.47      www      2166: # -------------------------------------------------------------- Critical Store
                   2167: 
                   2168: sub cstore {
1.124     www      2169:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2170:     my $home='';
                   2171: 
1.168     albertel 2172:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2173: 
1.213     www      2174:     $symb=&symbclean($symb);
1.122     albertel 2175:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2176: 
1.620     albertel 2177:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2178:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2179: 
                   2180:     &devalidate($symb,$stuname,$domain);
1.109     www      2181: 
                   2182:     $symb=escape($symb);
1.187     www      2183:     if (!$namespace) { 
1.620     albertel 2184:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2185:           return ''; 
                   2186:        } 
                   2187:     }
1.620     albertel 2188:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2189: 
                   2190:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2191:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2192: 
1.47      www      2193:     my $namevalue='';
1.191     harris41 2194:     foreach (keys %$storehash) {
1.591     albertel 2195:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2196:     }
1.47      www      2197:     $namevalue=~s/\&$//;
1.187     www      2198:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2199:     return critical
                   2200:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2201: }
                   2202: 
1.9       www      2203: # --------------------------------------------------------------------- Restore
                   2204: 
                   2205: sub restore {
1.124     www      2206:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2207:     my $home='';
                   2208: 
1.168     albertel 2209:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2210: 
1.122     albertel 2211:     if (!$symb) {
                   2212:       unless ($symb=escape(&symbread())) { return ''; }
                   2213:     } else {
1.213     www      2214:       $symb=&escape(&symbclean($symb));
1.122     albertel 2215:     }
1.188     www      2216:     if (!$namespace) { 
1.620     albertel 2217:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2218:           return ''; 
                   2219:        } 
                   2220:     }
1.620     albertel 2221:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2222:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2223:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2224:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2225: 
1.12      www      2226:     my %returnhash=();
1.191     harris41 2227:     foreach (split(/\&/,$answer)) {
1.12      www      2228: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2229:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2230:     }
1.75      www      2231:     my $version;
                   2232:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2233:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2234:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2235:        }
1.75      www      2236:     }
1.13      www      2237:     return %returnhash;
1.34      www      2238: }
                   2239: 
                   2240: # ---------------------------------------------------------- Course Description
                   2241: 
                   2242: sub coursedescription {
                   2243:     my $courseid=shift;
                   2244:     $courseid=~s/^\///;
1.49      www      2245:     $courseid=~s/\_/\//g;
1.34      www      2246:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2247:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2248:     my $normalid=$cdomain.'_'.$cnum;
                   2249:     # need to always cache even if we get errors otherwise we keep 
                   2250:     # trying and trying and trying to get the course description.
                   2251:     my %envhash=();
                   2252:     my %returnhash=();
                   2253:     $envhash{'course.'.$normalid.'.last_cache'}=time;
1.34      www      2254:     if ($chome ne 'no_host') {
1.302     albertel 2255:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2256:        if (!exists($returnhash{'con_lost'})) {
                   2257:            $returnhash{'home'}= $chome;
                   2258: 	   $returnhash{'domain'} = $cdomain;
                   2259: 	   $returnhash{'num'} = $cnum;
1.130     albertel 2260:            while (my ($name,$value) = each %returnhash) {
1.53      www      2261:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2262:            }
1.270     www      2263:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2264:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2265: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2266:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2267:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2268:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2269:        }
                   2270:     }
1.302     albertel 2271:     &appenv(%envhash);
                   2272:     return %returnhash;
1.461     www      2273: }
                   2274: 
                   2275: # -------------------------------------------------See if a user is privileged
                   2276: 
                   2277: sub privileged {
                   2278:     my ($username,$domain)=@_;
                   2279:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2280: 			&homeserver($username,$domain));
                   2281:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2282:     my $now=time;
                   2283:     if ($rolesdump ne '') {
                   2284:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2285: 	    if ($_!~/^rolesdef_/) {
1.461     www      2286: 		my ($area,$role)=split(/=/,$_);
                   2287: 		$area=~s/\_\w\w$//;
                   2288: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2289: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2290: 		    my $active=1;
                   2291: 		    if ($tend) {
                   2292: 			if ($tend<$now) { $active=0; }
                   2293: 		    }
                   2294: 		    if ($tstart) {
                   2295: 			if ($tstart>$now) { $active=0; }
                   2296: 		    }
                   2297: 		    if ($active) { return 1; }
                   2298: 		}
                   2299: 	    }
                   2300: 	}
                   2301:     }
                   2302:     return 0;
1.9       www      2303: }
1.1       albertel 2304: 
1.103     harris41 2305: # -------------------------------------------------------- Get user privileges
1.11      www      2306: 
                   2307: sub rolesinit {
                   2308:     my ($domain,$username,$authhost)=@_;
                   2309:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2310:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2311:     my %allroles=();
                   2312:     my $now=time;
1.21      www      2313:     my $userroles="user.login.time=$now\n";
1.11      www      2314: 
                   2315:     if ($rolesdump ne '') {
1.191     harris41 2316:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2317: 	  if ($_!~/^rolesdef_/) {
1.11      www      2318:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2319: 	    $area=~s/\_\w\w$//;
                   2320: 	    
                   2321:             my ($trole,$tend,$tstart);
                   2322: 	    if ($role=~/^cr/) { 
                   2323: 		($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2324: 		($tend,$tstart)=split('_',$trest);
                   2325: 	    } else {
                   2326: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2327: 	    }
1.576     albertel 2328:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
1.567     raeburn  2329:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2330:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2331:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2332: 		my $spec=$trole.'.'.$area;
                   2333: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2334: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2335:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.347     albertel 2336: 		} else {
1.567     raeburn  2337:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2338: 		}
1.12      www      2339:             }
                   2340:           } 
1.191     harris41 2341:         }
1.567     raeburn  2342:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles);
1.128     www      2343:         $userroles.='user.adv='.$adv."\n".
                   2344: 	            'user.author='.$author."\n";
1.620     albertel 2345:         $env{'user.adv'}=$adv;
1.11      www      2346:     }
                   2347:     return $userroles;  
                   2348: }
                   2349: 
1.567     raeburn  2350: sub set_arearole {
                   2351:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2352: # log the associated role with the area
                   2353:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   2354:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
                   2355: }
                   2356: 
                   2357: sub custom_roleprivs {
                   2358:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2359:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2360:     my $homsvr=homeserver($rauthor,$rdomain);
                   2361:     if ($hostname{$homsvr} ne '') {
                   2362:         my ($rdummy,$roledef)=
                   2363:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2364:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2365:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2366:             if (defined($syspriv)) {
                   2367:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2368:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2369:             }
                   2370:             if ($tdomain ne '') {
                   2371:                 if (defined($dompriv)) {
                   2372:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2373:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2374:                 }
                   2375:                 if (($trest ne '') && (defined($coursepriv))) {
                   2376:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2377:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2378:                 }
                   2379:             }
                   2380:         }
                   2381:     }
                   2382: }
                   2383: 
                   2384: 
                   2385: sub standard_roleprivs {
                   2386:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2387:     if (defined($pr{$trole.':s'})) {
                   2388:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2389:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2390:     }
                   2391:     if ($tdomain ne '') {
                   2392:         if (defined($pr{$trole.':d'})) {
                   2393:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2394:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2395:         }
                   2396:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2397:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2398:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2399:         }
                   2400:     }
                   2401: }
                   2402: 
                   2403: sub set_userprivs {
                   2404:     my ($userroles,$allroles) = @_; 
                   2405:     my $author=0;
                   2406:     my $adv=0;
                   2407:     foreach (keys %{$allroles}) {
                   2408:         my %thesepriv=();
                   2409:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2410:         foreach (split(/:/,$$allroles{$_})) {
                   2411:             if ($_ ne '') {
                   2412:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2413:                 if ($restrictions eq '') {
                   2414:                     $thesepriv{$privilege}='F';
                   2415:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2416:                     $thesepriv{$privilege}.=$restrictions;
                   2417:                 }
                   2418:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2419:             }
                   2420:         }
                   2421:         my $thesestr='';
                   2422:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
                   2423:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
                   2424:     }
                   2425:     return ($author,$adv);
                   2426: }
                   2427: 
1.12      www      2428: # --------------------------------------------------------------- get interface
                   2429: 
                   2430: sub get {
1.131     albertel 2431:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2432:    my $items='';
1.191     harris41 2433:    foreach (@$storearr) {
1.12      www      2434:        $items.=escape($_).'&';
1.191     harris41 2435:    }
1.12      www      2436:    $items=~s/\&$//;
1.620     albertel 2437:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2438:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2439:    my $uhome=&homeserver($uname,$udomain);
                   2440: 
1.133     albertel 2441:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2442:    my @pairs=split(/\&/,$rep);
1.273     albertel 2443:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2444:      return @pairs;
                   2445:    }
1.15      www      2446:    my %returnhash=();
1.42      www      2447:    my $i=0;
1.191     harris41 2448:    foreach (@$storearr) {
1.557     albertel 2449:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2450:       $i++;
1.191     harris41 2451:    }
1.15      www      2452:    return %returnhash;
1.27      www      2453: }
                   2454: 
                   2455: # --------------------------------------------------------------- del interface
                   2456: 
                   2457: sub del {
1.133     albertel 2458:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2459:    my $items='';
1.191     harris41 2460:    foreach (@$storearr) {
1.27      www      2461:        $items.=escape($_).'&';
1.191     harris41 2462:    }
1.27      www      2463:    $items=~s/\&$//;
1.620     albertel 2464:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2465:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2466:    my $uhome=&homeserver($uname,$udomain);
                   2467: 
                   2468:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2469: }
                   2470: 
                   2471: # -------------------------------------------------------------- dump interface
                   2472: 
                   2473: sub dump {
1.193     www      2474:    my ($namespace,$udomain,$uname,$regexp)=@_;
1.620     albertel 2475:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2476:    if (!$uname) { $uname=$env{'user.name'}; }
1.129     albertel 2477:    my $uhome=&homeserver($uname,$udomain);
1.193     www      2478:    if ($regexp) {
                   2479:        $regexp=&escape($regexp);
                   2480:    } else {
                   2481:        $regexp='.';
                   2482:    }
                   2483:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
1.12      www      2484:    my @pairs=split(/\&/,$rep);
                   2485:    my %returnhash=();
1.191     harris41 2486:    foreach (@pairs) {
1.12      www      2487:       my ($key,$value)=split(/=/,$_);
1.557     albertel 2488:       $returnhash{unescape($key)}=&thaw_unescape($value);
1.318     matthew  2489:    }
                   2490:    return %returnhash;
1.407     www      2491: }
                   2492: 
                   2493: # -------------------------------------------------------------- keys interface
                   2494: 
                   2495: sub getkeys {
                   2496:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2497:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2498:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2499:    my $uhome=&homeserver($uname,$udomain);
                   2500:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2501:    my @keyarray=();
                   2502:    foreach (split(/\&/,$rep)) {
                   2503:       push (@keyarray,&unescape($_));
                   2504:    }
                   2505:    return @keyarray;
1.318     matthew  2506: }
                   2507: 
1.319     matthew  2508: # --------------------------------------------------------------- currentdump
                   2509: sub currentdump {
1.328     matthew  2510:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2511:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2512:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2513:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2514:    my $uhome = &homeserver($sname,$sdom);
                   2515:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2516:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  2517:    #
1.318     matthew  2518:    my %returnhash=();
1.319     matthew  2519:    #
                   2520:    if ($rep eq "unknown_cmd") { 
                   2521:        # an old lond will not know currentdump
                   2522:        # Do a dump and make it look like a currentdump
1.326     matthew  2523:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  2524:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   2525:        my %hash = @tmp;
                   2526:        @tmp=();
1.424     matthew  2527:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  2528:    } else {
                   2529:        my @pairs=split(/\&/,$rep);
                   2530:        foreach (@pairs) {
                   2531:            my ($key,$value)=split(/=/,$_);
                   2532:            my ($symb,$param) = split(/:/,$key);
                   2533:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 2534:                                                         &thaw_unescape($value);
1.319     matthew  2535:        }
1.191     harris41 2536:    }
1.12      www      2537:    return %returnhash;
1.424     matthew  2538: }
                   2539: 
                   2540: sub convert_dump_to_currentdump{
                   2541:     my %hash = %{shift()};
                   2542:     my %returnhash;
                   2543:     # Code ripped from lond, essentially.  The only difference
                   2544:     # here is the unescaping done by lonnet::dump().  Conceivably
                   2545:     # we might run in to problems with parameter names =~ /^v\./
                   2546:     while (my ($key,$value) = each(%hash)) {
                   2547:         my ($v,$symb,$param) = split(/:/,$key);
                   2548:         next if ($v eq 'version' || $symb eq 'keys');
                   2549:         next if (exists($returnhash{$symb}) &&
                   2550:                  exists($returnhash{$symb}->{$param}) &&
                   2551:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   2552:         $returnhash{$symb}->{$param}=$value;
                   2553:         $returnhash{$symb}->{'v.'.$param}=$v;
                   2554:     }
                   2555:     #
                   2556:     # Remove all of the keys in the hashes which keep track of
                   2557:     # the version of the parameter.
                   2558:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   2559:         # use a foreach because we are going to delete from the hash.
                   2560:         foreach my $key (keys(%$param_hash)) {
                   2561:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   2562:         }
                   2563:     }
                   2564:     return \%returnhash;
1.12      www      2565: }
                   2566: 
1.627     albertel 2567: # ------------------------------------------------------ critical inc interface
                   2568: 
                   2569: sub cinc {
                   2570:     return &inc(@_,'critical');
                   2571: }
                   2572: 
1.449     matthew  2573: # --------------------------------------------------------------- inc interface
                   2574: 
                   2575: sub inc {
1.627     albertel 2576:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 2577:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2578:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  2579:     my $uhome=&homeserver($uname,$udomain);
                   2580:     my $items='';
                   2581:     if (! ref($store)) {
                   2582:         # got a single value, so use that instead
                   2583:         $items = &escape($store).'=&';
                   2584:     } elsif (ref($store) eq 'SCALAR') {
                   2585:         $items = &escape($$store).'=&';        
                   2586:     } elsif (ref($store) eq 'ARRAY') {
                   2587:         $items = join('=&',map {&escape($_);} @{$store});
                   2588:     } elsif (ref($store) eq 'HASH') {
                   2589:         while (my($key,$value) = each(%{$store})) {
                   2590:             $items.= &escape($key).'='.&escape($value).'&';
                   2591:         }
                   2592:     }
                   2593:     $items=~s/\&$//;
1.627     albertel 2594:     if ($critical) {
                   2595: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2596:     } else {
                   2597: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2598:     }
1.449     matthew  2599: }
                   2600: 
1.12      www      2601: # --------------------------------------------------------------- put interface
                   2602: 
                   2603: sub put {
1.134     albertel 2604:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2605:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2606:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 2607:    my $uhome=&homeserver($uname,$udomain);
1.12      www      2608:    my $items='';
1.191     harris41 2609:    foreach (keys %$storehash) {
1.557     albertel 2610:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2611:    }
1.12      www      2612:    $items=~s/\&$//;
1.134     albertel 2613:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      2614: }
                   2615: 
1.631     albertel 2616: # ------------------------------------------------------------ newput interface
                   2617: 
                   2618: sub newput {
                   2619:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2620:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2621:    if (!$uname) { $uname=$env{'user.name'}; }
                   2622:    my $uhome=&homeserver($uname,$udomain);
                   2623:    my $items='';
                   2624:    foreach my $key (keys(%$storehash)) {
                   2625:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2626:    }
                   2627:    $items=~s/\&$//;
                   2628:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   2629: }
                   2630: 
                   2631: # ---------------------------------------------------------  putstore interface
                   2632: 
1.524     raeburn  2633: sub putstore {
                   2634:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2635:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2636:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  2637:    my $uhome=&homeserver($uname,$udomain);
                   2638:    my $items='';
                   2639:    my %allitems = ();
                   2640:    foreach (keys %$storehash) {
                   2641:        if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   2642:            my $key = $1.':keys:'.$2;
                   2643:            $allitems{$key} .= $3.':';
                   2644:        }
1.591     albertel 2645:        $items.=$_.'='.&freeze_escape($$storehash{$_}).'&';
1.524     raeburn  2646:    }
                   2647:    foreach (keys %allitems) {
                   2648:        $allitems{$_} =~ s/\:$//;
                   2649:        $items.= $_.'='.$allitems{$_}.'&';
                   2650:    }
                   2651:    $items=~s/\&$//;
                   2652:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   2653: }
                   2654: 
1.47      www      2655: # ------------------------------------------------------ critical put interface
                   2656: 
                   2657: sub cput {
1.134     albertel 2658:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 2659:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2660:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 2661:    my $uhome=&homeserver($uname,$udomain);
1.47      www      2662:    my $items='';
1.191     harris41 2663:    foreach (keys %$storehash) {
1.557     albertel 2664:        $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2665:    }
1.47      www      2666:    $items=~s/\&$//;
1.134     albertel 2667:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2668: }
                   2669: 
                   2670: # -------------------------------------------------------------- eget interface
                   2671: 
                   2672: sub eget {
1.133     albertel 2673:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2674:    my $items='';
1.191     harris41 2675:    foreach (@$storearr) {
1.12      www      2676:        $items.=escape($_).'&';
1.191     harris41 2677:    }
1.12      www      2678:    $items=~s/\&$//;
1.620     albertel 2679:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2680:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2681:    my $uhome=&homeserver($uname,$udomain);
                   2682:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2683:    my @pairs=split(/\&/,$rep);
                   2684:    my %returnhash=();
1.42      www      2685:    my $i=0;
1.191     harris41 2686:    foreach (@$storearr) {
1.557     albertel 2687:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2688:       $i++;
1.191     harris41 2689:    }
1.12      www      2690:    return %returnhash;
                   2691: }
                   2692: 
1.341     www      2693: # ---------------------------------------------- Custom access rule evaluation
                   2694: 
                   2695: sub customaccess {
                   2696:     my ($priv,$uri)=@_;
1.620     albertel 2697:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      2698:     $urealm=~s/^\W//;
                   2699:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      2700:     my $access=0;
                   2701:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      2702: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      2703:         if ($role) {
                   2704: 	   if ($role ne $urole) { next; }
                   2705:         }
                   2706:         foreach (split(/\s*\,\s*/,$realm)) {
                   2707:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   2708:             if ($tdom) {
                   2709: 		if ($tdom ne $udom) { next; }
                   2710:             }
                   2711:             if ($tcrs) {
                   2712: 		if ($tcrs ne $ucrs) { next; }
                   2713:             }
                   2714:             if ($tsec) {
                   2715: 		if ($tsec ne $usec) { next; }
                   2716:             }
                   2717:             $access=($effect eq 'allow');
                   2718:             last;
1.342     www      2719:         }
1.402     bowersj2 2720: 	if ($realm eq '' && $role eq '') {
                   2721:             $access=($effect eq 'allow');
                   2722: 	}
1.341     www      2723:     }
                   2724:     return $access;
                   2725: }
                   2726: 
1.103     harris41 2727: # ------------------------------------------------- Check for a user privilege
1.12      www      2728: 
                   2729: sub allowed {
1.579     albertel 2730:     my ($priv,$uri,$symb)=@_;
1.439     www      2731:     $uri=&deversion($uri);
1.152     www      2732:     my $orguri=$uri;
1.52      www      2733:     $uri=&declutter($uri);
1.545     banghart 2734:     
                   2735:     
                   2736:     
1.620     albertel 2737:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      2738: # Free bre access to adm and meta resources
1.529     albertel 2739:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   2740: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      2741: 	return 'F';
1.159     www      2742:     }
                   2743: 
1.545     banghart 2744: # Free bre access to user's own portfolio contents
1.546     albertel 2745:     my ($space,$domain,$name,$dir)=split('/',$uri);
1.620     albertel 2746:     if (($space=~/^(uploaded|ediupload)$/) && ($env{'user.name'} eq $name) && 
                   2747: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
1.545     banghart 2748:         return 'F';
                   2749:     }
                   2750: 
1.159     www      2751: # Free bre to public access
                   2752: 
                   2753:     if ($priv eq 'bre') {
1.238     www      2754:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 2755: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      2756:            return 'F'; 
                   2757:         }
1.238     www      2758:         if ($copyright eq 'priv') {
                   2759:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 2760: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      2761: 		return '';
                   2762:             }
                   2763:         }
                   2764:         if ($copyright eq 'domain') {
                   2765:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 2766: 	    unless (($env{'user.domain'} eq $1) ||
                   2767:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      2768: 		return '';
                   2769:             }
1.262     matthew  2770:         }
1.620     albertel 2771:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  2772:             # Library role, so allow browsing of resources in this domain.
                   2773:             return 'F';
1.238     www      2774:         }
1.341     www      2775:         if ($copyright eq 'custom') {
                   2776: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   2777:         }
1.14      www      2778:     }
1.264     matthew  2779:     # Domain coordinator is trying to create a course
1.620     albertel 2780:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  2781:         # uri is the requested domain in this case.
                   2782:         # comparison to 'request.role.domain' shows if the user has selected
                   2783:         # a role of dc for the domain in question. 
1.620     albertel 2784:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  2785:     }
1.29      www      2786: 
1.52      www      2787:     my $thisallowed='';
                   2788:     my $statecond=0;
                   2789:     my $courseprivid='';
                   2790: 
                   2791: # Course
                   2792: 
1.620     albertel 2793:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      2794:        $thisallowed.=$1;
                   2795:     }
1.29      www      2796: 
1.52      www      2797: # Domain
                   2798: 
1.620     albertel 2799:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 2800:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      2801:        $thisallowed.=$1;
                   2802:     }
1.52      www      2803: 
                   2804: # Course: uri itself is a course
1.66      www      2805:     my $courseuri=$uri;
                   2806:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      2807:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      2808: 
1.620     albertel 2809:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 2810:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      2811:        $thisallowed.=$1;
                   2812:     }
1.29      www      2813: 
1.314     www      2814: # URI is an uploaded document for this course
1.611     albertel 2815: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 2816:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.620     albertel 2817: 	my $refuri=$env{'httpref.'.$orguri};
1.492     albertel 2818: 	if ($refuri) {
                   2819: 	    if ($refuri =~ m|^/adm/|) {
                   2820: 		$thisallowed='F';
                   2821: 	    }
                   2822: 	}
1.314     www      2823:     }
1.492     albertel 2824: 
1.52      www      2825: # Full access at system, domain or course-wide level? Exit.
1.29      www      2826: 
                   2827:     if ($thisallowed=~/F/) {
                   2828: 	return 'F';
                   2829:     }
                   2830: 
1.52      www      2831: # If this is generating or modifying users, exit with special codes
1.29      www      2832: 
1.479     albertel 2833:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:\Q$priv\E\:/) {
1.52      www      2834: 	return $thisallowed;
                   2835:     }
                   2836: #
1.103     harris41 2837: # Gathered so far: system, domain and course wide privileges
1.52      www      2838: #
                   2839: # Course: See if uri or referer is an individual resource that is part of 
                   2840: # the course
                   2841: 
1.620     albertel 2842:     if ($env{'request.course.id'}) {
1.232     www      2843: 
1.620     albertel 2844:        $courseprivid=$env{'request.course.id'};
                   2845:        if ($env{'request.course.sec'}) {
                   2846:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      2847:        }
                   2848:        $courseprivid=~s/\_/\//;
                   2849:        my $checkreferer=1;
1.232     www      2850:        my ($match,$cond)=&is_on_map($uri);
                   2851:        if ($match) {
                   2852:            $statecond=$cond;
1.620     albertel 2853:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 2854:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      2855:                $thisallowed.=$1;
                   2856:                $checkreferer=0;
                   2857:            }
1.29      www      2858:        }
1.83      www      2859:        
1.148     www      2860:        if ($checkreferer) {
1.620     albertel 2861: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      2862:             unless ($refuri) {
1.620     albertel 2863:                 foreach (keys %env) {
1.148     www      2864: 		    if ($_=~/^httpref\..*\*/) {
                   2865: 			my $pattern=$_;
1.156     www      2866:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      2867:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   2868:                         $pattern=~s/\//\\\//g;
1.152     www      2869:                         if ($orguri=~/$pattern/) {
1.620     albertel 2870: 			    $refuri=$env{$_};
1.148     www      2871:                         }
                   2872:                     }
1.191     harris41 2873:                 }
1.148     www      2874:             }
1.232     www      2875: 
1.148     www      2876:          if ($refuri) { 
1.152     www      2877: 	  $refuri=&declutter($refuri);
1.232     www      2878:           my ($match,$cond)=&is_on_map($refuri);
                   2879:             if ($match) {
                   2880:               my $refstatecond=$cond;
1.620     albertel 2881:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 2882:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      2883:                   $thisallowed.=$1;
1.53      www      2884:                   $uri=$refuri;
                   2885:                   $statecond=$refstatecond;
1.52      www      2886:               }
                   2887:           }
1.148     www      2888:         }
1.29      www      2889:        }
1.52      www      2890:    }
1.29      www      2891: 
1.52      www      2892: #
1.103     harris41 2893: # Gathered now: all privileges that could apply, and condition number
1.52      www      2894: # 
                   2895: #
                   2896: # Full or no access?
                   2897: #
1.29      www      2898: 
1.52      www      2899:     if ($thisallowed=~/F/) {
                   2900: 	return 'F';
                   2901:     }
1.29      www      2902: 
1.52      www      2903:     unless ($thisallowed) {
                   2904:         return '';
                   2905:     }
1.29      www      2906: 
1.52      www      2907: # Restrictions exist, deal with them
                   2908: #
                   2909: #   C:according to course preferences
                   2910: #   R:according to resource settings
                   2911: #   L:unless locked
                   2912: #   X:according to user session state
                   2913: #
                   2914: 
                   2915: # Possibly locked functionality, check all courses
1.54      www      2916: # Locks might take effect only after 10 minutes cache expiration for other
                   2917: # courses, and 2 minutes for current course
1.52      www      2918: 
                   2919:     my $envkey;
                   2920:     if ($thisallowed=~/L/) {
1.620     albertel 2921:         foreach $envkey (keys %env) {
1.54      www      2922:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   2923:                my $courseid=$2;
                   2924:                my $roleid=$1.'.'.$2;
1.92      www      2925:                $courseid=~s/^\///;
1.54      www      2926:                my $expiretime=600;
1.620     albertel 2927:                if ($env{'request.role'} eq $roleid) {
1.54      www      2928: 		  $expiretime=120;
                   2929:                }
                   2930: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   2931:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 2932:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.54      www      2933: 		   &coursedescription($courseid);
                   2934:                }
1.620     albertel 2935:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   2936:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   2937: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   2938:                        &log($env{'user.domain'},$env{'user.name'},
                   2939:                             $env{'user.home'},
1.57      www      2940:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      2941:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 2942:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2943: 		       return '';
                   2944:                    }
                   2945:                }
1.620     albertel 2946:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   2947:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   2948: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   2949:                        &log($env{'user.domain'},$env{'user.name'},
                   2950:                             $env{'user.home'},
1.57      www      2951:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      2952:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 2953:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2954: 		       return '';
                   2955:                    }
                   2956:                }
                   2957: 	   }
1.29      www      2958:        }
1.52      www      2959:     }
                   2960:    
                   2961: #
                   2962: # Rest of the restrictions depend on selected course
                   2963: #
                   2964: 
1.620     albertel 2965:     unless ($env{'request.course.id'}) {
1.52      www      2966:        return '1';
                   2967:     }
1.29      www      2968: 
1.52      www      2969: #
                   2970: # Now user is definitely in a course
                   2971: #
1.53      www      2972: 
                   2973: 
                   2974: # Course preferences
                   2975: 
                   2976:    if ($thisallowed=~/C/) {
1.620     albertel 2977:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   2978:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   2979:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 2980: 	   =~/\Q$rolecode\E/) {
1.620     albertel 2981:            &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.57      www      2982:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.620     albertel 2983:                 $env{'request.course.id'});
1.237     www      2984:            return '';
                   2985:        }
                   2986: 
1.620     albertel 2987:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 2988: 	   =~/\Q$unamedom\E/) {
1.620     albertel 2989:            &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.237     www      2990:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.620     albertel 2991:                 $env{'request.course.id'});
1.54      www      2992:            return '';
                   2993:        }
1.53      www      2994:    }
                   2995: 
                   2996: # Resource preferences
                   2997: 
                   2998:    if ($thisallowed=~/R/) {
1.620     albertel 2999:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3000:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.620     albertel 3001: 	  &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.57      www      3002:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341     www      3003:           return '';
1.54      www      3004:        }
1.53      www      3005:    }
1.30      www      3006: 
1.246     www      3007: # Restricted by state or randomout?
1.30      www      3008: 
1.52      www      3009:    if ($thisallowed=~/X/) {
1.620     albertel 3010:       if ($env{'acc.randomout'}) {
1.579     albertel 3011: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3012:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3013:             return ''; 
                   3014:          }
1.247     www      3015:       }
                   3016:       if (&condval($statecond)) {
1.52      www      3017: 	 return '2';
                   3018:       } else {
                   3019:          return '';
                   3020:       }
                   3021:    }
1.30      www      3022: 
1.52      www      3023:    return 'F';
1.232     www      3024: }
                   3025: 
                   3026: # --------------------------------------------------- Is a resource on the map?
                   3027: 
                   3028: sub is_on_map {
                   3029:     my $uri=&declutter(shift);
1.435     www      3030:     $uri=~s/\.\d+\.(\w+)$/\.$1/;
1.232     www      3031:     my @uriparts=split(/\//,$uri);
                   3032:     my $filename=$uriparts[$#uriparts];
                   3033:     my $pathname=$uri;
1.289     bowersj2 3034:     $pathname=~s|/\Q$filename\E$||;
1.332     www      3035:     $pathname=~s/^adm\/wrapper\///;    
1.289     bowersj2 3036:     #Trying to find the conditional for the file
1.620     albertel 3037:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3038: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3039:     if ($match) {
1.289     bowersj2 3040: 	return (1,$1);
                   3041:     } else {
1.434     www      3042: 	return (0,0);
1.289     bowersj2 3043:     }
1.12      www      3044: }
                   3045: 
1.427     www      3046: # --------------------------------------------------------- Get symb from alias
                   3047: 
                   3048: sub get_symb_from_alias {
                   3049:     my $symb=shift;
                   3050:     my ($map,$resid,$url)=&decode_symb($symb);
                   3051: # Already is a symb
                   3052:     if ($url) { return $symb; }
                   3053: # Must be an alias
                   3054:     my $aliassymb='';
                   3055:     my %bighash;
1.620     albertel 3056:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3057:                             &GDBM_READER(),0640)) {
                   3058:         my $rid=$bighash{'mapalias_'.$symb};
                   3059: 	if ($rid) {
                   3060: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3061: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3062: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3063: 	}
                   3064:         untie %bighash;
                   3065:     }
                   3066:     return $aliassymb;
                   3067: }
                   3068: 
1.12      www      3069: # ----------------------------------------------------------------- Define Role
                   3070: 
                   3071: sub definerole {
                   3072:   if (allowed('mcr','/')) {
                   3073:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3074:     foreach (split(':',$sysrole)) {
1.21      www      3075: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3076:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3077:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3078: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3079:                return "refused:s:$crole&$cqual"; 
                   3080:             }
                   3081:         }
1.191     harris41 3082:     }
1.392     www      3083:     foreach (split(':',$domrole)) {
1.21      www      3084: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3085:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3086:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3087: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3088:                return "refused:d:$crole&$cqual"; 
                   3089:             }
                   3090:         }
1.191     harris41 3091:     }
1.392     www      3092:     foreach (split(':',$courole)) {
1.21      www      3093: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3094:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3095:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3096: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3097:                return "refused:c:$crole&$cqual"; 
                   3098:             }
                   3099:         }
1.191     harris41 3100:     }
1.620     albertel 3101:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3102:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3103: 	        "rolesdef_$rolename=".
                   3104:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3105:     return reply($command,$env{'user.home'});
1.12      www      3106:   } else {
                   3107:     return 'refused';
                   3108:   }
1.105     harris41 3109: }
                   3110: 
                   3111: # ---------------- Make a metadata query against the network of library servers
                   3112: 
                   3113: sub metadata_query {
1.244     matthew  3114:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3115:     my %rhash;
1.244     matthew  3116:     my @server_list = (defined($server_array) ? @$server_array
                   3117:                                               : keys(%libserv) );
                   3118:     for my $server (@server_list) {
1.118     harris41 3119: 	unless ($custom or $customshow) {
                   3120: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3121: 	    $rhash{$server}=$reply;
                   3122: 	}
                   3123: 	else {
                   3124: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3125: 			     &escape($custom).':'.&escape($customshow),
                   3126: 			     $server);
                   3127: 	    $rhash{$server}=$reply;
                   3128: 	}
1.112     harris41 3129:     }
1.118     harris41 3130:     return \%rhash;
1.240     www      3131: }
                   3132: 
                   3133: # ----------------------------------------- Send log queries and wait for reply
                   3134: 
                   3135: sub log_query {
                   3136:     my ($uname,$udom,$query,%filters)=@_;
                   3137:     my $uhome=&homeserver($uname,$udom);
                   3138:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3139:     my $uhost=$hostname{$uhome};
1.241     www      3140:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3141:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3142:                        $uhome);
1.479     albertel 3143:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3144:     return get_query_reply($queryid);
                   3145: }
                   3146: 
1.508     raeburn  3147: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3148: 
                   3149: sub fetch_enrollment_query {
1.511     raeburn  3150:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3151:     my $homeserver;
1.547     raeburn  3152:     my $maxtries = 1;
1.508     raeburn  3153:     if ($context eq 'automated') {
                   3154:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3155:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3156:     } else {
                   3157:         $homeserver = &homeserver($cnum,$dom);
                   3158:     }
1.506     raeburn  3159:     my $host=$hostname{$homeserver};
                   3160:     my $cmd = '';
                   3161:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3162:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3163:     }
                   3164:     $cmd =~ s/%%$//;
                   3165:     $cmd = &escape($cmd);
                   3166:     my $query = 'fetchenrollment';
1.620     albertel 3167:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3168:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3169:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3170:         return 'error: '.$queryid;
                   3171:     }
1.506     raeburn  3172:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3173:     my $tries = 1;
                   3174:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3175:         $reply = &get_query_reply($queryid);
                   3176:         $tries ++;
                   3177:     }
1.526     raeburn  3178:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3179:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3180:     } else {
1.515     raeburn  3181:         my @responses = split/:/,$reply;
                   3182:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3183:             foreach (@responses) {
                   3184:                 my ($key,$value) = split/=/,$_;
                   3185:                 $$replyref{$key} = $value;
                   3186:             }
                   3187:         } else {
1.506     raeburn  3188:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3189:             foreach (@responses) {
                   3190:                 my ($key,$value) = split/=/,$_;
                   3191:                 $$replyref{$key} = $value;
                   3192:                 if ($value > 0) {
                   3193:                     foreach (@{$$affiliatesref{$key}}) {
                   3194:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3195:                         my $destname = $pathname.'/'.$filename;
                   3196:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3197:                         if ($xml_classlist =~ /^error/) {
                   3198:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3199:                         } else {
1.506     raeburn  3200:                             if ( open(FILE,">$destname") ) {
                   3201:                                 print FILE &unescape($xml_classlist);
                   3202:                                 close(FILE);
1.526     raeburn  3203:                             } else {
                   3204:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3205:                             }
                   3206:                         }
                   3207:                     }
                   3208:                 }
                   3209:             }
                   3210:         }
                   3211:         return 'ok';
                   3212:     }
                   3213:     return 'error';
                   3214: }
                   3215: 
1.242     www      3216: sub get_query_reply {
                   3217:     my $queryid=shift;
1.240     www      3218:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3219:     my $reply='';
                   3220:     for (1..100) {
                   3221: 	sleep 2;
                   3222:         if (-e $replyfile.'.end') {
1.448     albertel 3223: 	    if (open(my $fh,$replyfile)) {
1.240     www      3224:                $reply.=<$fh>;
1.448     albertel 3225:                close($fh);
1.240     www      3226: 	   } else { return 'error: reply_file_error'; }
1.242     www      3227:            return &unescape($reply);
                   3228: 	}
1.240     www      3229:     }
1.242     www      3230:     return 'timeout:'.$queryid;
1.240     www      3231: }
                   3232: 
                   3233: sub courselog_query {
1.241     www      3234: #
                   3235: # possible filters:
                   3236: # url: url or symb
                   3237: # username
                   3238: # domain
                   3239: # action: view, submit, grade
                   3240: # start: timestamp
                   3241: # end: timestamp
                   3242: #
1.240     www      3243:     my (%filters)=@_;
1.620     albertel 3244:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3245:     if ($filters{'url'}) {
                   3246: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3247:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3248:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3249:     }
1.620     albertel 3250:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3251:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3252:     return &log_query($cname,$cdom,'courselog',%filters);
                   3253: }
                   3254: 
                   3255: sub userlog_query {
                   3256:     my ($uname,$udom,%filters)=@_;
                   3257:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3258: }
                   3259: 
1.506     raeburn  3260: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3261: 
                   3262: sub auto_run {
1.508     raeburn  3263:     my ($cnum,$cdom) = @_;
                   3264:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3265:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3266:     return $response;
                   3267: }
                   3268:                                                                                    
                   3269: sub auto_get_sections {
1.508     raeburn  3270:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3271:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3272:     my @secs = ();
1.511     raeburn  3273:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3274:     unless ($response eq 'refused') {
                   3275:         @secs = split/:/,$response;
                   3276:     }
                   3277:     return @secs;
                   3278: }
                   3279:                                                                                    
                   3280: sub auto_new_course {
1.508     raeburn  3281:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3282:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3283:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3284:     return $response;
                   3285: }
                   3286:                                                                                    
                   3287: sub auto_validate_courseID {
1.508     raeburn  3288:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3289:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3290:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3291:     return $response;
                   3292: }
                   3293:                                                                                    
                   3294: sub auto_create_password {
1.508     raeburn  3295:     my ($cnum,$cdom,$authparam) = @_;
                   3296:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3297:     my $create_passwd = 0;
                   3298:     my $authchk = '';
1.511     raeburn  3299:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3300:     if ($response eq 'refused') {
                   3301:         $authchk = 'refused';
                   3302:     } else {
                   3303:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3304:     }
                   3305:     return ($authparam,$create_passwd,$authchk);
                   3306: }
                   3307: 
1.521     raeburn  3308: sub auto_instcode_format {
                   3309:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3310:     my $courses = '';
                   3311:     my $homeserver;
                   3312:     if ($caller eq 'global') {
1.584     raeburn  3313:         foreach my $tryserver (keys %libserv) {
                   3314:             if ($hostdom{$tryserver} eq $codedom) {
                   3315:                 $homeserver = $tryserver;
                   3316:                 last;
                   3317:             }
                   3318:         }
1.620     albertel 3319:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3320:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3321:         }
1.521     raeburn  3322:     } else {
                   3323:         $homeserver = &homeserver($caller,$codedom);
                   3324:     }
                   3325:     foreach (keys %{$instcodes}) {
                   3326:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3327:     }
                   3328:     chop($courses);
                   3329:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3330:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3331:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3332:         %{$codes} = &str2hash($codes_str);
                   3333:         @{$codetitles} = &str2array($codetitles_str);
                   3334:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3335:         %{$cat_order} = &str2hash($cat_order_str);
                   3336:         return 'ok';
                   3337:     }
                   3338:     return $response;
                   3339: }
                   3340: 
1.12      www      3341: # ------------------------------------------------------------------ Plain Text
                   3342: 
                   3343: sub plaintext {
1.22      www      3344:     my $short=shift;
1.414     www      3345:     return &mt($prp{$short});
1.12      www      3346: }
                   3347: 
                   3348: # ----------------------------------------------------------------- Assign Role
                   3349: 
                   3350: sub assignrole {
1.357     www      3351:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      3352:     my $mrole;
                   3353:     if ($role =~ /^cr\//) {
1.393     www      3354:         my $cwosec=$url;
                   3355:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   3356: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      3357:            &logthis('Refused custom assignrole: '.
                   3358:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3359: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3360:            return 'refused'; 
                   3361:         }
1.21      www      3362:         $mrole='cr';
                   3363:     } else {
1.82      www      3364:         my $cwosec=$url;
1.83      www      3365:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      3366:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      3367:            &logthis('Refused assignrole: '.
                   3368:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3369: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3370:            return 'refused'; 
                   3371:         }
1.21      www      3372:         $mrole=$role;
                   3373:     }
1.620     albertel 3374:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3375:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      3376:     if ($end) { $command.='_'.$end; }
1.21      www      3377:     if ($start) {
                   3378: 	if ($end) { 
1.81      www      3379:            $command.='_'.$start; 
1.21      www      3380:         } else {
1.81      www      3381:            $command.='_0_'.$start;
1.21      www      3382:         }
                   3383:     }
1.357     www      3384: # actually delete
                   3385:     if ($deleteflag) {
1.373     www      3386: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      3387: # modify command to delete the role
1.620     albertel 3388:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      3389:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 3390: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      3391: # set start and finish to negative values for userrolelog
                   3392:            $start=-1;
                   3393:            $end=-1;
                   3394:         }
                   3395:     }
                   3396: # send command
1.349     www      3397:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      3398: # log new user role if status is ok
1.349     www      3399:     if ($answer eq 'ok') {
                   3400: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
                   3401:     }
                   3402:     return $answer;
1.169     harris41 3403: }
                   3404: 
                   3405: # -------------------------------------------------- Modify user authentication
1.197     www      3406: # Overrides without validation
                   3407: 
1.169     harris41 3408: sub modifyuserauth {
                   3409:     my ($udom,$uname,$umode,$upass)=@_;
                   3410:     my $uhome=&homeserver($uname,$udom);
1.197     www      3411:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   3412:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 3413:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   3414:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 3415:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   3416: 		     &escape($upass),$uhome);
1.620     albertel 3417:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      3418:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   3419:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   3420:     &log($udom,,$uname,$uhome,
1.620     albertel 3421:         'Authentication changed by '.$env{'user.domain'}.', '.
                   3422:                                      $env{'user.name'}.', '.$umode.
1.197     www      3423:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 3424:     unless ($reply eq 'ok') {
1.197     www      3425:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 3426: 	return 'error: '.$reply;
                   3427:     }   
1.170     harris41 3428:     return 'ok';
1.80      www      3429: }
                   3430: 
1.81      www      3431: # --------------------------------------------------------------- Modify a user
1.80      www      3432: 
1.81      www      3433: sub modifyuser {
1.206     matthew  3434:     my ($udom,    $uname, $uid,
                   3435:         $umode,   $upass, $first,
                   3436:         $middle,  $last,  $gene,
1.387     www      3437:         $forceid, $desiredhome, $email)=@_;
1.198     www      3438:     $udom=~s/\W//g;
                   3439:     $uname=~s/\W//g;
1.81      www      3440:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3441:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  3442: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   3443:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   3444:                                      ' desiredhome not specified'). 
1.620     albertel 3445:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   3446:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 3447:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      3448: # ----------------------------------------------------------------- Create User
1.406     albertel 3449:     if (($uhome eq 'no_host') && 
                   3450: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      3451:         my $unhome='';
1.209     matthew  3452:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   3453:             $unhome = $desiredhome;
1.620     albertel 3454: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   3455: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  3456:         } else { # load balancing routine for determining $unhome
1.80      www      3457:             my $tryserver;
1.81      www      3458:             my $loadm=10000000;
1.80      www      3459:             foreach $tryserver (keys %libserv) {
                   3460: 	       if ($hostdom{$tryserver} eq $udom) {
                   3461:                   my $answer=reply('load',$tryserver);
                   3462:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   3463: 		      $loadm=$answer;
                   3464:                       $unhome=$tryserver;
                   3465:                   }
                   3466: 	       }
                   3467: 	    }
                   3468:         }
                   3469:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  3470: 	    return 'error: unable to find a home server for '.$uname.
                   3471:                    ' in domain '.$udom;
1.80      www      3472:         }
                   3473:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   3474:                          &escape($upass),$unhome);
                   3475: 	unless ($reply eq 'ok') {
                   3476:             return 'error: '.$reply;
                   3477:         }   
1.230     stredwic 3478:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      3479:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  3480: 	    return 'error: unable verify users home machine.';
1.80      www      3481:         }
1.209     matthew  3482:     }   # End of creation of new user
1.80      www      3483: # ---------------------------------------------------------------------- Add ID
                   3484:     if ($uid) {
                   3485:        $uid=~tr/A-Z/a-z/;
                   3486:        my %uidhash=&idrget($udom,$uname);
1.196     www      3487:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   3488:          && (!$forceid)) {
1.80      www      3489: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  3490: 	      return 'error: user id "'.$uid.'" does not match '.
                   3491:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      3492:           }
                   3493:        } else {
                   3494: 	  &idput($udom,($uname => $uid));
                   3495:        }
                   3496:     }
                   3497: # -------------------------------------------------------------- Add names, etc
1.313     matthew  3498:     my @tmp=&get('environment',
1.134     albertel 3499: 		   ['firstname','middlename','lastname','generation'],
                   3500: 		   $udom,$uname);
1.313     matthew  3501:     my %names;
                   3502:     if ($tmp[0] =~ m/^error:.*/) { 
                   3503:         %names=(); 
                   3504:     } else {
                   3505:         %names = @tmp;
                   3506:     }
1.388     www      3507: #
                   3508: # Make sure to not trash student environment if instructor does not bother
                   3509: # to supply name and email information
                   3510: #
                   3511:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  3512:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      3513:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  3514:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      3515:     if ($email) {
                   3516:        $email=~s/[^\w\@\.\-\,]//gs;
                   3517:        if ($email=~/\@/) { $names{'notification'} = $email;
                   3518: 			   $names{'critnotification'} = $email;
                   3519: 			   $names{'permanentemail'} = $email; }
                   3520:     }
1.134     albertel 3521:     my $reply = &put('environment', \%names, $udom,$uname);
                   3522:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      3523:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3524:              $umode.', '.$first.', '.$middle.', '.
                   3525: 	     $last.', '.$gene.' by '.
1.620     albertel 3526:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 3527:     return 'ok';
1.80      www      3528: }
                   3529: 
1.81      www      3530: # -------------------------------------------------------------- Modify student
1.80      www      3531: 
1.81      www      3532: sub modifystudent {
                   3533:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  3534:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 3535:     if (!$cid) {
1.620     albertel 3536: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 3537: 	    return 'not_in_class';
                   3538: 	}
1.80      www      3539:     }
                   3540: # --------------------------------------------------------------- Make the user
1.81      www      3541:     my $reply=&modifyuser
1.209     matthew  3542: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      3543:          $desiredhome,$email);
1.80      www      3544:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  3545:     # This will cause &modify_student_enrollment to get the uid from the
                   3546:     # students environment
                   3547:     $uid = undef if (!$forceid);
1.455     albertel 3548:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  3549: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  3550:     return $reply;
                   3551: }
                   3552: 
                   3553: sub modify_student_enrollment {
1.515     raeburn  3554:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 3555:     my ($cdom,$cnum,$chome);
                   3556:     if (!$cid) {
1.620     albertel 3557: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 3558: 	    return 'not_in_class';
                   3559: 	}
1.620     albertel 3560: 	$cdom=$env{'course.'.$cid.'.domain'};
                   3561: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 3562:     } else {
                   3563: 	($cdom,$cnum)=split(/_/,$cid);
                   3564:     }
1.620     albertel 3565:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 3566:     if (!$chome) {
1.457     raeburn  3567: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  3568:     }
1.455     albertel 3569:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  3570:     # Make sure the user exists
1.81      www      3571:     my $uhome=&homeserver($uname,$udom);
                   3572:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3573: 	return 'error: no such user';
                   3574:     }
1.297     matthew  3575:     # Get student data if we were not given enough information
                   3576:     if (!defined($first)  || $first  eq '' || 
                   3577:         !defined($last)   || $last   eq '' || 
                   3578:         !defined($uid)    || $uid    eq '' || 
                   3579:         !defined($middle) || $middle eq '' || 
                   3580:         !defined($gene)   || $gene   eq '') {
1.294     matthew  3581:         # They did not supply us with enough data to enroll the student, so
                   3582:         # we need to pick up more information.
1.297     matthew  3583:         my %tmp = &get('environment',
1.294     matthew  3584:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  3585:                        ,$udom,$uname);
                   3586: 
1.455     albertel 3587:         #foreach (keys(%tmp)) {
                   3588:         #    &logthis("key $_ = ".$tmp{$_});
                   3589:         #}
1.294     matthew  3590:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   3591:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   3592:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  3593:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  3594:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   3595:     }
1.556     albertel 3596:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 3597:     my $reply=cput('classlist',
                   3598: 		   {"$uname:$udom" => 
1.515     raeburn  3599: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 3600: 		   $cdom,$cnum);
1.81      www      3601:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   3602: 	return 'error: '.$reply;
                   3603:     }
1.297     matthew  3604:     # Add student role to user
1.83      www      3605:     my $uurl='/'.$cid;
1.81      www      3606:     $uurl=~s/\_/\//g;
                   3607:     if ($usec) {
                   3608: 	$uurl.='/'.$usec;
                   3609:     }
                   3610:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      3611: }
                   3612: 
1.556     albertel 3613: sub format_name {
                   3614:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   3615:     my $name;
                   3616:     if ($first ne 'lastname') {
                   3617: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   3618:     } else {
                   3619: 	if ($lastname=~/\S/) {
                   3620: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   3621: 	    $name=~s/\s+,/,/;
                   3622: 	} else {
                   3623: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   3624: 	}
                   3625:     }
                   3626:     $name=~s/^\s+//;
                   3627:     $name=~s/\s+$//;
                   3628:     $name=~s/\s+/ /g;
                   3629:     return $name;
                   3630: }
                   3631: 
1.84      www      3632: # ------------------------------------------------- Write to course preferences
                   3633: 
                   3634: sub writecoursepref {
                   3635:     my ($courseid,%prefs)=@_;
                   3636:     $courseid=~s/^\///;
                   3637:     $courseid=~s/\_/\//g;
                   3638:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   3639:     my $chome=homeserver($cnum,$cdomain);
                   3640:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   3641: 	return 'error: no such course';
                   3642:     }
                   3643:     my $cstring='';
1.191     harris41 3644:     foreach (keys %prefs) {
1.84      www      3645: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 3646:     }
1.84      www      3647:     $cstring=~s/\&$//;
                   3648:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   3649: }
                   3650: 
                   3651: # ---------------------------------------------------------- Make/modify course
                   3652: 
                   3653: sub createcourse {
1.571     raeburn  3654:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      3655:     $url=&declutter($url);
                   3656:     my $cid='';
1.264     matthew  3657:     unless (&allowed('ccc',$udom)) {
1.84      www      3658:         return 'refused';
                   3659:     }
                   3660: # ------------------------------------------------------------------- Create ID
                   3661:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3662:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   3663: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 3664:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      3665:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3666:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3667:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 3668:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      3669:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3670:            return 'error: unable to generate unique course-ID';
                   3671:        } 
                   3672:    }
1.264     matthew  3673: # ------------------------------------------------ Check supplied server name
1.620     albertel 3674:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  3675:     if (! exists($libserv{$course_server})) {
                   3676:         return 'error:bad server name '.$course_server;
                   3677:     }
1.84      www      3678: # ------------------------------------------------------------- Make the course
                   3679:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  3680:                       $course_server);
1.84      www      3681:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 3682:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      3683:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3684: 	return 'error: no such course';
                   3685:     }
1.271     www      3686: # ----------------------------------------------------------------- Course made
1.516     raeburn  3687: # log existence
                   3688:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  3689:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      3690:     &flushcourselogs();
                   3691: # set toplevel url
1.271     www      3692:     my $topurl=$url;
                   3693:     unless ($nonstandard) {
                   3694: # ------------------------------------------ For standard courses, make top url
                   3695:         my $mapurl=&clutter($url);
1.278     www      3696:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 3697:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      3698: <map>
                   3699: <resource id="1" type="start"></resource>
                   3700: <resource id="2" src="$mapurl"></resource>
                   3701: <resource id="3" type="finish"></resource>
                   3702: <link index="1" from="1" to="2"></link>
                   3703: <link index="2" from="2" to="3"></link>
                   3704: </map>
                   3705: ENDINITMAP
                   3706:         $topurl=&declutter(
                   3707:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
                   3708:                           );
                   3709:     }
                   3710: # ----------------------------------------------------------- Write preferences
1.84      www      3711:     &writecoursepref($udom.'_'.$uname,
                   3712:                      ('description' => $description,
1.271     www      3713:                       'url'         => $topurl));
1.84      www      3714:     return '/'.$udom.'/'.$uname;
                   3715: }
                   3716: 
1.21      www      3717: # ---------------------------------------------------------- Assign Custom Role
                   3718: 
                   3719: sub assigncustomrole {
1.357     www      3720:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      3721:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      3722:                        $end,$start,$deleteflag);
1.21      www      3723: }
                   3724: 
                   3725: # ----------------------------------------------------------------- Revoke Role
                   3726: 
                   3727: sub revokerole {
1.357     www      3728:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      3729:     my $now=time;
1.357     www      3730:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      3731: }
                   3732: 
                   3733: # ---------------------------------------------------------- Revoke Custom Role
                   3734: 
                   3735: sub revokecustomrole {
1.357     www      3736:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      3737:     my $now=time;
1.357     www      3738:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   3739:            $deleteflag);
1.17      www      3740: }
                   3741: 
1.533     banghart 3742: # ------------------------------------------------------------ Disk usage
1.535     albertel 3743: sub diskusage {
1.533     banghart 3744:     my ($udom,$uname,$directoryRoot)=@_;
                   3745:     $directoryRoot =~ s/\/$//;
1.535     albertel 3746:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 3747:     return $listing;
1.512     banghart 3748: }
                   3749: 
1.566     banghart 3750: sub is_locked {
                   3751:     my ($file_name, $domain, $user) = @_;
                   3752:     my @check;
                   3753:     my $is_locked;
                   3754:     push @check, $file_name;
1.613     albertel 3755:     my %locked = &get('file_permissions',\@check,
1.620     albertel 3756: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 3757:     my ($tmp)=keys(%locked);
                   3758:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 3759: 
1.566     banghart 3760:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   3761:         $is_locked = 'true';
                   3762:     } else {
                   3763:         $is_locked = 'false';
                   3764:     }
                   3765: }
                   3766: 
1.559     banghart 3767: # ------------------------------------------------------------- Mark as Read Only
                   3768: 
                   3769: sub mark_as_readonly {
                   3770:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 3771:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 3772:     my ($tmp)=keys(%current_permissions);
                   3773:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 3774:     foreach my $file (@{$files}) {
1.561     banghart 3775:         push(@{$current_permissions{$file}},$what);
1.559     banghart 3776:     }
1.613     albertel 3777:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 3778:     return;
                   3779: }
                   3780: 
1.572     banghart 3781: # ------------------------------------------------------------Save Selected Files
                   3782: 
                   3783: sub save_selected_files {
                   3784:     my ($user, $path, @files) = @_;
                   3785:     my $filename = $user."savedfiles";
1.573     banghart 3786:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 3787:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 3788:     foreach my $file (@files) {
1.620     albertel 3789:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 3790:     }
                   3791:     foreach my $file (@other_files) {
1.574     banghart 3792:         print (OUT $file."\n");
1.572     banghart 3793:     }
1.574     banghart 3794:     close (OUT);
1.572     banghart 3795:     return 'ok';
                   3796: }
                   3797: 
1.574     banghart 3798: sub clear_selected_files {
                   3799:     my ($user) = @_;
                   3800:     my $filename = $user."savedfiles";
                   3801:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   3802:     print (OUT undef);
                   3803:     close (OUT);
                   3804:     return ("ok");    
                   3805: }
                   3806: 
1.572     banghart 3807: sub files_in_path {
                   3808:     my ($user, $path) = @_;
                   3809:     my $filename = $user."savedfiles";
                   3810:     my %return_files;
1.574     banghart 3811:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 3812:     while (my $line_in = <IN>) {
1.574     banghart 3813:         chomp ($line_in);
                   3814:         my @paths_and_file = split (m!/!, $line_in);
                   3815:         my $file_part = pop (@paths_and_file);
                   3816:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 3817:         $path_part.='/';
                   3818:         my $path_and_file = $path_part.$file_part;
                   3819:         if ($path_part eq $path) {
                   3820:             $return_files{$file_part}= 'selected';
                   3821:         }
                   3822:     }
1.574     banghart 3823:     close (IN);
                   3824:     return (\%return_files);
1.572     banghart 3825: }
                   3826: 
                   3827: # called in portfolio select mode, to show files selected NOT in current directory
                   3828: sub files_not_in_path {
                   3829:     my ($user, $path) = @_;
                   3830:     my $filename = $user."savedfiles";
                   3831:     my @return_files;
                   3832:     my $path_part;
1.574     banghart 3833:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 3834:     while (<IN>) {
                   3835:         #ok, I know it's clunky, but I want it to work
                   3836:         my @paths_and_file = split m!/!, $_;
1.574     banghart 3837:         my $file_part = pop (@paths_and_file);
                   3838:         chomp ($file_part);
                   3839:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 3840:         $path_part .= '/';
                   3841:         my $path_and_file = $path_part.$file_part;
                   3842:         if ($path_part ne $path) {
1.574     banghart 3843:             push (@return_files, ($path_and_file));
1.572     banghart 3844:         }
                   3845:     }
1.574     banghart 3846:     close (OUT);
                   3847:     return (@return_files);
1.572     banghart 3848: }
                   3849: 
1.561     banghart 3850: #--------------------------------------------------------------Get Marked as Read Only
                   3851: 
1.629     banghart 3852: 
1.561     banghart 3853: sub get_marked_as_readonly {
                   3854:     my ($domain,$user,$what) = @_;
1.613     albertel 3855:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 3856:     my ($tmp)=keys(%current_permissions);
                   3857:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.563     banghart 3858:     my @readonly_files;
1.629     banghart 3859:     my $cmp1=$what;
                   3860:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.563     banghart 3861:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 3862:         if (ref($value) eq "ARRAY"){
                   3863:             foreach my $stored_what (@{$value}) {
1.629     banghart 3864:                 my $cmp2=$stored_what;
                   3865:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
                   3866:                 if ($cmp1 eq $cmp2) {
1.561     banghart 3867:                     push(@readonly_files, $file_name);
1.563     banghart 3868:                 } elsif (!defined($what)) {
                   3869:                     push(@readonly_files, $file_name);
1.561     banghart 3870:                 }
                   3871:             }
                   3872:         } 
                   3873:     }
                   3874:     return @readonly_files;
                   3875: }
1.577     banghart 3876: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 3877: 
1.577     banghart 3878: sub get_marked_as_readonly_hash {
                   3879:     my ($domain,$user,$what) = @_;
1.613     albertel 3880:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 3881:     my ($tmp)=keys(%current_permissions);
                   3882:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3883: 
1.577     banghart 3884:     my %readonly_files;
                   3885:     while (my ($file_name,$value) = each(%current_permissions)) {
                   3886:         if (ref($value) eq "ARRAY"){
                   3887:             foreach my $stored_what (@{$value}) {
                   3888:                 if ($stored_what eq $what) {
                   3889:                     $readonly_files{$file_name} = 'locked';
                   3890:                 } elsif (!defined($what)) {
                   3891:                     $readonly_files{$file_name} = 'locked';
                   3892:                 }
                   3893:             }
                   3894:         } 
                   3895:     }
                   3896:     return %readonly_files;
                   3897: }
1.559     banghart 3898: # ------------------------------------------------------------ Unmark as Read Only
                   3899: 
                   3900: sub unmark_as_readonly {
1.629     banghart 3901:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   3902:     # for portfolio submissions, $what contains [$symb,$crsid] 
                   3903:     my ($domain,$user,$what,$file_name) = @_;
1.634     albertel 3904:     my $symb_crs = $what;
                   3905:     if (ref($what)) { $symb_crs=join('',@$what); }
1.613     albertel 3906:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 3907:     my ($tmp)=keys(%current_permissions);
                   3908:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3909:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.561     banghart 3910:     foreach my $file(@readonly_files){
1.563     banghart 3911:         my $current_locks = $current_permissions{$file};
                   3912:         my @new_locks;
                   3913:         my @del_keys;
                   3914:         if (ref($current_locks) eq "ARRAY"){
                   3915:             foreach my $locker (@{$current_locks}) {
1.632     albertel 3916:                 my $compare=$locker;
                   3917:                 if (ref($locker)) { $compare=join('',@{$locker}) };
                   3918:                 if ($compare eq $symb_crs) {
1.629     banghart 3919:                     if (defined($file_name) && ($file_name ne $file)) {
                   3920:                         push(@new_locks, $what);
                   3921:                     }
                   3922:                 } else {
1.563     banghart 3923:                     push(@new_locks, $what);
                   3924:                 }
                   3925:             }
                   3926:             if (@new_locks > 0) {
                   3927:                 $current_permissions{$file} = \@new_locks;
                   3928:             } else {
                   3929:                 push(@del_keys, $file);
1.613     albertel 3930:                 &del('file_permissions',\@del_keys, $domain, $user);
1.563     banghart 3931:                 delete $current_permissions{$file};
                   3932:             }
                   3933:         }
1.561     banghart 3934:     }
1.613     albertel 3935:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 3936:     return;
                   3937: }
1.512     banghart 3938: 
1.17      www      3939: # ------------------------------------------------------------ Directory lister
                   3940: 
                   3941: sub dirlist {
1.253     stredwic 3942:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   3943: 
1.18      www      3944:     $uri=~s/^\///;
                   3945:     $uri=~s/\/$//;
1.253     stredwic 3946:     my ($udom, $uname);
                   3947:     (undef,$udom,$uname)=split(/\//,$uri);
                   3948:     if(defined($userdomain)) {
                   3949:         $udom = $userdomain;
                   3950:     }
                   3951:     if(defined($username)) {
                   3952:         $uname = $username;
                   3953:     }
                   3954: 
                   3955:     my $dirRoot = $perlvar{'lonDocRoot'};
                   3956:     if(defined($alternateDirectoryRoot)) {
                   3957:         $dirRoot = $alternateDirectoryRoot;
                   3958:         $dirRoot =~ s/\/$//;
                   3959:     }
                   3960: 
                   3961:     if($udom) {
                   3962:         if($uname) {
1.605     matthew  3963:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 3964:                               homeserver($uname,$udom));
1.605     matthew  3965:             my @listing_results;
                   3966:             if ($listing eq 'unknown_cmd') {
                   3967:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   3968:                                homeserver($uname,$udom));
                   3969:                 @listing_results = split(/:/,$listing);
                   3970:             } else {
                   3971:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   3972:             }
                   3973:             return @listing_results;
1.253     stredwic 3974:         } elsif(!defined($alternateDirectoryRoot)) {
                   3975:             my $tryserver;
                   3976:             my %allusers=();
                   3977:             foreach $tryserver (keys %libserv) {
                   3978:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  3979:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 3980:                                       $udom, $tryserver);
1.605     matthew  3981:                     my @listing_results;
                   3982:                     if ($listing eq 'unknown_cmd') {
                   3983:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   3984:                                        $udom, $tryserver);
                   3985:                         @listing_results = split(/:/,$listing);
                   3986:                     } else {
                   3987:                         @listing_results =
                   3988:                             map { &unescape($_); } split(/:/,$listing);
                   3989:                     }
                   3990:                     if ($listing_results[0] ne 'no_such_dir' && 
                   3991:                         $listing_results[0] ne 'empty'       &&
                   3992:                         $listing_results[0] ne 'con_lost') {
                   3993:                         foreach (@listing_results) {
1.253     stredwic 3994:                             my ($entry,@stat)=split(/&/,$_);
                   3995:                             $allusers{$entry}=1;
                   3996:                         }
                   3997:                     }
1.191     harris41 3998:                 }
1.253     stredwic 3999:             }
                   4000:             my $alluserstr='';
                   4001:             foreach (sort keys %allusers) {
                   4002:                 $alluserstr.=$_.'&user:';
                   4003:             }
                   4004:             $alluserstr=~s/:$//;
                   4005:             return split(/:/,$alluserstr);
                   4006:         } else {
                   4007:             my @emptyResults = ();
                   4008:             push(@emptyResults, 'missing user name');
                   4009:             return split(':',@emptyResults);
                   4010:         }
                   4011:     } elsif(!defined($alternateDirectoryRoot)) {
                   4012:         my $tryserver;
                   4013:         my %alldom=();
                   4014:         foreach $tryserver (keys %libserv) {
                   4015:             $alldom{$hostdom{$tryserver}}=1;
                   4016:         }
                   4017:         my $alldomstr='';
                   4018:         foreach (sort keys %alldom) {
1.397     albertel 4019:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 4020:         }
                   4021:         $alldomstr=~s/:$//;
                   4022:         return split(/:/,$alldomstr);       
                   4023:     } else {
                   4024:         my @emptyResults = ();
                   4025:         push(@emptyResults, 'missing domain');
                   4026:         return split(':',@emptyResults);
1.275     stredwic 4027:     }
                   4028: }
                   4029: 
                   4030: # --------------------------------------------- GetFileTimestamp
                   4031: # This function utilizes dirlist and returns the date stamp for
                   4032: # when it was last modified.  It will also return an error of -1
                   4033: # if an error occurs
                   4034: 
1.410     matthew  4035: ##
                   4036: ## FIXME: This subroutine assumes its caller knows something about the
                   4037: ## directory structure of the home server for the student ($root).
                   4038: ## Not a good assumption to make.  Since this is for looking up files
                   4039: ## in user directories, the full path should be constructed by lond, not
                   4040: ## whatever machine we request data from.
                   4041: ##
1.275     stredwic 4042: sub GetFileTimestamp {
                   4043:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4044:     $studentDomain=~s/\W//g;
                   4045:     $studentName=~s/\W//g;
                   4046:     my $subdir=$studentName.'__';
                   4047:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4048:     my $proname="$studentDomain/$subdir/$studentName";
                   4049:     $proname .= '/'.$filename;
1.375     matthew  4050:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4051:                                               $studentName, $root);
1.275     stredwic 4052:     my @stats = split('&', $fileStat);
                   4053:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4054:         # @stats contains first the filename, then the stat output
                   4055:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4056:     } else {
                   4057:         return -1;
1.253     stredwic 4058:     }
1.26      www      4059: }
                   4060: 
                   4061: # -------------------------------------------------------- Value of a Condition
                   4062: 
1.40      www      4063: sub directcondval {
                   4064:     my $number=shift;
1.620     albertel 4065:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4066: 	&Apache::lonuserstate::evalstate();
                   4067:     }
1.620     albertel 4068:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4069:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4070:     } else {
                   4071:        return 2;
                   4072:     }
                   4073: }
                   4074: 
1.26      www      4075: sub condval {
                   4076:     my $condidx=shift;
                   4077:     my $result=0;
1.54      www      4078:     my $allpathcond='';
1.191     harris41 4079:     foreach (split(/\|/,$condidx)) {
1.620     albertel 4080:        if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$_})) {
1.54      www      4081: 	   $allpathcond.=
1.620     albertel 4082:                '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$_}.')|';
1.54      www      4083:        }
1.191     harris41 4084:     }
1.54      www      4085:     $allpathcond=~s/\|$//;
1.620     albertel 4086:     if ($env{'request.course.id'}) {
1.54      www      4087:        if ($allpathcond) {
1.26      www      4088:           my $operand='|';
                   4089: 	  my @stack;
1.191     harris41 4090:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      4091:               if ($_ eq '(') {
                   4092:                  push @stack,($operand,$result)
                   4093:               } elsif ($_ eq ')') {
                   4094:                   my $before=pop @stack;
                   4095: 		  if (pop @stack eq '&') {
                   4096: 		      $result=$result>$before?$before:$result;
                   4097:                   } else {
                   4098:                       $result=$result>$before?$result:$before;
                   4099:                   }
                   4100:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   4101:                   $operand=$_;
                   4102:               } else {
1.40      www      4103:                   my $new=directcondval($_);
1.26      www      4104:                   if ($operand eq '&') {
                   4105:                      $result=$result>$new?$new:$result;
                   4106:                   } else {
                   4107:                      $result=$result>$new?$result:$new;
1.191     harris41 4108:                   }
1.26      www      4109:               }
1.191     harris41 4110:           }
1.26      www      4111:        }
                   4112:     }
                   4113:     return $result;
1.421     albertel 4114: }
                   4115: 
                   4116: # ---------------------------------------------------- Devalidate courseresdata
                   4117: 
                   4118: sub devalidatecourseresdata {
                   4119:     my ($coursenum,$coursedomain)=@_;
                   4120:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4121:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4122: }
                   4123: 
1.200     www      4124: # --------------------------------------------------- Course Resourcedata Query
                   4125: 
1.624     albertel 4126: sub get_courseresdata {
                   4127:     my ($coursenum,$coursedomain)=@_;
1.200     www      4128:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4129:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4130:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4131:     my %dumpreply;
1.417     albertel 4132:     unless (defined($cached)) {
1.624     albertel 4133: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4134: 	$result=\%dumpreply;
1.251     albertel 4135: 	my ($tmp) = keys(%dumpreply);
                   4136: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4137: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4138: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4139: 	    return $tmp;
1.416     albertel 4140: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4141: 	    $result=undef;
1.599     albertel 4142: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4143: 	}
                   4144:     }
1.624     albertel 4145:     return $result;
                   4146: }
                   4147: 
1.633     albertel 4148: sub devalidateuserresdata {
                   4149:     my ($uname,$udom)=@_;
                   4150:     my $hashid="$udom:$uname";
                   4151:     &devalidate_cache_new('userres',$hashid);
                   4152: }
                   4153: 
1.624     albertel 4154: sub get_userresdata {
                   4155:     my ($uname,$udom)=@_;
                   4156:     #most student don\'t have any data set, check if there is some data
                   4157:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4158: 
                   4159:     my $hashid="$udom:$uname";
                   4160:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4161:     if (!defined($cached)) {
                   4162: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4163: 	$result=\%resourcedata;
                   4164: 	&do_cache_new('userres',$hashid,$result,600);
                   4165:     }
                   4166:     my ($tmp)=keys(%$result);
                   4167:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4168: 	return $result;
                   4169:     }
                   4170:     #error 2 occurs when the .db doesn't exist
                   4171:     if ($tmp!~/error: 2 /) {
                   4172: 	&logthis("<font color=blue>WARNING:".
                   4173: 		 " Trying to get resource data for ".
                   4174: 		 $uname." at ".$udom.": ".
                   4175: 		 $tmp."</font>");
                   4176:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 4177: 	#&EXT_cache_set($udom,$uname);
                   4178: 	&do_cache_new('userres',$hashid,undef,600);
1.624     albertel 4179:     }
                   4180:     return $tmp;
                   4181: }
                   4182: 
                   4183: sub resdata {
                   4184:     my ($name,$domain,$type,@which)=@_;
                   4185:     my $result;
                   4186:     if ($type eq 'course') {
                   4187: 	$result=&get_courseresdata($name,$domain);
                   4188:     } elsif ($type eq 'user') {
                   4189: 	$result=&get_userresdata($name,$domain);
                   4190:     }
                   4191:     if (!ref($result)) { return $result; }    
1.251     albertel 4192:     foreach my $item (@which) {
1.417     albertel 4193: 	if (defined($result->{$item})) {
                   4194: 	    return $result->{$item};
1.251     albertel 4195: 	}
1.250     albertel 4196:     }
1.291     albertel 4197:     return undef;
1.200     www      4198: }
                   4199: 
1.379     matthew  4200: #
                   4201: # EXT resource caching routines
                   4202: #
                   4203: 
                   4204: sub clear_EXT_cache_status {
1.383     albertel 4205:     &delenv('cache.EXT.');
1.379     matthew  4206: }
                   4207: 
                   4208: sub EXT_cache_status {
                   4209:     my ($target_domain,$target_user) = @_;
1.383     albertel 4210:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 4211:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  4212:         # We know already the user has no data
                   4213:         return 1;
                   4214:     } else {
                   4215:         return 0;
                   4216:     }
                   4217: }
                   4218: 
                   4219: sub EXT_cache_set {
                   4220:     my ($target_domain,$target_user) = @_;
1.383     albertel 4221:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 4222:     #&appenv($cachename => time);
1.379     matthew  4223: }
                   4224: 
1.28      www      4225: # --------------------------------------------------------- Value of a Variable
1.58      www      4226: sub EXT {
1.395     albertel 4227:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218     albertel 4228: 
1.68      www      4229:     unless ($varname) { return ''; }
1.218     albertel 4230:     #get real user name/domain, courseid and symb
                   4231:     my $courseid;
1.359     albertel 4232:     my $publicuser;
1.427     www      4233:     if ($symbparm) {
                   4234: 	$symbparm=&get_symb_from_alias($symbparm);
                   4235:     }
1.218     albertel 4236:     if (!($uname && $udom)) {
1.360     albertel 4237:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  4238: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 4239:       if (!$symbparm) {	$symbparm=$cursymb; }
                   4240:     } else {
1.620     albertel 4241: 	$courseid=$env{'request.course.id'};
1.218     albertel 4242:     }
1.48      www      4243:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   4244:     my $rest;
1.320     albertel 4245:     if (defined($therest[0])) {
1.48      www      4246:        $rest=join('.',@therest);
                   4247:     } else {
                   4248:        $rest='';
                   4249:     }
1.320     albertel 4250: 
1.57      www      4251:     my $qualifierrest=$qualifier;
                   4252:     if ($rest) { $qualifierrest.='.'.$rest; }
                   4253:     my $spacequalifierrest=$space;
                   4254:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      4255:     if ($realm eq 'user') {
1.48      www      4256: # --------------------------------------------------------------- user.resource
                   4257: 	if ($space eq 'resource') {
1.618     albertel 4258: 	    if (defined($Apache::lonhomework::parsing_a_problem) ||
                   4259: 		defined($Apache::lonhomework::parsing_a_task)) {
1.335     albertel 4260: 		return $Apache::lonhomework::history{$qualifierrest};
                   4261: 	    } else {
1.359     albertel 4262: 		my %restored;
1.620     albertel 4263: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 4264: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   4265: 		} else {
                   4266: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   4267: 		}
1.335     albertel 4268: 		return $restored{$qualifierrest};
                   4269: 	    }
1.48      www      4270: # ----------------------------------------------------------------- user.access
                   4271:         } elsif ($space eq 'access') {
1.218     albertel 4272: 	    # FIXME - not supporting calls for a specific user
1.48      www      4273:             return &allowed($qualifier,$rest);
                   4274: # ------------------------------------------ user.preferences, user.environment
                   4275:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 4276: 	    if (($uname eq $env{'user.name'}) &&
                   4277: 		($udom eq $env{'user.domain'})) {
                   4278: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 4279: 	    } else {
1.359     albertel 4280: 		my %returnhash;
                   4281: 		if (!$publicuser) {
                   4282: 		    %returnhash=&userenvironment($udom,$uname,
                   4283: 						 $qualifierrest);
                   4284: 		}
1.218     albertel 4285: 		return $returnhash{$qualifierrest};
                   4286: 	    }
1.48      www      4287: # ----------------------------------------------------------------- user.course
                   4288:         } elsif ($space eq 'course') {
1.218     albertel 4289: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4290:             return $env{join('.',('request.course',$qualifier))};
1.48      www      4291: # ------------------------------------------------------------------- user.role
                   4292:         } elsif ($space eq 'role') {
1.218     albertel 4293: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4294:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      4295:             if ($qualifier eq 'value') {
                   4296: 		return $role;
                   4297:             } elsif ($qualifier eq 'extent') {
                   4298:                 return $where;
                   4299:             }
                   4300: # ----------------------------------------------------------------- user.domain
                   4301:         } elsif ($space eq 'domain') {
1.218     albertel 4302:             return $udom;
1.48      www      4303: # ------------------------------------------------------------------- user.name
                   4304:         } elsif ($space eq 'name') {
1.218     albertel 4305:             return $uname;
1.48      www      4306: # ---------------------------------------------------- Any other user namespace
1.29      www      4307:         } else {
1.359     albertel 4308: 	    my %reply;
                   4309: 	    if (!$publicuser) {
                   4310: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   4311: 	    }
                   4312: 	    return $reply{$qualifierrest};
1.48      www      4313:         }
1.236     www      4314:     } elsif ($realm eq 'query') {
                   4315: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 4316:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   4317: 						[$spacequalifierrest]);
1.620     albertel 4318: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      4319:    } elsif ($realm eq 'request') {
1.48      www      4320: # ------------------------------------------------------------- request.browser
                   4321:         if ($space eq 'browser') {
1.430     www      4322: 	    if ($qualifier eq 'textremote') {
                   4323: 		if (&mt('textual_remote_display') eq 'on') {
                   4324: 		    return 1;
                   4325: 		} else {
                   4326: 		    return 0;
                   4327: 		}
                   4328: 	    } else {
1.620     albertel 4329: 		return $env{'browser.'.$qualifier};
1.430     www      4330: 	    }
1.57      www      4331: # ------------------------------------------------------------ request.filename
                   4332:         } else {
1.620     albertel 4333:             return $env{'request.'.$spacequalifierrest};
1.29      www      4334:         }
1.28      www      4335:     } elsif ($realm eq 'course') {
1.48      www      4336: # ---------------------------------------------------------- course.description
1.620     albertel 4337:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      4338:     } elsif ($realm eq 'resource') {
1.165     www      4339: 
1.395     albertel 4340: 	my $section;
1.620     albertel 4341: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 4342: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   4343: 	}
1.593     albertel 4344: 	my ($courselevelm,$courselevel);
1.539     albertel 4345: 	if ($symbparm && defined($courseid) && 
1.620     albertel 4346: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      4347: 
1.218     albertel 4348: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      4349: 
1.60      www      4350: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 4351: 	    my $symbp=$symbparm;
1.409     www      4352: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 4353: 
                   4354: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   4355: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   4356: 
1.620     albertel 4357: 	    if (($env{'user.name'} eq $uname) &&
                   4358: 		($env{'user.domain'} eq $udom)) {
                   4359: 		$section=$env{'request.course.sec'};
1.218     albertel 4360: 	    } else {
1.539     albertel 4361: 		if (! defined($usection)) {
1.551     albertel 4362: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 4363: 		} else {
                   4364: 		    $section = $usection;
                   4365: 		}
1.218     albertel 4366: 	    }
                   4367: 
                   4368: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   4369: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   4370: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   4371: 
1.593     albertel 4372: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 4373: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 4374: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      4375: 
1.60      www      4376: # ----------------------------------------------------------- first, check user
1.624     albertel 4377: 
                   4378: 	    my $userreply=&resdata($uname,$udom,'user',
                   4379: 				       ($courselevelr,$courselevelm,
                   4380: 					$courselevel));
                   4381: 
                   4382: 	    if (defined($userreply)) { return $userreply; }
1.95      www      4383: 
1.594     albertel 4384: # ------------------------------------------------ second, check some of course
1.96      www      4385: 
1.624     albertel 4386: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   4387: 				     $env{'course.'.$courseid.'.domain'},
                   4388: 				     'course',
                   4389: 				     ($seclevelr,$seclevelm,$seclevel,
                   4390: 				      $courselevelr));
1.287     albertel 4391: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      4392: 
1.60      www      4393: # ------------------------------------------------------ third, check map parms
1.218     albertel 4394: 	    my %parmhash=();
                   4395: 	    my $thisparm='';
                   4396: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 4397: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 4398: 		    &GDBM_READER(),0640)) {
1.218     albertel 4399: 		$thisparm=$parmhash{$symbparm};
                   4400: 		untie(%parmhash);
                   4401: 	    }
                   4402: 	    if ($thisparm) { return $thisparm; }
                   4403: 	}
1.594     albertel 4404: # ------------------------------------------ fourth, look in resource metadata
1.71      www      4405: 
1.218     albertel 4406: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 4407: 	my $filename;
                   4408: 	if (!$symbparm) { $symbparm=&symbread(); }
                   4409: 	if ($symbparm) {
1.409     www      4410: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 4411: 	} else {
1.620     albertel 4412: 	    $filename=$env{'request.filename'};
1.282     albertel 4413: 	}
                   4414: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 4415: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 4416: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 4417: 	if (defined($metadata)) { return $metadata; }
1.142     www      4418: 
1.594     albertel 4419: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 4420: 	if ($symbparm && defined($courseid) && 
1.620     albertel 4421: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 4422: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   4423: 				     $env{'course.'.$courseid.'.domain'},
                   4424: 				     'course',
                   4425: 				     ($courselevelm,$courselevel));
1.593     albertel 4426: 	    if (defined($coursereply)) { return $coursereply; }
                   4427: 	}
1.145     www      4428: # ------------------------------------------------------------------ Cascade up
1.218     albertel 4429: 	unless ($space eq '0') {
1.336     albertel 4430: 	    my @parts=split(/_/,$space);
                   4431: 	    my $id=pop(@parts);
                   4432: 	    my $part=join('_',@parts);
                   4433: 	    if ($part eq '') { $part='0'; }
                   4434: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 4435: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 4436: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 4437: 	}
1.395     albertel 4438: 	if ($recurse) { return undef; }
                   4439: 	my $pack_def=&packages_tab_default($filename,$varname);
                   4440: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      4441: 
1.48      www      4442: # ---------------------------------------------------- Any other user namespace
                   4443:     } elsif ($realm eq 'environment') {
                   4444: # ----------------------------------------------------------------- environment
1.620     albertel 4445: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   4446: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 4447: 	} else {
                   4448: 	    my %returnhash=&userenvironment($udom,$uname,
                   4449: 					    $spacequalifierrest);
                   4450: 	    return $returnhash{$spacequalifierrest};
                   4451: 	}
1.28      www      4452:     } elsif ($realm eq 'system') {
1.48      www      4453: # ----------------------------------------------------------------- system.time
                   4454: 	if ($space eq 'time') {
                   4455: 	    return time;
                   4456:         }
1.28      www      4457:     }
1.48      www      4458:     return '';
1.61      www      4459: }
                   4460: 
1.395     albertel 4461: sub packages_tab_default {
                   4462:     my ($uri,$varname)=@_;
                   4463:     my (undef,$part,$name)=split(/\./,$varname);
                   4464:     my $packages=&metadata($uri,'packages');
                   4465:     foreach my $package (split(/,/,$packages)) {
                   4466: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 4467: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   4468: 	    return $packagetab{"$pack_type&$name&default"};
                   4469: 	}
1.585     albertel 4470: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 4471: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   4472: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 4473: 	}
                   4474:     }
                   4475:     return undef;
                   4476: }
                   4477: 
1.334     albertel 4478: sub add_prefix_and_part {
                   4479:     my ($prefix,$part)=@_;
                   4480:     my $keyroot;
                   4481:     if (defined($prefix) && $prefix !~ /^__/) {
                   4482: 	# prefix that has a part already
                   4483: 	$keyroot=$prefix;
                   4484:     } elsif (defined($prefix)) {
                   4485: 	# prefix that is missing a part
                   4486: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   4487:     } else {
                   4488: 	# no prefix at all
                   4489: 	if (defined($part)) { $keyroot='_'.$part; }
                   4490:     }
                   4491:     return $keyroot;
                   4492: }
                   4493: 
1.71      www      4494: # ---------------------------------------------------------------- Get metadata
                   4495: 
1.599     albertel 4496: my %metaentry;
1.71      www      4497: sub metadata {
1.176     www      4498:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      4499:     $uri=&declutter($uri);
1.288     albertel 4500:     # if it is a non metadata possible uri return quickly
1.529     albertel 4501:     if (($uri eq '') || 
                   4502: 	(($uri =~ m|^/*adm/|) && 
                   4503: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 4504:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 4505: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 4506: 	return undef;
1.288     albertel 4507:     }
1.73      www      4508:     my $filename=$uri;
                   4509:     $uri=~s/\.meta$//;
1.172     www      4510: #
                   4511: # Is the metadata already cached?
1.177     www      4512: # Look at timestamp of caching
1.172     www      4513: # Everything is cached by the main uri, libraries are never directly cached
                   4514: #
1.428     albertel 4515:     if (!defined($liburi)) {
1.599     albertel 4516: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 4517: 	if (defined($cached)) { return $result->{':'.$what}; }
                   4518:     }
                   4519:     {
1.172     www      4520: #
                   4521: # Is this a recursive call for a library?
                   4522: #
1.599     albertel 4523: #	if (! exists($metacache{$uri})) {
                   4524: #	    $metacache{$uri}={};
                   4525: #	}
1.171     www      4526:         if ($liburi) {
                   4527: 	    $liburi=&declutter($liburi);
                   4528:             $filename=$liburi;
1.401     bowersj2 4529:         } else {
1.599     albertel 4530: 	    &devalidate_cache_new('meta',$uri);
                   4531: 	    undef(%metaentry);
1.401     bowersj2 4532: 	}
1.140     www      4533:         my %metathesekeys=();
1.73      www      4534:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 4535: 	my $metastring;
1.609     banghart 4536: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 4537: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 4538: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 4539: 	    $metastring=&getfile($file);
1.489     albertel 4540: 	}
1.208     albertel 4541:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      4542:         my $token;
1.140     www      4543:         undef %metathesekeys;
1.71      www      4544:         while ($token=$parser->get_token) {
1.339     albertel 4545: 	    if ($token->[0] eq 'S') {
                   4546: 		if (defined($token->[2]->{'package'})) {
1.172     www      4547: #
                   4548: # This is a package - get package info
                   4549: #
1.339     albertel 4550: 		    my $package=$token->[2]->{'package'};
                   4551: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   4552: 		    if (defined($token->[2]->{'id'})) { 
                   4553: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   4554: 		    }
1.599     albertel 4555: 		    if ($metaentry{':packages'}) {
                   4556: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 4557: 		    } else {
1.599     albertel 4558: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 4559: 		    }
1.613     albertel 4560: 		    foreach (sort keys %packagetab) {
1.432     albertel 4561: 			my $part=$keyroot;
                   4562: 			$part=~s/^\_//;
                   4563: 			if ($_=~/^\Q$package\E\&/ || 
                   4564: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 4565: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 4566: 			    # ignore package.tab specified default values
                   4567:                             # here &package_tab_default() will fetch those
                   4568: 			    if ($subp eq 'default') { next; }
1.339     albertel 4569: 			    my $value=$packagetab{$_};
1.432     albertel 4570: 			    my $unikey;
                   4571: 			    if ($pack =~ /_0$/) {
                   4572: 				$unikey='parameter_0_'.$name;
                   4573: 				$part=0;
                   4574: 			    } else {
                   4575: 				$unikey='parameter'.$keyroot.'_'.$name;
                   4576: 			    }
1.339     albertel 4577: 			    if ($subp eq 'display') {
                   4578: 				$value.=' [Part: '.$part.']';
                   4579: 			    }
1.599     albertel 4580: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 4581: 			    $metathesekeys{$unikey}=1;
1.599     albertel 4582: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   4583: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 4584: 			    }
1.599     albertel 4585: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   4586: 				$metaentry{':'.$unikey}=
                   4587: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 4588: 			    }
1.339     albertel 4589: 			}
                   4590: 		    }
                   4591: 		} else {
1.172     www      4592: #
                   4593: # This is not a package - some other kind of start tag
1.339     albertel 4594: #
                   4595: 		    my $entry=$token->[1];
                   4596: 		    my $unikey;
                   4597: 		    if ($entry eq 'import') {
                   4598: 			$unikey='';
                   4599: 		    } else {
                   4600: 			$unikey=$entry;
                   4601: 		    }
                   4602: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   4603: 
                   4604: 		    if (defined($token->[2]->{'id'})) { 
                   4605: 			$unikey.='_'.$token->[2]->{'id'}; 
                   4606: 		    }
1.175     www      4607: 
1.339     albertel 4608: 		    if ($entry eq 'import') {
1.175     www      4609: #
                   4610: # Importing a library here
1.339     albertel 4611: #
                   4612: 			if ($depthcount<20) {
                   4613: 			    my $location=$parser->get_text('/import');
                   4614: 			    my $dir=$filename;
                   4615: 			    $dir=~s|[^/]*$||;
                   4616: 			    $location=&filelocation($dir,$location);
                   4617: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   4618: 							       $location,$unikey,
                   4619: 							       $depthcount+1)))) {
1.599     albertel 4620: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 4621: 				$metathesekeys{$_}=1;
                   4622: 			    }
                   4623: 			}
                   4624: 		    } else { 
                   4625: 			
                   4626: 			if (defined($token->[2]->{'name'})) { 
                   4627: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   4628: 			}
                   4629: 			$metathesekeys{$unikey}=1;
                   4630: 			foreach (@{$token->[3]}) {
1.599     albertel 4631: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 4632: 			}
                   4633: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 4634: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 4635: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   4636: 		 # only ws inside the tag, and not in default, so use default
                   4637: 		 # as value
1.599     albertel 4638: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 4639: 			} else {
1.321     albertel 4640: 		  # either something interesting inside the tag or default
                   4641:                   # uninteresting
1.599     albertel 4642: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 4643: 			}
1.172     www      4644: # end of not-a-package not-a-library import
1.339     albertel 4645: 		    }
1.172     www      4646: # end of not-a-package start tag
1.339     albertel 4647: 		}
1.172     www      4648: # the next is the end of "start tag"
1.339     albertel 4649: 	    }
                   4650: 	}
1.483     albertel 4651: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   4652: 	foreach my $key (sort(keys(%packagetab))) {
                   4653: 	    #&logthis("extsion1 $extension $key !!");
                   4654: 	    #no specific packages #how's our extension
                   4655: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 4656: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 4657: 					 \%metathesekeys);
                   4658: 	}
1.599     albertel 4659: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 4660: 	    foreach my $key (sort(keys(%packagetab))) {
                   4661: 		#no specific packages well let's get default then
                   4662: 		if ($key!~/^default&/) { next; }
1.488     albertel 4663: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 4664: 					     \%metathesekeys);
                   4665: 	    }
                   4666: 	}
1.338     www      4667: # are there custom rights to evaluate
1.599     albertel 4668: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 4669: 
1.338     www      4670:     #
                   4671:     # Importing a rights file here
1.339     albertel 4672:     #
                   4673: 	    unless ($depthcount) {
1.599     albertel 4674: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 4675: 		my $dir=$filename;
                   4676: 		$dir=~s|[^/]*$||;
                   4677: 		$location=&filelocation($dir,$location);
                   4678: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   4679: 						   $location,'_rights',
                   4680: 						   $depthcount+1)))) {
1.599     albertel 4681: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 4682: 		    $metathesekeys{$_}=1;
                   4683: 		}
                   4684: 	    }
                   4685: 	}
1.599     albertel 4686: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   4687: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   4688: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.623     albertel 4689: 	&do_cache_new('meta',$uri,\%metaentry,60*60*24);
1.177     www      4690: # this is the end of "was not already recently cached
1.71      www      4691:     }
1.599     albertel 4692:     return $metaentry{':'.$what};
1.261     albertel 4693: }
                   4694: 
1.488     albertel 4695: sub metadata_create_package_def {
1.483     albertel 4696:     my ($uri,$key,$package,$metathesekeys)=@_;
                   4697:     my ($pack,$name,$subp)=split(/\&/,$key);
                   4698:     if ($subp eq 'default') { next; }
                   4699:     
1.599     albertel 4700:     if (defined($metaentry{':packages'})) {
                   4701: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 4702:     } else {
1.599     albertel 4703: 	$metaentry{':packages'}=$package;
1.483     albertel 4704:     }
                   4705:     my $value=$packagetab{$key};
                   4706:     my $unikey;
                   4707:     $unikey='parameter_0_'.$name;
1.599     albertel 4708:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 4709:     $$metathesekeys{$unikey}=1;
1.599     albertel 4710:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   4711: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 4712:     }
1.599     albertel 4713:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   4714: 	$metaentry{':'.$unikey}=
                   4715: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 4716:     }
                   4717: }
                   4718: 
1.261     albertel 4719: sub metadata_generate_part0 {
                   4720:     my ($metadata,$metacache,$uri) = @_;
                   4721:     my %allnames;
                   4722:     foreach my $metakey (sort keys %$metadata) {
                   4723: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 4724: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   4725: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 4726: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 4727: 	    $allnames{$name}=$part;
                   4728: 	  }
                   4729: 	}
                   4730:     }
                   4731:     foreach my $name (keys(%allnames)) {
                   4732:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 4733:       my $key=":parameter_0_$name";
1.261     albertel 4734:       $$metacache{"$key.part"}='0';
                   4735:       $$metacache{"$key.name"}=$name;
1.428     albertel 4736:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 4737: 					   $allnames{$name}.'_'.$name.
                   4738: 					   '.type'};
1.428     albertel 4739:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 4740: 			     '.display'};
                   4741:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
1.479     albertel 4742:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 4743:       $$metacache{"$key.display"}=$olddis;
                   4744:     }
1.71      www      4745: }
                   4746: 
1.301     www      4747: # ------------------------------------------------- Get the title of a resource
                   4748: 
                   4749: sub gettitle {
                   4750:     my $urlsymb=shift;
                   4751:     my $symb=&symbread($urlsymb);
1.534     albertel 4752:     if ($symb) {
1.620     albertel 4753: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 4754: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 4755: 	if (defined($cached)) { 
                   4756: 	    return $result;
                   4757: 	}
1.534     albertel 4758: 	my ($map,$resid,$url)=&decode_symb($symb);
                   4759: 	my $title='';
                   4760: 	my %bighash;
1.620     albertel 4761: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 4762: 		&GDBM_READER(),0640)) {
                   4763: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   4764: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   4765: 	    untie %bighash;
                   4766: 	}
                   4767: 	$title=~s/\&colon\;/\:/gs;
                   4768: 	if ($title) {
1.599     albertel 4769: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 4770: 	}
                   4771: 	$urlsymb=$url;
                   4772:     }
                   4773:     my $title=&metadata($urlsymb,'title');
                   4774:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   4775:     return $title;
1.301     www      4776: }
1.613     albertel 4777: 
1.614     albertel 4778: sub get_slot {
                   4779:     my ($which,$cnum,$cdom)=@_;
                   4780:     if (!$cnum || !$cdom) {
                   4781: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 4782: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   4783: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 4784:     }
                   4785:     my %slotinfo=&get('slots',[$which],$cdom,$cnum);
                   4786:     &Apache::lonhomework::showhash(%slotinfo);
                   4787:     my ($tmp)=keys(%slotinfo);
                   4788:     if ($tmp=~/^error:/) { return (); }
1.616     albertel 4789:     if (ref($slotinfo{$which}) eq 'HASH') {
                   4790: 	return %{$slotinfo{$which}};
                   4791:     }
                   4792:     return $slotinfo{$which};
1.614     albertel 4793: }
1.31      www      4794: # ------------------------------------------------- Update symbolic store links
                   4795: 
                   4796: sub symblist {
                   4797:     my ($mapname,%newhash)=@_;
1.438     www      4798:     $mapname=&deversion(&declutter($mapname));
1.31      www      4799:     my %hash;
1.620     albertel 4800:     if (($env{'request.course.fn'}) && (%newhash)) {
                   4801:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 4802:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 4803: 	    foreach (keys %newhash) {
1.601     albertel 4804:                 $hash{declutter($_)}=&encode_symb($mapname,$newhash{$_}->[1],
                   4805: 						  $newhash{$_}->[0]);
1.191     harris41 4806:             }
1.31      www      4807:             if (untie(%hash)) {
                   4808: 		return 'ok';
                   4809:             }
                   4810:         }
                   4811:     }
                   4812:     return 'error';
1.212     www      4813: }
                   4814: 
                   4815: # --------------------------------------------------------------- Verify a symb
                   4816: 
                   4817: sub symbverify {
1.510     www      4818:     my ($symb,$thisurl)=@_;
                   4819:     my $thisfn=$thisurl;
                   4820: # wrapper not part of symbs
                   4821:     $thisfn=~s/^\/adm\/wrapper//;
1.439     www      4822:     $thisfn=&declutter($thisfn);
1.215     www      4823: # direct jump to resource in page or to a sequence - will construct own symbs
                   4824:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   4825: # check URL part
1.409     www      4826:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      4827: 
1.431     www      4828:     unless ($url eq $thisfn) { return 0; }
1.213     www      4829: 
1.216     www      4830:     $symb=&symbclean($symb);
1.510     www      4831:     $thisurl=&deversion($thisurl);
1.439     www      4832:     $thisfn=&deversion($thisfn);
1.213     www      4833: 
                   4834:     my %bighash;
                   4835:     my $okay=0;
1.431     www      4836: 
1.620     albertel 4837:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 4838:                             &GDBM_READER(),0640)) {
1.510     www      4839:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      4840:         unless ($ids) { 
1.510     www      4841:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      4842:         }
                   4843:         if ($ids) {
                   4844: # ------------------------------------------------------------------- Has ID(s)
                   4845: 	    foreach (split(/\,/,$ids)) {
                   4846:                my ($mapid,$resid)=split(/\./,$_);
                   4847:                if (
                   4848:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   4849:    eq $symb) { 
1.620     albertel 4850: 		   if (($env{'request.role.adv'}) ||
                   4851: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 4852: 		       $okay=1; 
                   4853: 		   }
                   4854: 	       }
1.216     www      4855: 	   }
                   4856:         }
1.213     www      4857: 	untie(%bighash);
                   4858:     }
                   4859:     return $okay;
1.31      www      4860: }
                   4861: 
1.210     www      4862: # --------------------------------------------------------------- Clean-up symb
                   4863: 
                   4864: sub symbclean {
                   4865:     my $symb=shift;
1.568     albertel 4866:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      4867: # remove version from map
                   4868:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      4869: 
1.210     www      4870: # remove version from URL
                   4871:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      4872: 
1.507     www      4873: # remove wrapper
                   4874: 
1.510     www      4875:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.210     www      4876:     return $symb;
1.409     www      4877: }
                   4878: 
                   4879: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 4880: 
                   4881: sub encode_symb {
                   4882:     my ($map,$resid,$url)=@_;
                   4883:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   4884: }
1.409     www      4885: 
                   4886: sub decode_symb {
1.568     albertel 4887:     my $symb=shift;
                   4888:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   4889:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      4890:     return (&fixversion($map),$resid,&fixversion($url));
                   4891: }
                   4892: 
                   4893: sub fixversion {
                   4894:     my $fn=shift;
1.609     banghart 4895:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      4896:     my %bighash;
                   4897:     my $uri=&clutter($fn);
1.620     albertel 4898:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      4899: # is this cached?
1.599     albertel 4900:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      4901:     if (defined($cached)) { return $result; }
                   4902: # unfortunately not cached, or expired
1.620     albertel 4903:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      4904: 	    &GDBM_READER(),0640)) {
                   4905:  	if ($bighash{'version_'.$uri}) {
                   4906:  	    my $version=$bighash{'version_'.$uri};
1.444     www      4907:  	    unless (($version eq 'mostrecent') || 
                   4908: 		    ($version==&getversion($uri))) {
1.440     www      4909:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   4910:  	    }
                   4911:  	}
                   4912:  	untie %bighash;
1.413     www      4913:     }
1.599     albertel 4914:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      4915: }
                   4916: 
                   4917: sub deversion {
                   4918:     my $url=shift;
                   4919:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   4920:     return $url;
1.210     www      4921: }
                   4922: 
1.31      www      4923: # ------------------------------------------------------ Return symb list entry
                   4924: 
                   4925: sub symbread {
1.249     www      4926:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 4927:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 4928:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      4929: # no filename provided? try from environment
1.44      www      4930:     unless ($thisfn) {
1.620     albertel 4931:         if ($env{'request.symb'}) {
                   4932: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 4933: 	}
1.620     albertel 4934: 	$thisfn=$env{'request.filename'};
1.44      www      4935:     }
1.569     albertel 4936:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      4937: # is that filename actually a symb? Verify, clean, and return
                   4938:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 4939: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 4940: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 4941: 	}
1.242     www      4942:     }
1.44      www      4943:     $thisfn=declutter($thisfn);
1.31      www      4944:     my %hash;
1.37      www      4945:     my %bighash;
                   4946:     my $syval='';
1.620     albertel 4947:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  4948:         my $targetfn = $thisfn;
1.609     banghart 4949:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  4950:             $targetfn = 'adm/wrapper/'.$thisfn;
                   4951:         }
1.620     albertel 4952:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 4953:                       &GDBM_READER(),0640)) {
1.481     raeburn  4954: 	    $syval=$hash{$targetfn};
1.37      www      4955:             untie(%hash);
                   4956:         }
                   4957: # ---------------------------------------------------------- There was an entry
                   4958:         if ($syval) {
1.601     albertel 4959: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 4960: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 4961: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 4962: 		    #return $env{$cache_str}='';
1.601     albertel 4963: 		#}    
                   4964: 		#$syval.=$1;
                   4965: 	    #}
1.37      www      4966:         } else {
                   4967: # ------------------------------------------------------- Was not in symb table
1.620     albertel 4968:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 4969:                             &GDBM_READER(),0640)) {
1.37      www      4970: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      4971:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      4972:               unless ($ids) { 
                   4973:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      4974:               }
                   4975:               unless ($ids) {
                   4976: # alias?
                   4977: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      4978:               }
1.37      www      4979:               if ($ids) {
                   4980: # ------------------------------------------------------------------- Has ID(s)
                   4981:                  my @possibilities=split(/\,/,$ids);
1.39      www      4982:                  if ($#possibilities==0) {
                   4983: # ----------------------------------------------- There is only one possibility
1.37      www      4984: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 4985: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   4986: 						    $resid,$thisfn);
1.249     www      4987:                  } elsif (!$donotrecurse) {
1.39      www      4988: # ------------------------------------------ There is more than one possibility
                   4989:                      my $realpossible=0;
1.191     harris41 4990:                      foreach (@possibilities) {
1.39      www      4991: 			 my $file=$bighash{'src_'.$_};
                   4992:                          if (&allowed('bre',$file)) {
                   4993:          		    my ($mapid,$resid)=split(/\./,$_);
                   4994:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   4995: 				$realpossible++;
1.626     albertel 4996:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   4997: 						    $resid,$thisfn);
1.39      www      4998:                             }
                   4999: 			 }
1.191     harris41 5000:                      }
1.39      www      5001: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      5002:                  } else {
                   5003:                      $syval='';
1.37      www      5004:                  }
                   5005: 	      }
                   5006:               untie(%bighash)
1.481     raeburn  5007:            }
1.31      www      5008:         }
1.62      www      5009:         if ($syval) {
1.620     albertel 5010: 	    return $env{$cache_str}=$syval;
1.62      www      5011:         }
1.31      www      5012:     }
1.44      www      5013:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 5014:     return $env{$cache_str}='';
1.31      www      5015: }
                   5016: 
                   5017: # ---------------------------------------------------------- Return random seed
                   5018: 
1.32      www      5019: sub numval {
                   5020:     my $txt=shift;
                   5021:     $txt=~tr/A-J/0-9/;
                   5022:     $txt=~tr/a-j/0-9/;
                   5023:     $txt=~tr/K-T/0-9/;
                   5024:     $txt=~tr/k-t/0-9/;
                   5025:     $txt=~tr/U-Z/0-5/;
                   5026:     $txt=~tr/u-z/0-5/;
                   5027:     $txt=~s/\D//g;
1.564     albertel 5028:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      5029:     return int($txt);
1.368     albertel 5030: }
                   5031: 
1.484     albertel 5032: sub numval2 {
                   5033:     my $txt=shift;
                   5034:     $txt=~tr/A-J/0-9/;
                   5035:     $txt=~tr/a-j/0-9/;
                   5036:     $txt=~tr/K-T/0-9/;
                   5037:     $txt=~tr/k-t/0-9/;
                   5038:     $txt=~tr/U-Z/0-5/;
                   5039:     $txt=~tr/u-z/0-5/;
                   5040:     $txt=~s/\D//g;
                   5041:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5042:     my $total;
                   5043:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5044:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5045:     return int($total);
                   5046: }
                   5047: 
1.575     albertel 5048: sub numval3 {
                   5049:     use integer;
                   5050:     my $txt=shift;
                   5051:     $txt=~tr/A-J/0-9/;
                   5052:     $txt=~tr/a-j/0-9/;
                   5053:     $txt=~tr/K-T/0-9/;
                   5054:     $txt=~tr/k-t/0-9/;
                   5055:     $txt=~tr/U-Z/0-5/;
                   5056:     $txt=~tr/u-z/0-5/;
                   5057:     $txt=~s/\D//g;
                   5058:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5059:     my $total;
                   5060:     foreach my $val (@txts) { $total+=$val; }
                   5061:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5062:     return $total;
                   5063: }
                   5064: 
1.368     albertel 5065: sub latest_rnd_algorithm_id {
1.575     albertel 5066:     return '64bit4';
1.366     albertel 5067: }
1.32      www      5068: 
1.503     albertel 5069: sub get_rand_alg {
                   5070:     my ($courseid)=@_;
                   5071:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   5072:     if ($courseid) {
1.620     albertel 5073: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 5074:     }
                   5075:     return &latest_rnd_algorithm_id();
                   5076: }
                   5077: 
1.562     albertel 5078: sub validCODE {
                   5079:     my ($CODE)=@_;
                   5080:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5081:     return 0;
                   5082: }
                   5083: 
1.491     albertel 5084: sub getCODE {
1.620     albertel 5085:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 5086:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   5087: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   5088: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5089: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5090:     }
                   5091:     return undef;
                   5092: }
                   5093: 
1.31      www      5094: sub rndseed {
1.155     albertel 5095:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5096: 
                   5097:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5098:     if (!$symb) {
1.366     albertel 5099: 	unless ($symb=$wsymb) { return time; }
                   5100:     }
                   5101:     if (!$courseid) { $courseid=$wcourseid; }
                   5102:     if (!$domain) { $domain=$wdomain; }
                   5103:     if (!$username) { $username=$wusername }
1.503     albertel 5104:     my $which=&get_rand_alg();
1.491     albertel 5105:     if (defined(&getCODE())) {
1.575     albertel 5106: 	if ($which eq '64bit4') {
                   5107: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5108: 	} else {
                   5109: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5110: 	}
                   5111:     } elsif ($which eq '64bit4') {
                   5112: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 5113:     } elsif ($which eq '64bit3') {
                   5114: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 5115:     } elsif ($which eq '64bit2') {
                   5116: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 5117:     } elsif ($which eq '64bit') {
                   5118: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   5119:     }
                   5120:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   5121: }
                   5122: 
                   5123: sub rndseed_32bit {
                   5124:     my ($symb,$courseid,$domain,$username)=@_;
                   5125:     {
                   5126: 	use integer;
                   5127: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   5128: 	my $symbseed=numval($symb) << 22;
                   5129: 	my $namechck=unpack("%32C*",$username) << 17;
                   5130: 	my $nameseed=numval($username) << 12;
                   5131: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   5132: 	my $courseseed=unpack("%32C*",$courseid);
                   5133: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   5134: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5135: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5136: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 5137: 	return $num;
                   5138:     }
                   5139: }
                   5140: 
                   5141: sub rndseed_64bit {
                   5142:     my ($symb,$courseid,$domain,$username)=@_;
                   5143:     {
                   5144: 	use integer;
                   5145: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   5146: 	my $symbseed=numval($symb) << 10;
                   5147: 	my $namechck=unpack("%32S*",$username);
                   5148: 	
                   5149: 	my $nameseed=numval($username) << 21;
                   5150: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   5151: 	my $courseseed=unpack("%32S*",$courseid);
                   5152: 	
                   5153: 	my $num1=$symbchck+$symbseed+$namechck;
                   5154: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5155: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5156: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5157: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5158: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 5159: 	return "$num1,$num2";
1.155     albertel 5160:     }
1.366     albertel 5161: }
                   5162: 
1.443     albertel 5163: sub rndseed_64bit2 {
                   5164:     my ($symb,$courseid,$domain,$username)=@_;
                   5165:     {
                   5166: 	use integer;
                   5167: 	# strings need to be an even # of cahracters long, it it is odd the
                   5168:         # last characters gets thrown away
                   5169: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5170: 	my $symbseed=numval($symb) << 10;
                   5171: 	my $namechck=unpack("%32S*",$username.' ');
                   5172: 	
                   5173: 	my $nameseed=numval($username) << 21;
1.501     albertel 5174: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5175: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5176: 	
                   5177: 	my $num1=$symbchck+$symbseed+$namechck;
                   5178: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5179: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5180: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   5181: 	return "$num1,$num2";
                   5182:     }
                   5183: }
                   5184: 
                   5185: sub rndseed_64bit3 {
                   5186:     my ($symb,$courseid,$domain,$username)=@_;
                   5187:     {
                   5188: 	use integer;
                   5189: 	# strings need to be an even # of cahracters long, it it is odd the
                   5190:         # last characters gets thrown away
                   5191: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5192: 	my $symbseed=numval2($symb) << 10;
                   5193: 	my $namechck=unpack("%32S*",$username.' ');
                   5194: 	
                   5195: 	my $nameseed=numval2($username) << 21;
1.443     albertel 5196: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5197: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5198: 	
                   5199: 	my $num1=$symbchck+$symbseed+$namechck;
                   5200: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5201: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 5202: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5203: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5204: 	
1.503     albertel 5205: 	return "$num1:$num2";
1.443     albertel 5206:     }
                   5207: }
                   5208: 
1.575     albertel 5209: sub rndseed_64bit4 {
                   5210:     my ($symb,$courseid,$domain,$username)=@_;
                   5211:     {
                   5212: 	use integer;
                   5213: 	# strings need to be an even # of cahracters long, it it is odd the
                   5214:         # last characters gets thrown away
                   5215: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5216: 	my $symbseed=numval3($symb) << 10;
                   5217: 	my $namechck=unpack("%32S*",$username.' ');
                   5218: 	
                   5219: 	my $nameseed=numval3($username) << 21;
                   5220: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5221: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5222: 	
                   5223: 	my $num1=$symbchck+$symbseed+$namechck;
                   5224: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5225: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5226: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5227: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5228: 	
                   5229: 	return "$num1:$num2";
                   5230:     }
                   5231: }
                   5232: 
1.366     albertel 5233: sub rndseed_CODE_64bit {
                   5234:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 5235:     {
1.366     albertel 5236: 	use integer;
1.443     albertel 5237: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 5238: 	my $symbseed=numval2($symb);
1.491     albertel 5239: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5240: 	my $CODEseed=numval(&getCODE());
1.443     albertel 5241: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 5242: 	my $num1=$symbseed+$CODEchck;
                   5243: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5244: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 5245: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 5246: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5247: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 5248: 	return "$num1:$num2";
1.366     albertel 5249:     }
                   5250: }
                   5251: 
1.575     albertel 5252: sub rndseed_CODE_64bit4 {
                   5253:     my ($symb,$courseid,$domain,$username)=@_;
                   5254:     {
                   5255: 	use integer;
                   5256: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   5257: 	my $symbseed=numval3($symb);
                   5258: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5259: 	my $CODEseed=numval3(&getCODE());
                   5260: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5261: 	my $num1=$symbseed+$CODEchck;
                   5262: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5263: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   5264: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   5265: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5266: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   5267: 	return "$num1:$num2";
                   5268:     }
                   5269: }
                   5270: 
1.366     albertel 5271: sub setup_random_from_rndseed {
                   5272:     my ($rndseed)=@_;
1.503     albertel 5273:     if ($rndseed =~/([,:])/) {
                   5274: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 5275: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   5276:     } else {
                   5277: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 5278:     }
1.36      albertel 5279: }
                   5280: 
1.474     albertel 5281: sub latest_receipt_algorithm_id {
                   5282:     return 'receipt2';
                   5283: }
                   5284: 
1.480     www      5285: sub recunique {
                   5286:     my $fucourseid=shift;
                   5287:     my $unique;
1.620     albertel 5288:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5289: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      5290:     } else {
                   5291: 	$unique=$perlvar{'lonReceipt'};
                   5292:     }
                   5293:     return unpack("%32C*",$unique);
                   5294: }
                   5295: 
                   5296: sub recprefix {
                   5297:     my $fucourseid=shift;
                   5298:     my $prefix;
1.620     albertel 5299:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5300: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      5301:     } else {
                   5302: 	$prefix=$perlvar{'lonHostID'};
                   5303:     }
                   5304:     return unpack("%32C*",$prefix);
                   5305: }
                   5306: 
1.76      www      5307: sub ireceipt {
1.474     albertel 5308:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      5309:     my $cuname=unpack("%32C*",$funame);
                   5310:     my $cudom=unpack("%32C*",$fudom);
                   5311:     my $cucourseid=unpack("%32C*",$fucourseid);
                   5312:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      5313:     my $cunique=&recunique($fucourseid);
1.474     albertel 5314:     my $cpart=unpack("%32S*",$part);
1.480     www      5315:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 5316:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   5317: 	$env{'request.state'} eq 'construct') {
1.474     albertel 5318: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   5319: 			       " and ".($cpart%$cudom));
                   5320: 			       
                   5321: 	$return.= ($cunique%$cuname+
                   5322: 		   $cunique%$cudom+
                   5323: 		   $cusymb%$cuname+
                   5324: 		   $cusymb%$cudom+
                   5325: 		   $cucourseid%$cuname+
                   5326: 		   $cucourseid%$cudom+
                   5327: 		   $cpart%$cuname+
                   5328: 		   $cpart%$cudom);
                   5329:     } else {
                   5330: 	$return.= ($cunique%$cuname+
                   5331: 		   $cunique%$cudom+
                   5332: 		   $cusymb%$cuname+
                   5333: 		   $cusymb%$cudom+
                   5334: 		   $cucourseid%$cuname+
                   5335: 		   $cucourseid%$cudom);
                   5336:     }
                   5337:     return $return;
1.76      www      5338: }
                   5339: 
                   5340: sub receipt {
1.474     albertel 5341:     my ($part)=@_;
                   5342:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   5343:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      5344: }
1.260     ng       5345: 
1.36      albertel 5346: # ------------------------------------------------------------ Serves up a file
1.472     albertel 5347: # returns either the contents of the file or 
                   5348: # -1 if the file doesn't exist
1.481     raeburn  5349: #
                   5350: # if the target is a file that was uploaded via DOCS, 
                   5351: # a check will be made to see if a current copy exists on the local server,
                   5352: # if it does this will be served, otherwise a copy will be retrieved from
                   5353: # the home server for the course and stored in /home/httpd/html/userfiles on
                   5354: # the local server.   
1.472     albertel 5355: 
1.36      albertel 5356: sub getfile {
1.538     albertel 5357:     my ($file) = @_;
1.609     banghart 5358:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 5359:     &repcopy($file);
                   5360:     return &readfile($file);
                   5361: }
                   5362: 
                   5363: sub repcopy_userfile {
                   5364:     my ($file)=@_;
1.609     banghart 5365:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 5366:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 5367:     my ($cdom,$cnum,$filename) = 
                   5368: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   5369:     my ($info,$rtncode);
                   5370:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   5371:     if (-e "$file") {
                   5372: 	my @fileinfo = stat($file);
                   5373: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5374: 	if ($lwpresp ne 'ok') {
                   5375: 	    if ($rtncode eq '404') {
1.538     albertel 5376: 		unlink($file);
1.482     albertel 5377: 	    }
1.517     albertel 5378: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 5379: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5380: 	    #my $response=$ua->request($request);
                   5381: 	    #if ($response->is_success()) {
                   5382: 	#	return $response->content;
                   5383: 	#    } else {
                   5384: 	#	return -1;
                   5385: 	#    }
1.482     albertel 5386: 	    return -1;
                   5387: 	}
                   5388: 	if ($info < $fileinfo[9]) {
1.607     raeburn  5389: 	    return 'ok';
1.482     albertel 5390: 	}
                   5391: 	$info = '';
1.538     albertel 5392: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5393: 	if ($lwpresp ne 'ok') {
                   5394: 	    return -1;
                   5395: 	}
                   5396:     } else {
1.538     albertel 5397: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5398: 	if ($lwpresp ne 'ok') {
1.517     albertel 5399: 	    my $ua=new LWP::UserAgent;
1.538     albertel 5400: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5401: 	    my $response=$ua->request($request);
                   5402: 	    if ($response->is_success()) {
1.538     albertel 5403: 		$info=$response->content;
1.517     albertel 5404: 	    } else {
                   5405: 		return -1;
                   5406: 	    }
1.482     albertel 5407: 	}
                   5408: 	my @parts = ($cdom,$cnum); 
                   5409: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   5410: 	    push @parts, split(/\//,$1);
1.518     albertel 5411: 	}
1.538     albertel 5412: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 5413: 	foreach my $part (@parts) {
                   5414: 	    $path .= '/'.$part;
                   5415: 	    if (!-e $path) {
                   5416: 		mkdir($path,0770);
                   5417: 	    }
                   5418: 	}
                   5419:     }
1.538     albertel 5420:     open(FILE,">$file");
1.482     albertel 5421:     print FILE $info;
                   5422:     close(FILE);
1.607     raeburn  5423:     return 'ok';
1.481     raeburn  5424: }
                   5425: 
1.517     albertel 5426: sub tokenwrapper {
                   5427:     my $uri=shift;
1.552     albertel 5428:     $uri=~s|^http\://([^/]+)||;
                   5429:     $uri=~s|^/||;
1.620     albertel 5430:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 5431:     my $token=$1;
1.552     albertel 5432:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   5433:     if ($udom && $uname && $file) {
                   5434: 	$file=~s|(\?\.*)*$||;
1.620     albertel 5435:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 5436:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 5437:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   5438:                                '&tokenissued='.$perlvar{'lonHostID'};
                   5439:     } else {
                   5440:         return '/adm/notfound.html';
                   5441:     }
                   5442: }
                   5443: 
1.481     raeburn  5444: sub getuploaded {
                   5445:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   5446:     $uri=~s/^\///;
                   5447:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   5448:     my $ua=new LWP::UserAgent;
                   5449:     my $request=new HTTP::Request($reqtype,$uri);
                   5450:     my $response=$ua->request($request);
                   5451:     $$rtncode = $response->code;
1.482     albertel 5452:     if (! $response->is_success()) {
                   5453: 	return 'failed';
                   5454:     }      
                   5455:     if ($reqtype eq 'HEAD') {
1.486     www      5456: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 5457:     } elsif ($reqtype eq 'GET') {
                   5458: 	$$info = $response->content;
1.472     albertel 5459:     }
1.482     albertel 5460:     return 'ok';
1.36      albertel 5461: }
                   5462: 
1.481     raeburn  5463: sub readfile {
                   5464:     my $file = shift;
                   5465:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   5466:     my $fh;
                   5467:     open($fh,"<$file");
                   5468:     my $a='';
                   5469:     while (<$fh>) { $a .=$_; }
                   5470:     return $a;
                   5471: }
                   5472: 
1.36      albertel 5473: sub filelocation {
1.590     banghart 5474:     my ($dir,$file) = @_;
                   5475:     my $location;
                   5476:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
                   5477:     if ($file=~m:^/~:) { # is a contruction space reference
                   5478:         $location = $file;
                   5479:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.609     banghart 5480:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 5481:         my ($udom,$uname,$filename)=
1.609     banghart 5482:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 5483:         my $home=&homeserver($uname,$udom);
                   5484:         my $is_me=0;
                   5485:         my @ids=&current_machine_ids();
                   5486:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   5487:         if ($is_me) {
                   5488:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   5489:   	      '/userfiles/'.$filename;
                   5490:         } else {
                   5491:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   5492:   	      $udom.'/'.$uname.'/'.$filename;
                   5493:         }
                   5494:     } else {
                   5495:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   5496:         $file=~s:^/res/:/:;
                   5497:         if ( !( $file =~ m:^/:) ) {
                   5498:             $location = $dir. '/'.$file;
                   5499:         } else {
                   5500:             $location = '/home/httpd/html/res'.$file;
                   5501:         }
1.59      albertel 5502:     }
1.590     banghart 5503:     $location=~s://+:/:g; # remove duplicate /
                   5504:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   5505:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   5506:     return $location;
1.46      www      5507: }
1.36      albertel 5508: 
1.46      www      5509: sub hreflocation {
                   5510:     my ($dir,$file)=@_;
1.460     albertel 5511:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
                   5512: 	my $finalpath=filelocation($dir,$file);
                   5513: 	$finalpath=~s-^/home/httpd/html--;
1.462     albertel 5514: 	$finalpath=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460     albertel 5515: 	return $finalpath;
                   5516:     } elsif ($file=~m-^/home-) {
                   5517: 	$file=~s-^/home/httpd/html--;
1.462     albertel 5518: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460     albertel 5519: 	return $file;
1.46      www      5520:     }
1.462     albertel 5521:     return $file;
1.465     albertel 5522: }
                   5523: 
                   5524: sub current_machine_domains {
                   5525:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   5526:     my @domains;
                   5527:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  5528: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 5529: 	if ($hostname eq $name) {
                   5530: 	    push(@domains,$hostdom{$id});
                   5531: 	}
                   5532:     }
                   5533:     return @domains;
                   5534: }
                   5535: 
                   5536: sub current_machine_ids {
                   5537:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   5538:     my @ids;
                   5539:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  5540: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 5541: 	if ($hostname eq $name) {
                   5542: 	    push(@ids,$id);
                   5543: 	}
                   5544:     }
                   5545:     return @ids;
1.31      www      5546: }
                   5547: 
                   5548: # ------------------------------------------------------------- Declutters URLs
                   5549: 
                   5550: sub declutter {
                   5551:     my $thisfn=shift;
1.569     albertel 5552:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 5553:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      5554:     $thisfn=~s/^\///;
                   5555:     $thisfn=~s/^res\///;
1.235     www      5556:     $thisfn=~s/\?.+$//;
1.268     www      5557:     return $thisfn;
                   5558: }
                   5559: 
                   5560: # ------------------------------------------------------------- Clutter up URLs
                   5561: 
                   5562: sub clutter {
                   5563:     my $thisfn='/'.&declutter(shift);
1.609     banghart 5564:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      5565:        $thisfn='/res'.$thisfn; 
                   5566:     }
1.31      www      5567:     return $thisfn;
1.12      www      5568: }
                   5569: 
1.557     albertel 5570: sub freeze_escape {
                   5571:     my ($value)=@_;
                   5572:     if (ref($value)) {
                   5573: 	$value=&nfreeze($value);
                   5574: 	return '__FROZEN__'.&escape($value);
                   5575:     }
                   5576:     return &escape($value);
                   5577: }
                   5578: 
1.12      www      5579: # -------------------------------------------------------- Escape Special Chars
                   5580: 
                   5581: sub escape {
                   5582:     my $str=shift;
                   5583:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   5584:     return $str;
                   5585: }
                   5586: 
                   5587: # ----------------------------------------------------- Un-Escape Special Chars
                   5588: 
                   5589: sub unescape {
                   5590:     my $str=shift;
                   5591:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   5592:     return $str;
                   5593: }
1.11      www      5594: 
1.557     albertel 5595: sub thaw_unescape {
                   5596:     my ($value)=@_;
                   5597:     if ($value =~ /^__FROZEN__/) {
                   5598: 	substr($value,0,10,undef);
                   5599: 	$value=&unescape($value);
                   5600: 	return &thaw($value);
                   5601:     }
                   5602:     return &unescape($value);
                   5603: }
                   5604: 
1.415     albertel 5605: sub mod_perl_version {
1.580     albertel 5606:     return 1;
1.415     albertel 5607:     if (defined($perlvar{'MODPERL2'})) {
                   5608: 	return 2;
                   5609:     }
1.436     albertel 5610: }
                   5611: 
                   5612: sub correct_line_ends {
                   5613:     my ($result)=@_;
                   5614:     $$result =~s/\r\n/\n/mg;
                   5615:     $$result =~s/\r/\n/mg;
1.415     albertel 5616: }
1.1       albertel 5617: # ================================================================ Main Program
                   5618: 
1.184     www      5619: sub goodbye {
1.204     albertel 5620:    &logthis("Starting Shut down");
1.443     albertel 5621: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 5622:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 5623: #converted
1.599     albertel 5624: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   5625:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   5626: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   5627: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 5628: #1.1 only
1.599     albertel 5629: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   5630: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   5631: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   5632: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   5633:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   5634:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   5635:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      5636:    &flushcourselogs();
                   5637:    &logthis("Shutting down");
1.362     albertel 5638:    return DONE;
1.184     www      5639: }
                   5640: 
1.179     www      5641: BEGIN {
1.228     harris41 5642: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      5643:     unless ($readit) {
1.217     harris41 5644: {
1.581     matthew  5645:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 5646:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 5647: 
                   5648:     while (my $configline=<$config>) {
1.484     albertel 5649:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 5650: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      5651:            chomp($varvalue);
1.1       albertel 5652:            $perlvar{$varname}=$varvalue;
                   5653:         }
                   5654:     }
1.448     albertel 5655:     close($config);
1.1       albertel 5656: }
1.227     harris41 5657: {
1.448     albertel 5658:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 5659: 
                   5660:     while (my $configline=<$config>) {
                   5661:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   5662: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   5663:            chomp($varvalue);
                   5664:            $perlvar{$varname}=$varvalue;
                   5665:         }
                   5666:     }
1.448     albertel 5667:     close($config);
1.227     harris41 5668: }
1.1       albertel 5669: 
1.327     albertel 5670: # ------------------------------------------------------------ Read domain file
                   5671: {
                   5672:     %domaindescription = ();
                   5673:     %domain_auth_def = ();
                   5674:     %domain_auth_arg_def = ();
1.448     albertel 5675:     my $fh;
                   5676:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 5677:        while (<$fh>) {
1.390     matthew  5678:            next if (/^(\#|\s*$)/);
                   5679: #           next if /^\#/;
1.327     albertel 5680:            chomp;
1.403     www      5681:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
                   5682: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
                   5683: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 5684:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      5685: 	   $domaindescription{$domain}=$domain_description;
                   5686: 	   $domain_lang_def{$domain}=$def_lang;
                   5687: 	   $domain_city{$domain}=$city;
                   5688: 	   $domain_longi{$domain}=$longi;
                   5689: 	   $domain_lati{$domain}=$lati;
                   5690: 
1.448     albertel 5691:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 5692: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 5693: 	}
1.327     albertel 5694:     }
1.448     albertel 5695:     close ($fh);
1.327     albertel 5696: }
                   5697: 
                   5698: 
1.1       albertel 5699: # ------------------------------------------------------------- Read hosts file
                   5700: {
1.448     albertel 5701:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 5702: 
                   5703:     while (my $configline=<$config>) {
1.303     matthew  5704:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      5705:        chomp($configline);
1.595     albertel 5706:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 5707:        $name=~s/\s//g;
1.595     albertel 5708:        if ($id && $domain && $role && $name) {
1.252     albertel 5709: 	 $hostname{$id}=$name;
                   5710: 	 $hostdom{$id}=$domain;
                   5711: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      5712:        }
1.1       albertel 5713:     }
1.448     albertel 5714:     close($config);
1.619     albertel 5715:     # FIXME: dev server don't want this, production servers _do_ want this
                   5716:     #&get_iphost();
1.1       albertel 5717: }
                   5718: 
1.598     albertel 5719: sub get_iphost {
                   5720:     if (%iphost) { return %iphost; }
                   5721:     foreach my $id (keys(%hostname)) {
                   5722: 	my $name=$hostname{$id};
                   5723: 	my $ip = gethostbyname($name);
                   5724: 	if (!$ip || length($ip) ne 4) {
                   5725: 	    &logthis("Skipping host $id name $name no IP found\n");
                   5726: 	    next;
                   5727: 	}
                   5728: 	$ip=inet_ntoa($ip);
                   5729: 	push(@{$iphost{$ip}},$id);
                   5730:     }
                   5731:     return %iphost;
                   5732: }
                   5733: 
1.1       albertel 5734: # ------------------------------------------------------ Read spare server file
                   5735: {
1.448     albertel 5736:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 5737: 
                   5738:     while (my $configline=<$config>) {
                   5739:        chomp($configline);
1.284     matthew  5740:        if ($configline) {
1.1       albertel 5741:           $spareid{$configline}=1;
                   5742:        }
                   5743:     }
1.448     albertel 5744:     close($config);
1.1       albertel 5745: }
1.11      www      5746: # ------------------------------------------------------------ Read permissions
                   5747: {
1.448     albertel 5748:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      5749: 
                   5750:     while (my $configline=<$config>) {
1.448     albertel 5751: 	chomp($configline);
                   5752: 	if ($configline) {
                   5753: 	    my ($role,$perm)=split(/ /,$configline);
                   5754: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   5755: 	}
1.11      www      5756:     }
1.448     albertel 5757:     close($config);
1.11      www      5758: }
                   5759: 
                   5760: # -------------------------------------------- Read plain texts for permissions
                   5761: {
1.448     albertel 5762:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      5763: 
                   5764:     while (my $configline=<$config>) {
1.448     albertel 5765: 	chomp($configline);
                   5766: 	if ($configline) {
                   5767: 	    my ($short,$plain)=split(/:/,$configline);
                   5768: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   5769: 	}
1.135     www      5770:     }
1.448     albertel 5771:     close($config);
1.135     www      5772: }
                   5773: 
                   5774: # ---------------------------------------------------------- Read package table
                   5775: {
1.448     albertel 5776:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      5777: 
                   5778:     while (my $configline=<$config>) {
1.483     albertel 5779: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 5780: 	chomp($configline);
                   5781: 	my ($short,$plain)=split(/:/,$configline);
                   5782: 	my ($pack,$name)=split(/\&/,$short);
                   5783: 	if ($plain ne '') {
                   5784: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   5785: 	    $packagetab{$short}=$plain; 
                   5786: 	}
1.11      www      5787:     }
1.448     albertel 5788:     close($config);
1.329     matthew  5789: }
                   5790: 
                   5791: # ------------- set up temporary directory
                   5792: {
                   5793:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   5794: 
1.11      www      5795: }
                   5796: 
1.599     albertel 5797: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      5798: 
1.281     www      5799: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      5800: $dumpcount=0;
1.22      www      5801: 
1.163     harris41 5802: &logtouch();
1.12      www      5803: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      5804: $readit=1;
1.564     albertel 5805:     {
                   5806: 	use integer;
                   5807: 	my $test=(2**32)+1;
1.568     albertel 5808: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 5809: 	&logthis(" Detected 64bit platform ($_64bit)");
                   5810:     }
1.195     www      5811: }
1.1       albertel 5812: }
1.179     www      5813: 
1.1       albertel 5814: 1;
1.191     harris41 5815: __END__
                   5816: 
1.243     albertel 5817: =pod
                   5818: 
1.191     harris41 5819: =head1 NAME
                   5820: 
1.243     albertel 5821: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 5822: 
                   5823: =head1 SYNOPSIS
                   5824: 
1.243     albertel 5825: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 5826: 
                   5827:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   5828: 
1.243     albertel 5829: Common parameters:
                   5830: 
                   5831: =over 4
                   5832: 
                   5833: =item *
                   5834: 
                   5835: $uname : an internal username (if $cname expecting a course Id specifically)
                   5836: 
                   5837: =item *
                   5838: 
                   5839: $udom : a domain (if $cdom expecting a course's domain specifically)
                   5840: 
                   5841: =item *
                   5842: 
                   5843: $symb : a resource instance identifier
                   5844: 
                   5845: =item *
                   5846: 
                   5847: $namespace : the name of a .db file that contains the data needed or
                   5848: being set.
                   5849: 
                   5850: =back
                   5851: 
1.394     bowersj2 5852: =head1 OVERVIEW
1.191     harris41 5853: 
1.394     bowersj2 5854: lonnet provides subroutines which interact with the
                   5855: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   5856: about classes, users, and resources.
1.243     albertel 5857: 
                   5858: For many of these objects you can also use this to store data about
                   5859: them or modify them in various ways.
1.191     harris41 5860: 
1.394     bowersj2 5861: =head2 Symbs
1.191     harris41 5862: 
1.394     bowersj2 5863: To identify a specific instance of a resource, LON-CAPA uses symbols
                   5864: or "symbs"X<symb>. These identifiers are built from the URL of the
                   5865: map, the resource number of the resource in the map, and the URL of
                   5866: the resource itself. The latter is somewhat redundant, but might help
                   5867: if maps change.
                   5868: 
                   5869: An example is
                   5870: 
                   5871:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   5872: 
                   5873: The respective map entry is
                   5874: 
                   5875:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   5876:   title="Problem 2">
                   5877:  </resource>
                   5878: 
                   5879: Symbs are used by the random number generator, as well as to store and
                   5880: restore data specific to a certain instance of for example a problem.
                   5881: 
                   5882: =head2 Storing And Retrieving Data
                   5883: 
                   5884: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   5885: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   5886: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   5887: is is the non-critical message twin of cstore. These functions are for
                   5888: handlers to store a perl hash to a user's permanent data space in an
                   5889: easy manner, and to retrieve it again on another call. It is expected
                   5890: that a handler would use this once at the beginning to retrieve data,
                   5891: and then again once at the end to send only the new data back.
                   5892: 
                   5893: The data is stored in the user's data directory on the user's
                   5894: homeserver under the ID of the course.
                   5895: 
                   5896: The hash that is returned by restore will have all of the previous
                   5897: value for all of the elements of the hash.
                   5898: 
                   5899: Example:
                   5900: 
                   5901:  #creating a hash
                   5902:  my %hash;
                   5903:  $hash{'foo'}='bar';
                   5904: 
                   5905:  #storing it
                   5906:  &Apache::lonnet::cstore(\%hash);
                   5907: 
                   5908:  #changing a value
                   5909:  $hash{'foo'}='notbar';
                   5910: 
                   5911:  #adding a new value
                   5912:  $hash{'bar'}='foo';
                   5913:  &Apache::lonnet::cstore(\%hash);
                   5914: 
                   5915:  #retrieving the hash
                   5916:  my %history=&Apache::lonnet::restore();
                   5917: 
                   5918:  #print the hash
                   5919:  foreach my $key (sort(keys(%history))) {
                   5920:    print("\%history{$key} = $history{$key}");
                   5921:  }
                   5922: 
                   5923: Will print out:
1.191     harris41 5924: 
1.394     bowersj2 5925:  %history{1:foo} = bar
                   5926:  %history{1:keys} = foo:timestamp
                   5927:  %history{1:timestamp} = 990455579
                   5928:  %history{2:bar} = foo
                   5929:  %history{2:foo} = notbar
                   5930:  %history{2:keys} = foo:bar:timestamp
                   5931:  %history{2:timestamp} = 990455580
                   5932:  %history{bar} = foo
                   5933:  %history{foo} = notbar
                   5934:  %history{timestamp} = 990455580
                   5935:  %history{version} = 2
                   5936: 
                   5937: Note that the special hash entries C<keys>, C<version> and
                   5938: C<timestamp> were added to the hash. C<version> will be equal to the
                   5939: total number of versions of the data that have been stored. The
                   5940: C<timestamp> attribute will be the UNIX time the hash was
                   5941: stored. C<keys> is available in every historical section to list which
                   5942: keys were added or changed at a specific historical revision of a
                   5943: hash.
                   5944: 
                   5945: B<Warning>: do not store the hash that restore returns directly. This
                   5946: will cause a mess since it will restore the historical keys as if the
                   5947: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 5948: 
1.394     bowersj2 5949: Calling convention:
1.191     harris41 5950: 
1.394     bowersj2 5951:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   5952:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 5953: 
1.394     bowersj2 5954: For more detailed information, see lonnet specific documentation.
1.191     harris41 5955: 
1.394     bowersj2 5956: =head1 RETURN MESSAGES
1.191     harris41 5957: 
1.394     bowersj2 5958: =over 4
1.191     harris41 5959: 
1.394     bowersj2 5960: =item * B<con_lost>: unable to contact remote host
1.191     harris41 5961: 
1.394     bowersj2 5962: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   5963: when the connection is brought back up
1.191     harris41 5964: 
1.394     bowersj2 5965: =item * B<con_failed>: unable to contact remote host and unable to save message
                   5966: for later delivery
1.191     harris41 5967: 
1.394     bowersj2 5968: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 5969: 
1.394     bowersj2 5970: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 5971: that was requested
1.191     harris41 5972: 
1.243     albertel 5973: =back
1.191     harris41 5974: 
1.243     albertel 5975: =head1 PUBLIC SUBROUTINES
1.191     harris41 5976: 
1.243     albertel 5977: =head2 Session Environment Functions
1.191     harris41 5978: 
1.243     albertel 5979: =over 4
1.191     harris41 5980: 
1.394     bowersj2 5981: =item * 
                   5982: X<appenv()>
                   5983: B<appenv(%hash)>: the value of %hash is written to
                   5984: the user envirnoment file, and will be restored for each access this
1.620     albertel 5985: user makes during this session, also modifies the %env for the current
1.394     bowersj2 5986: process
1.191     harris41 5987: 
                   5988: =item *
1.394     bowersj2 5989: X<delenv()>
                   5990: B<delenv($regexp)>: removes all items from the session
                   5991: environment file that matches the regular expression in $regexp. The
1.620     albertel 5992: values are also delted from the current processes %env.
1.191     harris41 5993: 
1.243     albertel 5994: =back
                   5995: 
                   5996: =head2 User Information
1.191     harris41 5997: 
1.243     albertel 5998: =over 4
1.191     harris41 5999: 
                   6000: =item *
1.394     bowersj2 6001: X<queryauthenticate()>
                   6002: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 6003: authentication scheme
                   6004: 
                   6005: =item *
1.394     bowersj2 6006: X<authenticate()>
                   6007: B<authenticate($uname,$upass,$udom)>: try to
                   6008: authenticate user from domain's lib servers (first use the current
                   6009: one). C<$upass> should be the users password.
1.191     harris41 6010: 
                   6011: =item *
1.394     bowersj2 6012: X<homeserver()>
                   6013: B<homeserver($uname,$udom)>: find the server which has
                   6014: the user's directory and files (there must be only one), this caches
                   6015: the answer, and also caches if there is a borken connection.
1.191     harris41 6016: 
                   6017: =item *
1.394     bowersj2 6018: X<idget()>
                   6019: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   6020: (IDs are a unique resource in a domain, there must be only 1 ID per
                   6021: username, and only 1 username per ID in a specific domain) (returns
                   6022: hash: id=>name,id=>name)
1.191     harris41 6023: 
                   6024: =item *
1.394     bowersj2 6025: X<idrget()>
                   6026: B<idrget($udom,@unames)>: find the IDs behind a list of
                   6027: usernames (returns hash: name=>id,name=>id)
1.191     harris41 6028: 
                   6029: =item *
1.394     bowersj2 6030: X<idput()>
                   6031: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 6032: 
                   6033: =item *
1.394     bowersj2 6034: X<rolesinit()>
                   6035: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 6036: 
                   6037: =item *
1.551     albertel 6038: X<getsection()>
                   6039: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 6040: course $cname, return section name/number or '' for "not in course"
                   6041: and '-1' for "no section"
                   6042: 
                   6043: =item *
1.394     bowersj2 6044: X<userenvironment()>
                   6045: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 6046: passed in @what from the requested user's environment, returns a hash
                   6047: 
                   6048: =back
                   6049: 
                   6050: =head2 User Roles
                   6051: 
                   6052: =over 4
                   6053: 
                   6054: =item *
                   6055: 
                   6056: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   6057: actions
                   6058:  F: full access
                   6059:  U,I,K: authentication modes (cxx only)
                   6060:  '': forbidden
                   6061:  1: user needs to choose course
                   6062:  2: browse allowed
                   6063: 
                   6064: =item *
                   6065: 
                   6066: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   6067: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   6068: and course level
                   6069: 
                   6070: =item *
                   6071: 
                   6072: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   6073: explanation of a user role term
                   6074: 
                   6075: =back
                   6076: 
                   6077: =head2 User Modification
                   6078: 
                   6079: =over 4
                   6080: 
                   6081: =item *
                   6082: 
                   6083: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   6084: user for the level given by URL.  Optional start and end dates (leave empty
                   6085: string or zero for "no date")
1.191     harris41 6086: 
                   6087: =item *
                   6088: 
1.243     albertel 6089: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   6090: change a users, password, possible return values are: ok,
                   6091: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   6092: refused
1.191     harris41 6093: 
                   6094: =item *
                   6095: 
1.243     albertel 6096: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 6097: 
                   6098: =item *
                   6099: 
1.243     albertel 6100: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   6101: modify user
1.191     harris41 6102: 
                   6103: =item *
                   6104: 
1.286     matthew  6105: modifystudent
                   6106: 
                   6107: modify a students enrollment and identification information.
                   6108: The course id is resolved based on the current users environment.  
                   6109: This means the envoking user must be a course coordinator or otherwise
                   6110: associated with a course.
                   6111: 
1.297     matthew  6112: This call is essentially a wrapper for lonnet::modifyuser and
                   6113: lonnet::modify_student_enrollment
1.286     matthew  6114: 
                   6115: Inputs: 
                   6116: 
                   6117: =over 4
                   6118: 
                   6119: =item B<$udom> Students loncapa domain
                   6120: 
                   6121: =item B<$uname> Students loncapa login name
                   6122: 
                   6123: =item B<$uid> Students id/student number
                   6124: 
                   6125: =item B<$umode> Students authentication mode
                   6126: 
                   6127: =item B<$upass> Students password
                   6128: 
                   6129: =item B<$first> Students first name
                   6130: 
                   6131: =item B<$middle> Students middle name
                   6132: 
                   6133: =item B<$last> Students last name
                   6134: 
                   6135: =item B<$gene> Students generation
                   6136: 
                   6137: =item B<$usec> Students section in course
                   6138: 
                   6139: =item B<$end> Unix time of the roles expiration
                   6140: 
                   6141: =item B<$start> Unix time of the roles start date
                   6142: 
                   6143: =item B<$forceid> If defined, allow $uid to be changed
                   6144: 
                   6145: =item B<$desiredhome> server to use as home server for student
                   6146: 
                   6147: =back
1.297     matthew  6148: 
                   6149: =item *
                   6150: 
                   6151: modify_student_enrollment
                   6152: 
                   6153: Change a students enrollment status in a class.  The environment variable
                   6154: 'role.request.course' must be defined for this function to proceed.
                   6155: 
                   6156: Inputs:
                   6157: 
                   6158: =over 4
                   6159: 
                   6160: =item $udom, students domain
                   6161: 
                   6162: =item $uname, students name
                   6163: 
                   6164: =item $uid, students user id
                   6165: 
                   6166: =item $first, students first name
                   6167: 
                   6168: =item $middle
                   6169: 
                   6170: =item $last
                   6171: 
                   6172: =item $gene
                   6173: 
                   6174: =item $usec
                   6175: 
                   6176: =item $end
                   6177: 
                   6178: =item $start
                   6179: 
                   6180: =back
                   6181: 
1.191     harris41 6182: 
                   6183: =item *
                   6184: 
1.243     albertel 6185: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   6186: custom role; give a custom role to a user for the level given by URL.  Specify
                   6187: name and domain of role author, and role name
1.191     harris41 6188: 
                   6189: =item *
                   6190: 
1.243     albertel 6191: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 6192: 
                   6193: =item *
                   6194: 
1.243     albertel 6195: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   6196: 
                   6197: =back
                   6198: 
                   6199: =head2 Course Infomation
                   6200: 
                   6201: =over 4
1.191     harris41 6202: 
                   6203: =item *
                   6204: 
1.631     albertel 6205: coursedescription($courseid) : returns a hash of information about the
                   6206: specified course id, including all environment settings for the
                   6207: course, the description of the course will be in the hash under the
                   6208: key 'description'
1.191     harris41 6209: 
                   6210: =item *
                   6211: 
1.624     albertel 6212: resdata($name,$domain,$type,@which) : request for current parameter
                   6213: setting for a specific $type, where $type is either 'course' or 'user',
                   6214: @what should be a list of parameters to ask about. This routine caches
                   6215: answers for 5 minutes.
1.243     albertel 6216: 
                   6217: =back
                   6218: 
                   6219: =head2 Course Modification
                   6220: 
                   6221: =over 4
1.191     harris41 6222: 
                   6223: =item *
                   6224: 
1.243     albertel 6225: writecoursepref($courseid,%prefs) : write preferences (environment
                   6226: database) for a course
1.191     harris41 6227: 
                   6228: =item *
                   6229: 
1.243     albertel 6230: createcourse($udom,$description,$url) : make/modify course
                   6231: 
                   6232: =back
                   6233: 
                   6234: =head2 Resource Subroutines
                   6235: 
                   6236: =over 4
1.191     harris41 6237: 
                   6238: =item *
                   6239: 
1.243     albertel 6240: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 6241: 
                   6242: =item *
                   6243: 
1.243     albertel 6244: repcopy($filename) : subscribes to the requested file, and attempts to
                   6245: replicate from the owning library server, Might return
1.607     raeburn  6246: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   6247: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 6248: resource. Expects the local filesystem pathname
                   6249: (/home/httpd/html/res/....)
                   6250: 
                   6251: =back
                   6252: 
                   6253: =head2 Resource Information
                   6254: 
                   6255: =over 4
1.191     harris41 6256: 
                   6257: =item *
                   6258: 
1.243     albertel 6259: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   6260: a vairety of different possible values, $varname should be a request
                   6261: string, and the other parameters can be used to specify who and what
                   6262: one is asking about.
                   6263: 
                   6264: Possible values for $varname are environment.lastname (or other item
                   6265: from the envirnment hash), user.name (or someother aspect about the
                   6266: user), resource.0.maxtries (or some other part and parameter of a
                   6267: resource)
1.204     albertel 6268: 
                   6269: =item *
                   6270: 
1.243     albertel 6271: directcondval($number) : get current value of a condition; reads from a state
                   6272: string
1.204     albertel 6273: 
                   6274: =item *
                   6275: 
1.243     albertel 6276: condval($condidx) : value of condition index based on state
1.204     albertel 6277: 
                   6278: =item *
                   6279: 
1.243     albertel 6280: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   6281: resource's metadata, $what should be either a specific key, or either
                   6282: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   6283: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   6284: 
                   6285: this function automatically caches all requests
1.191     harris41 6286: 
                   6287: =item *
                   6288: 
1.243     albertel 6289: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   6290: network of library servers; returns file handle of where SQL and regex results
                   6291: will be stored for query
1.191     harris41 6292: 
                   6293: =item *
                   6294: 
1.243     albertel 6295: symbread($filename) : return symbolic list entry (filename argument optional);
                   6296: returns the data handle
1.191     harris41 6297: 
                   6298: =item *
                   6299: 
1.243     albertel 6300: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 6301: a possible symb for the URL in $thisfn, and if is an encryypted
                   6302: resource that the user accessed using /enc/ returns a 1 on success, 0
                   6303: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 6304: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 6305: 
1.191     harris41 6306: 
                   6307: =item *
                   6308: 
1.243     albertel 6309: symbclean($symb) : removes versions numbers from a symb, returns the
                   6310: cleaned symb
1.191     harris41 6311: 
                   6312: =item *
                   6313: 
1.243     albertel 6314: is_on_map($uri) : checks if the $uri is somewhere on the current
                   6315: course map, user must be in a course for it to work.
1.191     harris41 6316: 
                   6317: =item *
                   6318: 
1.243     albertel 6319: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 6320: 
                   6321: =item *
                   6322: 
1.243     albertel 6323: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   6324: a random seed, all arguments are optional, if they aren't sent it uses the
                   6325: environment to derive them. Note: if symb isn't sent and it can't get one
                   6326: from &symbread it will use the current time as its return value
1.191     harris41 6327: 
                   6328: =item *
                   6329: 
1.243     albertel 6330: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   6331: unfakeable, receipt
1.191     harris41 6332: 
                   6333: =item *
                   6334: 
1.620     albertel 6335: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 6336: 
                   6337: =item *
                   6338: 
1.243     albertel 6339: countacc($url) : count the number of accesses to a given URL
1.191     harris41 6340: 
                   6341: =item *
                   6342: 
1.243     albertel 6343: 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 6344: 
                   6345: =item *
                   6346: 
1.243     albertel 6347: 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 6348: 
                   6349: =item *
                   6350: 
1.243     albertel 6351: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 6352: 
                   6353: =item *
                   6354: 
1.243     albertel 6355: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   6356: forcing spreadsheet to reevaluate the resource scores next time.
                   6357: 
                   6358: =back
                   6359: 
                   6360: =head2 Storing/Retreiving Data
                   6361: 
                   6362: =over 4
1.191     harris41 6363: 
                   6364: =item *
                   6365: 
1.243     albertel 6366: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   6367: for this url; hashref needs to be given and should be a \%hashname; the
                   6368: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 6369: be derived from the env
1.191     harris41 6370: 
                   6371: =item *
                   6372: 
1.243     albertel 6373: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   6374: uses critical subroutine
1.191     harris41 6375: 
                   6376: =item *
                   6377: 
1.243     albertel 6378: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   6379: all args are optional
1.191     harris41 6380: 
                   6381: =item *
                   6382: 
1.243     albertel 6383: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   6384: works very similar to store/cstore, but all data is stored in a
                   6385: temporary location and can be reset using tmpreset, $storehash should
                   6386: be a hash reference, returns nothing on success
1.191     harris41 6387: 
                   6388: =item *
                   6389: 
1.243     albertel 6390: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   6391: similar to restore, but all data is stored in a temporary location and
                   6392: can be reset using tmpreset. Returns a hash of values on success,
                   6393: error string otherwise.
1.191     harris41 6394: 
                   6395: =item *
                   6396: 
1.243     albertel 6397: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   6398: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 6399: 
                   6400: =item *
                   6401: 
1.243     albertel 6402: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6403: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 6404: 
                   6405: =item *
                   6406: 
1.243     albertel 6407: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   6408: namesp ($udom and $uname are optional)
1.191     harris41 6409: 
                   6410: =item *
                   6411: 
1.243     albertel 6412: dump($namespace,$udom,$uname,$regexp) : 
                   6413: dumps the complete (or key matching regexp) namespace into a hash
                   6414: ($udom, $uname and $regexp are optional)
1.449     matthew  6415: 
                   6416: =item *
                   6417: 
                   6418: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   6419: $store can be a scalar, an array reference, or if the amount to be 
                   6420: incremented is > 1, a hash reference.
                   6421: 
                   6422: ($udom and $uname are optional)
1.191     harris41 6423: 
                   6424: =item *
                   6425: 
1.243     albertel 6426: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   6427: ($udom and $uname are optional)
1.191     harris41 6428: 
                   6429: =item *
                   6430: 
1.524     raeburn  6431: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
                   6432: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
                   6433: used in records written by &store and retrieved by &restore.  This function 
                   6434: was created for use in editing discussion posts, without incrementing the
                   6435: version number included in the key for a particular post. The colon 
                   6436: separated list of attribute names (e.g., the value associated with the key 
                   6437: 1:keys:$symb) is also generated and passed in the ampersand separated 
                   6438: items sent to lonnet::reply().  
                   6439: 
                   6440: =item *
                   6441: 
1.243     albertel 6442: cput($namespace,$storehash,$udom,$uname) : critical put
                   6443: ($udom and $uname are optional)
1.191     harris41 6444: 
                   6445: =item *
                   6446: 
1.243     albertel 6447: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6448: reference filled in from namesp (encrypts the return communication)
                   6449: ($udom and $uname are optional)
1.191     harris41 6450: 
                   6451: =item *
                   6452: 
1.243     albertel 6453: log($udom,$name,$home,$message) : write to permanent log for user; use
                   6454: critical subroutine
                   6455: 
                   6456: =back
                   6457: 
                   6458: =head2 Network Status Functions
                   6459: 
                   6460: =over 4
1.191     harris41 6461: 
                   6462: =item *
                   6463: 
                   6464: dirlist($uri) : return directory list based on URI
                   6465: 
                   6466: =item *
                   6467: 
1.243     albertel 6468: spareserver() : find server with least workload from spare.tab
                   6469: 
                   6470: =back
                   6471: 
                   6472: =head2 Apache Request
                   6473: 
                   6474: =over 4
1.191     harris41 6475: 
                   6476: =item *
                   6477: 
1.243     albertel 6478: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   6479: localhost, posts hash
                   6480: 
                   6481: =back
                   6482: 
                   6483: =head2 Data to String to Data
                   6484: 
                   6485: =over 4
1.191     harris41 6486: 
                   6487: =item *
                   6488: 
1.243     albertel 6489: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   6490: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 6491: 
                   6492: =item *
                   6493: 
1.243     albertel 6494: hashref2str($hashref) : convert a hashref into a string complete with
                   6495: escaping and '=' and '&' separators, supports elements that are
                   6496: arrayrefs and hashrefs
1.191     harris41 6497: 
                   6498: =item *
                   6499: 
1.243     albertel 6500: arrayref2str($arrayref) : convert an arrayref into a string complete
                   6501: with escaping and '&' separators, supports elements that are arrayrefs
                   6502: and hashrefs
1.191     harris41 6503: 
                   6504: =item *
                   6505: 
1.243     albertel 6506: str2hash($string) : convert string to hash using unescaping and
                   6507: splitting on '=' and '&', supports elements that are arrayrefs and
                   6508: hashrefs
1.191     harris41 6509: 
                   6510: =item *
                   6511: 
1.243     albertel 6512: str2array($string) : convert string to hash using unescaping and
                   6513: splitting on '&', supports elements that are arrayrefs and hashrefs
                   6514: 
                   6515: =back
                   6516: 
                   6517: =head2 Logging Routines
                   6518: 
                   6519: =over 4
                   6520: 
                   6521: These routines allow one to make log messages in the lonnet.log and
                   6522: lonnet.perm logfiles.
1.191     harris41 6523: 
                   6524: =item *
                   6525: 
1.243     albertel 6526: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 6527: 
                   6528: =item *
                   6529: 
1.243     albertel 6530: logthis() : append message to the normal lonnet.log file, it gets
                   6531: preiodically rolled over and deleted.
1.191     harris41 6532: 
                   6533: =item *
                   6534: 
1.243     albertel 6535: logperm() : append a permanent message to lonnet.perm.log, this log
                   6536: file never gets deleted by any automated portion of the system, only
                   6537: messages of critical importance should go in here.
                   6538: 
                   6539: =back
                   6540: 
                   6541: =head2 General File Helper Routines
                   6542: 
                   6543: =over 4
1.191     harris41 6544: 
                   6545: =item *
                   6546: 
1.481     raeburn  6547: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   6548: (a) files in /uploaded
                   6549:   (i) If a local copy of the file exists - 
                   6550:       compares modification date of local copy with last-modified date for 
                   6551:       definitive version stored on home server for course. If local copy is 
                   6552:       stale, requests a new version from the home server and stores it. 
                   6553:       If the original has been removed from the home server, then local copy 
                   6554:       is unlinked.
                   6555:   (ii) If local copy does not exist -
                   6556:       requests the file from the home server and stores it. 
                   6557:   
                   6558:   If $caller is 'uploadrep':  
                   6559:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   6560:     for request for files originally uploaded via DOCS. 
                   6561:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   6562:   
                   6563:   Otherwise:
                   6564:      This indicates a call from the content generation phase of the request.
                   6565:      -  returns the entire contents of the file or -1.
                   6566:      
                   6567: (b) files in /res
                   6568:    - returns the entire contents of a file or -1; 
                   6569:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 6570: 
                   6571: =item *
                   6572: 
1.243     albertel 6573: filelocation($dir,$file) : returns file system location of a file
                   6574: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   6575: directory that relative $file lookups are to looked in ($dir of /a/dir
                   6576: and a file of ../bob will become /a/bob)
1.191     harris41 6577: 
                   6578: =item *
                   6579: 
                   6580: hreflocation($dir,$file) : returns file system location or a URL; same as
                   6581: filelocation except for hrefs
                   6582: 
                   6583: =item *
                   6584: 
                   6585: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   6586: 
1.243     albertel 6587: =back
                   6588: 
1.608     albertel 6589: =head2 Usererfile file routines (/uploaded*)
                   6590: 
                   6591: =over 4
                   6592: 
                   6593: =item *
                   6594: 
                   6595: userfileupload(): main rotine for putting a file in a user or course's
                   6596:                   filespace, arguments are,
                   6597: 
1.620     albertel 6598:  formname - required - this is the name of the element in $env where the
1.608     albertel 6599:            filename, and the contents of the file to create/modifed exist
1.620     albertel 6600:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   6601:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 6602:  coursedoc - if true, store the file in the course of the active role
                   6603:              of the current user
                   6604:  subdir - required - subdirectory to put the file in under ../userfiles/
                   6605:          if undefined, it will be placed in "unknown"
                   6606: 
                   6607:  (This routine calls clean_filename() to remove any dangerous
                   6608:  characters from the filename, and then calls finuserfileupload() to
                   6609:  complete the transaction)
                   6610: 
                   6611:  returns either the url of the uploaded file (/uploaded/....) if successful
                   6612:  and /adm/notfound.html if unsuccessful
                   6613: 
                   6614: =item *
                   6615: 
                   6616: clean_filename(): routine for cleaing a filename up for storage in
                   6617:                  userfile space, argument is:
                   6618: 
                   6619:  filename - proposed filename
                   6620: 
                   6621: returns: the new clean filename
                   6622: 
                   6623: =item *
                   6624: 
                   6625: finishuserfileupload(): routine that creaes and sends the file to
                   6626: userspace, probably shouldn't be called directly
                   6627: 
                   6628:   docuname: username or courseid of destination for the file
                   6629:   docudom: domain of user/course of destination for the file
                   6630:   docuhome: loncapa id of the library server that is getting the file
                   6631:   formname: same as for userfileupload()
                   6632:   fname: filename (inculding subdirectories) for the file
                   6633: 
                   6634:  returns either the url of the uploaded file (/uploaded/....) if successful
                   6635:  and /adm/notfound.html if unsuccessful
                   6636: 
                   6637: =item *
                   6638: 
                   6639: renameuserfile(): renames an existing userfile to a new name
                   6640: 
                   6641:   Args:
                   6642:    docuname: username or courseid of destination for the file
                   6643:    docudom: domain of user/course of destination for the file
                   6644:    old: current file name (including any subdirs under userfiles)
                   6645:    new: desired file name (including any subdirs under userfiles)
                   6646: 
                   6647: =item *
                   6648: 
                   6649: mkdiruserfile(): creates a directory is a userfiles dir
                   6650: 
                   6651:   Args:
                   6652:    docuname: username or courseid of destination for the file
                   6653:    docudom: domain of user/course of destination for the file
                   6654:    dir: dir to create (including any subdirs under userfiles)
                   6655: 
                   6656: =item *
                   6657: 
                   6658: removeuserfile(): removes a file that exists in userfiles
                   6659: 
                   6660:   Args:
                   6661:    docuname: username or courseid of destination for the file
                   6662:    docudom: domain of user/course of destination for the file
                   6663:    fname: filname to delete (including any subdirs under userfiles)
                   6664: 
                   6665: =item *
                   6666: 
                   6667: removeuploadedurl(): convience function for removeuserfile()
                   6668: 
                   6669:   Args:
                   6670:    url:  a full /uploaded/... url to delete
                   6671: 
                   6672: =back
                   6673: 
1.243     albertel 6674: =head2 HTTP Helper Routines
                   6675: 
                   6676: =over 4
                   6677: 
1.191     harris41 6678: =item *
                   6679: 
                   6680: escape() : unpack non-word characters into CGI-compatible hex codes
                   6681: 
                   6682: =item *
                   6683: 
                   6684: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   6685: 
1.243     albertel 6686: =back
                   6687: 
                   6688: =head1 PRIVATE SUBROUTINES
                   6689: 
                   6690: =head2 Underlying communication routines (Shouldn't call)
                   6691: 
                   6692: =over 4
                   6693: 
                   6694: =item *
                   6695: 
                   6696: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   6697: 
                   6698: =item *
                   6699: 
                   6700: reply() : uses subreply to send a message to remote machine, logs all failures
                   6701: 
                   6702: =item *
                   6703: 
                   6704: critical() : passes a critical message to another server; if cannot
                   6705: get through then place message in connection buffer directory and
                   6706: returns con_delayed, if incapable of saving message, returns
                   6707: con_failed
                   6708: 
                   6709: =item *
                   6710: 
                   6711: reconlonc() : tries to reconnect lonc client processes.
                   6712: 
                   6713: =back
                   6714: 
                   6715: =head2 Resource Access Logging
                   6716: 
                   6717: =over 4
                   6718: 
                   6719: =item *
                   6720: 
                   6721: flushcourselogs() : flush (save) buffer logs and access logs
                   6722: 
                   6723: =item *
                   6724: 
                   6725: courselog($what) : save message for course in hash
                   6726: 
                   6727: =item *
                   6728: 
                   6729: courseacclog($what) : save message for course using &courselog().  Perform
                   6730: special processing for specific resource types (problems, exams, quizzes, etc).
                   6731: 
1.191     harris41 6732: =item *
                   6733: 
                   6734: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   6735: as a PerlChildExitHandler
1.243     albertel 6736: 
                   6737: =back
                   6738: 
                   6739: =head2 Other
                   6740: 
                   6741: =over 4
                   6742: 
                   6743: =item *
                   6744: 
                   6745: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 6746: 
                   6747: =back
                   6748: 
                   6749: =cut

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