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

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

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