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

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

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