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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.626   ! albertel    4: # $Id: lonnet.pm,v 1.625 2005/04/18 21:10:41 raeburn 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: 
1.625     raeburn  2642: # ------------------------------------------------------ critical inc interface
                   2643:                                                                                 
                   2644: sub cinc {
                   2645:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   2646:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2647:    if (!$uname) { $uname=$env{'user.name'}; }
                   2648:    my $uhome=&homeserver($uname,$udomain);
                   2649:    my $items='';
                   2650:    foreach (keys %$storehash) {
                   2651:        $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   2652:    }
                   2653:    $items=~s/\&$//;
                   2654:    return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   2655: }
                   2656: 
1.12      www      2657: # -------------------------------------------------------------- eget interface
                   2658: 
                   2659: sub eget {
1.133     albertel 2660:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2661:    my $items='';
1.191     harris41 2662:    foreach (@$storearr) {
1.12      www      2663:        $items.=escape($_).'&';
1.191     harris41 2664:    }
1.12      www      2665:    $items=~s/\&$//;
1.620     albertel 2666:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2667:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2668:    my $uhome=&homeserver($uname,$udomain);
                   2669:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      2670:    my @pairs=split(/\&/,$rep);
                   2671:    my %returnhash=();
1.42      www      2672:    my $i=0;
1.191     harris41 2673:    foreach (@$storearr) {
1.557     albertel 2674:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2675:       $i++;
1.191     harris41 2676:    }
1.12      www      2677:    return %returnhash;
                   2678: }
                   2679: 
1.341     www      2680: # ---------------------------------------------- Custom access rule evaluation
                   2681: 
                   2682: sub customaccess {
                   2683:     my ($priv,$uri)=@_;
1.620     albertel 2684:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      2685:     $urealm=~s/^\W//;
                   2686:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      2687:     my $access=0;
                   2688:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      2689: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      2690:         if ($role) {
                   2691: 	   if ($role ne $urole) { next; }
                   2692:         }
                   2693:         foreach (split(/\s*\,\s*/,$realm)) {
                   2694:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   2695:             if ($tdom) {
                   2696: 		if ($tdom ne $udom) { next; }
                   2697:             }
                   2698:             if ($tcrs) {
                   2699: 		if ($tcrs ne $ucrs) { next; }
                   2700:             }
                   2701:             if ($tsec) {
                   2702: 		if ($tsec ne $usec) { next; }
                   2703:             }
                   2704:             $access=($effect eq 'allow');
                   2705:             last;
1.342     www      2706:         }
1.402     bowersj2 2707: 	if ($realm eq '' && $role eq '') {
                   2708:             $access=($effect eq 'allow');
                   2709: 	}
1.341     www      2710:     }
                   2711:     return $access;
                   2712: }
                   2713: 
1.103     harris41 2714: # ------------------------------------------------- Check for a user privilege
1.12      www      2715: 
                   2716: sub allowed {
1.579     albertel 2717:     my ($priv,$uri,$symb)=@_;
1.439     www      2718:     $uri=&deversion($uri);
1.152     www      2719:     my $orguri=$uri;
1.52      www      2720:     $uri=&declutter($uri);
1.545     banghart 2721:     
                   2722:     
                   2723:     
1.620     albertel 2724:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      2725: # Free bre access to adm and meta resources
1.529     albertel 2726:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
                   2727: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
1.14      www      2728: 	return 'F';
1.159     www      2729:     }
                   2730: 
1.545     banghart 2731: # Free bre access to user's own portfolio contents
1.546     albertel 2732:     my ($space,$domain,$name,$dir)=split('/',$uri);
1.620     albertel 2733:     if (($space=~/^(uploaded|ediupload)$/) && ($env{'user.name'} eq $name) && 
                   2734: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
1.545     banghart 2735:         return 'F';
                   2736:     }
                   2737: 
1.159     www      2738: # Free bre to public access
                   2739: 
                   2740:     if ($priv eq 'bre') {
1.238     www      2741:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 2742: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      2743:            return 'F'; 
                   2744:         }
1.238     www      2745:         if ($copyright eq 'priv') {
                   2746:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 2747: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      2748: 		return '';
                   2749:             }
                   2750:         }
                   2751:         if ($copyright eq 'domain') {
                   2752:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 2753: 	    unless (($env{'user.domain'} eq $1) ||
                   2754:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      2755: 		return '';
                   2756:             }
1.262     matthew  2757:         }
1.620     albertel 2758:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  2759:             # Library role, so allow browsing of resources in this domain.
                   2760:             return 'F';
1.238     www      2761:         }
1.341     www      2762:         if ($copyright eq 'custom') {
                   2763: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   2764:         }
1.14      www      2765:     }
1.264     matthew  2766:     # Domain coordinator is trying to create a course
1.620     albertel 2767:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  2768:         # uri is the requested domain in this case.
                   2769:         # comparison to 'request.role.domain' shows if the user has selected
                   2770:         # a role of dc for the domain in question. 
1.620     albertel 2771:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  2772:     }
1.29      www      2773: 
1.52      www      2774:     my $thisallowed='';
                   2775:     my $statecond=0;
                   2776:     my $courseprivid='';
                   2777: 
                   2778: # Course
                   2779: 
1.620     albertel 2780:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      2781:        $thisallowed.=$1;
                   2782:     }
1.29      www      2783: 
1.52      www      2784: # Domain
                   2785: 
1.620     albertel 2786:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 2787:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      2788:        $thisallowed.=$1;
                   2789:     }
1.52      www      2790: 
                   2791: # Course: uri itself is a course
1.66      www      2792:     my $courseuri=$uri;
                   2793:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      2794:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      2795: 
1.620     albertel 2796:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 2797:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      2798:        $thisallowed.=$1;
                   2799:     }
1.29      www      2800: 
1.314     www      2801: # URI is an uploaded document for this course
1.611     albertel 2802: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 2803:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.620     albertel 2804: 	my $refuri=$env{'httpref.'.$orguri};
1.492     albertel 2805: 	if ($refuri) {
                   2806: 	    if ($refuri =~ m|^/adm/|) {
                   2807: 		$thisallowed='F';
                   2808: 	    }
                   2809: 	}
1.314     www      2810:     }
1.492     albertel 2811: 
1.52      www      2812: # Full access at system, domain or course-wide level? Exit.
1.29      www      2813: 
                   2814:     if ($thisallowed=~/F/) {
                   2815: 	return 'F';
                   2816:     }
                   2817: 
1.52      www      2818: # If this is generating or modifying users, exit with special codes
1.29      www      2819: 
1.479     albertel 2820:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:\Q$priv\E\:/) {
1.52      www      2821: 	return $thisallowed;
                   2822:     }
                   2823: #
1.103     harris41 2824: # Gathered so far: system, domain and course wide privileges
1.52      www      2825: #
                   2826: # Course: See if uri or referer is an individual resource that is part of 
                   2827: # the course
                   2828: 
1.620     albertel 2829:     if ($env{'request.course.id'}) {
1.232     www      2830: 
1.620     albertel 2831:        $courseprivid=$env{'request.course.id'};
                   2832:        if ($env{'request.course.sec'}) {
                   2833:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      2834:        }
                   2835:        $courseprivid=~s/\_/\//;
                   2836:        my $checkreferer=1;
1.232     www      2837:        my ($match,$cond)=&is_on_map($uri);
                   2838:        if ($match) {
                   2839:            $statecond=$cond;
1.620     albertel 2840:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 2841:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      2842:                $thisallowed.=$1;
                   2843:                $checkreferer=0;
                   2844:            }
1.29      www      2845:        }
1.83      www      2846:        
1.148     www      2847:        if ($checkreferer) {
1.620     albertel 2848: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      2849:             unless ($refuri) {
1.620     albertel 2850:                 foreach (keys %env) {
1.148     www      2851: 		    if ($_=~/^httpref\..*\*/) {
                   2852: 			my $pattern=$_;
1.156     www      2853:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      2854:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   2855:                         $pattern=~s/\//\\\//g;
1.152     www      2856:                         if ($orguri=~/$pattern/) {
1.620     albertel 2857: 			    $refuri=$env{$_};
1.148     www      2858:                         }
                   2859:                     }
1.191     harris41 2860:                 }
1.148     www      2861:             }
1.232     www      2862: 
1.148     www      2863:          if ($refuri) { 
1.152     www      2864: 	  $refuri=&declutter($refuri);
1.232     www      2865:           my ($match,$cond)=&is_on_map($refuri);
                   2866:             if ($match) {
                   2867:               my $refstatecond=$cond;
1.620     albertel 2868:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 2869:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      2870:                   $thisallowed.=$1;
1.53      www      2871:                   $uri=$refuri;
                   2872:                   $statecond=$refstatecond;
1.52      www      2873:               }
                   2874:           }
1.148     www      2875:         }
1.29      www      2876:        }
1.52      www      2877:    }
1.29      www      2878: 
1.52      www      2879: #
1.103     harris41 2880: # Gathered now: all privileges that could apply, and condition number
1.52      www      2881: # 
                   2882: #
                   2883: # Full or no access?
                   2884: #
1.29      www      2885: 
1.52      www      2886:     if ($thisallowed=~/F/) {
                   2887: 	return 'F';
                   2888:     }
1.29      www      2889: 
1.52      www      2890:     unless ($thisallowed) {
                   2891:         return '';
                   2892:     }
1.29      www      2893: 
1.52      www      2894: # Restrictions exist, deal with them
                   2895: #
                   2896: #   C:according to course preferences
                   2897: #   R:according to resource settings
                   2898: #   L:unless locked
                   2899: #   X:according to user session state
                   2900: #
                   2901: 
                   2902: # Possibly locked functionality, check all courses
1.54      www      2903: # Locks might take effect only after 10 minutes cache expiration for other
                   2904: # courses, and 2 minutes for current course
1.52      www      2905: 
                   2906:     my $envkey;
                   2907:     if ($thisallowed=~/L/) {
1.620     albertel 2908:         foreach $envkey (keys %env) {
1.54      www      2909:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   2910:                my $courseid=$2;
                   2911:                my $roleid=$1.'.'.$2;
1.92      www      2912:                $courseid=~s/^\///;
1.54      www      2913:                my $expiretime=600;
1.620     albertel 2914:                if ($env{'request.role'} eq $roleid) {
1.54      www      2915: 		  $expiretime=120;
                   2916:                }
                   2917: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   2918:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 2919:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.54      www      2920: 		   &coursedescription($courseid);
                   2921:                }
1.620     albertel 2922:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   2923:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   2924: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   2925:                        &log($env{'user.domain'},$env{'user.name'},
                   2926:                             $env{'user.home'},
1.57      www      2927:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      2928:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 2929:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2930: 		       return '';
                   2931:                    }
                   2932:                }
1.620     albertel 2933:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   2934:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   2935: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   2936:                        &log($env{'user.domain'},$env{'user.name'},
                   2937:                             $env{'user.home'},
1.57      www      2938:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      2939:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 2940:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      2941: 		       return '';
                   2942:                    }
                   2943:                }
                   2944: 	   }
1.29      www      2945:        }
1.52      www      2946:     }
                   2947:    
                   2948: #
                   2949: # Rest of the restrictions depend on selected course
                   2950: #
                   2951: 
1.620     albertel 2952:     unless ($env{'request.course.id'}) {
1.52      www      2953:        return '1';
                   2954:     }
1.29      www      2955: 
1.52      www      2956: #
                   2957: # Now user is definitely in a course
                   2958: #
1.53      www      2959: 
                   2960: 
                   2961: # Course preferences
                   2962: 
                   2963:    if ($thisallowed=~/C/) {
1.620     albertel 2964:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   2965:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   2966:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 2967: 	   =~/\Q$rolecode\E/) {
1.620     albertel 2968:            &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.57      www      2969:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
1.620     albertel 2970:                 $env{'request.course.id'});
1.237     www      2971:            return '';
                   2972:        }
                   2973: 
1.620     albertel 2974:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 2975: 	   =~/\Q$unamedom\E/) {
1.620     albertel 2976:            &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.237     www      2977:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
1.620     albertel 2978:                 $env{'request.course.id'});
1.54      www      2979:            return '';
                   2980:        }
1.53      www      2981:    }
                   2982: 
                   2983: # Resource preferences
                   2984: 
                   2985:    if ($thisallowed=~/R/) {
1.620     albertel 2986:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 2987:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.620     albertel 2988: 	  &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
1.57      www      2989:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
1.341     www      2990:           return '';
1.54      www      2991:        }
1.53      www      2992:    }
1.30      www      2993: 
1.246     www      2994: # Restricted by state or randomout?
1.30      www      2995: 
1.52      www      2996:    if ($thisallowed=~/X/) {
1.620     albertel 2997:       if ($env{'acc.randomout'}) {
1.579     albertel 2998: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 2999:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3000:             return ''; 
                   3001:          }
1.247     www      3002:       }
                   3003:       if (&condval($statecond)) {
1.52      www      3004: 	 return '2';
                   3005:       } else {
                   3006:          return '';
                   3007:       }
                   3008:    }
1.30      www      3009: 
1.52      www      3010:    return 'F';
1.232     www      3011: }
                   3012: 
                   3013: # --------------------------------------------------- Is a resource on the map?
                   3014: 
                   3015: sub is_on_map {
                   3016:     my $uri=&declutter(shift);
1.435     www      3017:     $uri=~s/\.\d+\.(\w+)$/\.$1/;
1.232     www      3018:     my @uriparts=split(/\//,$uri);
                   3019:     my $filename=$uriparts[$#uriparts];
                   3020:     my $pathname=$uri;
1.289     bowersj2 3021:     $pathname=~s|/\Q$filename\E$||;
1.332     www      3022:     $pathname=~s/^adm\/wrapper\///;    
1.289     bowersj2 3023:     #Trying to find the conditional for the file
1.620     albertel 3024:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3025: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3026:     if ($match) {
1.289     bowersj2 3027: 	return (1,$1);
                   3028:     } else {
1.434     www      3029: 	return (0,0);
1.289     bowersj2 3030:     }
1.12      www      3031: }
                   3032: 
1.427     www      3033: # --------------------------------------------------------- Get symb from alias
                   3034: 
                   3035: sub get_symb_from_alias {
                   3036:     my $symb=shift;
                   3037:     my ($map,$resid,$url)=&decode_symb($symb);
                   3038: # Already is a symb
                   3039:     if ($url) { return $symb; }
                   3040: # Must be an alias
                   3041:     my $aliassymb='';
                   3042:     my %bighash;
1.620     albertel 3043:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3044:                             &GDBM_READER(),0640)) {
                   3045:         my $rid=$bighash{'mapalias_'.$symb};
                   3046: 	if ($rid) {
                   3047: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3048: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3049: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3050: 	}
                   3051:         untie %bighash;
                   3052:     }
                   3053:     return $aliassymb;
                   3054: }
                   3055: 
1.12      www      3056: # ----------------------------------------------------------------- Define Role
                   3057: 
                   3058: sub definerole {
                   3059:   if (allowed('mcr','/')) {
                   3060:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3061:     foreach (split(':',$sysrole)) {
1.21      www      3062: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3063:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3064:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3065: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3066:                return "refused:s:$crole&$cqual"; 
                   3067:             }
                   3068:         }
1.191     harris41 3069:     }
1.392     www      3070:     foreach (split(':',$domrole)) {
1.21      www      3071: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3072:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3073:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3074: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3075:                return "refused:d:$crole&$cqual"; 
                   3076:             }
                   3077:         }
1.191     harris41 3078:     }
1.392     www      3079:     foreach (split(':',$courole)) {
1.21      www      3080: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3081:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3082:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3083: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3084:                return "refused:c:$crole&$cqual"; 
                   3085:             }
                   3086:         }
1.191     harris41 3087:     }
1.620     albertel 3088:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3089:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3090: 	        "rolesdef_$rolename=".
                   3091:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3092:     return reply($command,$env{'user.home'});
1.12      www      3093:   } else {
                   3094:     return 'refused';
                   3095:   }
1.105     harris41 3096: }
                   3097: 
                   3098: # ---------------- Make a metadata query against the network of library servers
                   3099: 
                   3100: sub metadata_query {
1.244     matthew  3101:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3102:     my %rhash;
1.244     matthew  3103:     my @server_list = (defined($server_array) ? @$server_array
                   3104:                                               : keys(%libserv) );
                   3105:     for my $server (@server_list) {
1.118     harris41 3106: 	unless ($custom or $customshow) {
                   3107: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3108: 	    $rhash{$server}=$reply;
                   3109: 	}
                   3110: 	else {
                   3111: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3112: 			     &escape($custom).':'.&escape($customshow),
                   3113: 			     $server);
                   3114: 	    $rhash{$server}=$reply;
                   3115: 	}
1.112     harris41 3116:     }
1.118     harris41 3117:     return \%rhash;
1.240     www      3118: }
                   3119: 
                   3120: # ----------------------------------------- Send log queries and wait for reply
                   3121: 
                   3122: sub log_query {
                   3123:     my ($uname,$udom,$query,%filters)=@_;
                   3124:     my $uhome=&homeserver($uname,$udom);
                   3125:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3126:     my $uhost=$hostname{$uhome};
1.241     www      3127:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3128:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3129:                        $uhome);
1.479     albertel 3130:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3131:     return get_query_reply($queryid);
                   3132: }
                   3133: 
1.508     raeburn  3134: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3135: 
                   3136: sub fetch_enrollment_query {
1.511     raeburn  3137:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3138:     my $homeserver;
1.547     raeburn  3139:     my $maxtries = 1;
1.508     raeburn  3140:     if ($context eq 'automated') {
                   3141:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3142:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3143:     } else {
                   3144:         $homeserver = &homeserver($cnum,$dom);
                   3145:     }
1.506     raeburn  3146:     my $host=$hostname{$homeserver};
                   3147:     my $cmd = '';
                   3148:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3149:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3150:     }
                   3151:     $cmd =~ s/%%$//;
                   3152:     $cmd = &escape($cmd);
                   3153:     my $query = 'fetchenrollment';
1.620     albertel 3154:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3155:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3156:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3157:         return 'error: '.$queryid;
                   3158:     }
1.506     raeburn  3159:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3160:     my $tries = 1;
                   3161:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3162:         $reply = &get_query_reply($queryid);
                   3163:         $tries ++;
                   3164:     }
1.526     raeburn  3165:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 3166:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  3167:     } else {
1.515     raeburn  3168:         my @responses = split/:/,$reply;
                   3169:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   3170:             foreach (@responses) {
                   3171:                 my ($key,$value) = split/=/,$_;
                   3172:                 $$replyref{$key} = $value;
                   3173:             }
                   3174:         } else {
1.506     raeburn  3175:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   3176:             foreach (@responses) {
                   3177:                 my ($key,$value) = split/=/,$_;
                   3178:                 $$replyref{$key} = $value;
                   3179:                 if ($value > 0) {
                   3180:                     foreach (@{$$affiliatesref{$key}}) {
                   3181:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   3182:                         my $destname = $pathname.'/'.$filename;
                   3183:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  3184:                         if ($xml_classlist =~ /^error/) {
                   3185:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   3186:                         } else {
1.506     raeburn  3187:                             if ( open(FILE,">$destname") ) {
                   3188:                                 print FILE &unescape($xml_classlist);
                   3189:                                 close(FILE);
1.526     raeburn  3190:                             } else {
                   3191:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  3192:                             }
                   3193:                         }
                   3194:                     }
                   3195:                 }
                   3196:             }
                   3197:         }
                   3198:         return 'ok';
                   3199:     }
                   3200:     return 'error';
                   3201: }
                   3202: 
1.242     www      3203: sub get_query_reply {
                   3204:     my $queryid=shift;
1.240     www      3205:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   3206:     my $reply='';
                   3207:     for (1..100) {
                   3208: 	sleep 2;
                   3209:         if (-e $replyfile.'.end') {
1.448     albertel 3210: 	    if (open(my $fh,$replyfile)) {
1.240     www      3211:                $reply.=<$fh>;
1.448     albertel 3212:                close($fh);
1.240     www      3213: 	   } else { return 'error: reply_file_error'; }
1.242     www      3214:            return &unescape($reply);
                   3215: 	}
1.240     www      3216:     }
1.242     www      3217:     return 'timeout:'.$queryid;
1.240     www      3218: }
                   3219: 
                   3220: sub courselog_query {
1.241     www      3221: #
                   3222: # possible filters:
                   3223: # url: url or symb
                   3224: # username
                   3225: # domain
                   3226: # action: view, submit, grade
                   3227: # start: timestamp
                   3228: # end: timestamp
                   3229: #
1.240     www      3230:     my (%filters)=@_;
1.620     albertel 3231:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      3232:     if ($filters{'url'}) {
                   3233: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   3234:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   3235:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   3236:     }
1.620     albertel 3237:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3238:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      3239:     return &log_query($cname,$cdom,'courselog',%filters);
                   3240: }
                   3241: 
                   3242: sub userlog_query {
                   3243:     my ($uname,$udom,%filters)=@_;
                   3244:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      3245: }
                   3246: 
1.506     raeburn  3247: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   3248: 
                   3249: sub auto_run {
1.508     raeburn  3250:     my ($cnum,$cdom) = @_;
                   3251:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3252:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  3253:     return $response;
                   3254: }
                   3255:                                                                                    
                   3256: sub auto_get_sections {
1.508     raeburn  3257:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   3258:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  3259:     my @secs = ();
1.511     raeburn  3260:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  3261:     unless ($response eq 'refused') {
                   3262:         @secs = split/:/,$response;
                   3263:     }
                   3264:     return @secs;
                   3265: }
                   3266:                                                                                    
                   3267: sub auto_new_course {
1.508     raeburn  3268:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   3269:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  3270:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  3271:     return $response;
                   3272: }
                   3273:                                                                                    
                   3274: sub auto_validate_courseID {
1.508     raeburn  3275:     my ($cnum,$cdom,$inst_course_id) = @_;
                   3276:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  3277:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  3278:     return $response;
                   3279: }
                   3280:                                                                                    
                   3281: sub auto_create_password {
1.508     raeburn  3282:     my ($cnum,$cdom,$authparam) = @_;
                   3283:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  3284:     my $create_passwd = 0;
                   3285:     my $authchk = '';
1.511     raeburn  3286:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  3287:     if ($response eq 'refused') {
                   3288:         $authchk = 'refused';
                   3289:     } else {
                   3290:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   3291:     }
                   3292:     return ($authparam,$create_passwd,$authchk);
                   3293: }
                   3294: 
1.521     raeburn  3295: sub auto_instcode_format {
                   3296:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
                   3297:     my $courses = '';
                   3298:     my $homeserver;
                   3299:     if ($caller eq 'global') {
1.584     raeburn  3300:         foreach my $tryserver (keys %libserv) {
                   3301:             if ($hostdom{$tryserver} eq $codedom) {
                   3302:                 $homeserver = $tryserver;
                   3303:                 last;
                   3304:             }
                   3305:         }
1.620     albertel 3306:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
                   3307:             $homeserver = &homeserver($env{'user.name'},$codedom);
1.584     raeburn  3308:         }
1.521     raeburn  3309:     } else {
                   3310:         $homeserver = &homeserver($caller,$codedom);
                   3311:     }
                   3312:     foreach (keys %{$instcodes}) {
                   3313:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
                   3314:     }
                   3315:     chop($courses);
                   3316:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
                   3317:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   3318:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
                   3319:         %{$codes} = &str2hash($codes_str);
                   3320:         @{$codetitles} = &str2array($codetitles_str);
                   3321:         %{$cat_titles} = &str2hash($cat_titles_str);
                   3322:         %{$cat_order} = &str2hash($cat_order_str);
                   3323:         return 'ok';
                   3324:     }
                   3325:     return $response;
                   3326: }
                   3327: 
1.12      www      3328: # ------------------------------------------------------------------ Plain Text
                   3329: 
                   3330: sub plaintext {
1.22      www      3331:     my $short=shift;
1.414     www      3332:     return &mt($prp{$short});
1.12      www      3333: }
                   3334: 
                   3335: # ----------------------------------------------------------------- Assign Role
                   3336: 
                   3337: sub assignrole {
1.357     www      3338:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      3339:     my $mrole;
                   3340:     if ($role =~ /^cr\//) {
1.393     www      3341:         my $cwosec=$url;
                   3342:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   3343: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      3344:            &logthis('Refused custom assignrole: '.
                   3345:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3346: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3347:            return 'refused'; 
                   3348:         }
1.21      www      3349:         $mrole='cr';
                   3350:     } else {
1.82      www      3351:         my $cwosec=$url;
1.83      www      3352:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      3353:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      3354:            &logthis('Refused assignrole: '.
                   3355:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 3356: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      3357:            return 'refused'; 
                   3358:         }
1.21      www      3359:         $mrole=$role;
                   3360:     }
1.620     albertel 3361:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3362:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      3363:     if ($end) { $command.='_'.$end; }
1.21      www      3364:     if ($start) {
                   3365: 	if ($end) { 
1.81      www      3366:            $command.='_'.$start; 
1.21      www      3367:         } else {
1.81      www      3368:            $command.='_0_'.$start;
1.21      www      3369:         }
                   3370:     }
1.357     www      3371: # actually delete
                   3372:     if ($deleteflag) {
1.373     www      3373: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      3374: # modify command to delete the role
1.620     albertel 3375:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      3376:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 3377: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      3378: # set start and finish to negative values for userrolelog
                   3379:            $start=-1;
                   3380:            $end=-1;
                   3381:         }
                   3382:     }
                   3383: # send command
1.349     www      3384:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      3385: # log new user role if status is ok
1.349     www      3386:     if ($answer eq 'ok') {
                   3387: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
                   3388:     }
                   3389:     return $answer;
1.169     harris41 3390: }
                   3391: 
                   3392: # -------------------------------------------------- Modify user authentication
1.197     www      3393: # Overrides without validation
                   3394: 
1.169     harris41 3395: sub modifyuserauth {
                   3396:     my ($udom,$uname,$umode,$upass)=@_;
                   3397:     my $uhome=&homeserver($uname,$udom);
1.197     www      3398:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   3399:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 3400:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   3401:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 3402:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   3403: 		     &escape($upass),$uhome);
1.620     albertel 3404:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      3405:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   3406:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   3407:     &log($udom,,$uname,$uhome,
1.620     albertel 3408:         'Authentication changed by '.$env{'user.domain'}.', '.
                   3409:                                      $env{'user.name'}.', '.$umode.
1.197     www      3410:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 3411:     unless ($reply eq 'ok') {
1.197     www      3412:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 3413: 	return 'error: '.$reply;
                   3414:     }   
1.170     harris41 3415:     return 'ok';
1.80      www      3416: }
                   3417: 
1.81      www      3418: # --------------------------------------------------------------- Modify a user
1.80      www      3419: 
1.81      www      3420: sub modifyuser {
1.206     matthew  3421:     my ($udom,    $uname, $uid,
                   3422:         $umode,   $upass, $first,
                   3423:         $middle,  $last,  $gene,
1.387     www      3424:         $forceid, $desiredhome, $email)=@_;
1.198     www      3425:     $udom=~s/\W//g;
                   3426:     $uname=~s/\W//g;
1.81      www      3427:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3428:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  3429: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   3430:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   3431:                                      ' desiredhome not specified'). 
1.620     albertel 3432:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   3433:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 3434:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      3435: # ----------------------------------------------------------------- Create User
1.406     albertel 3436:     if (($uhome eq 'no_host') && 
                   3437: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      3438:         my $unhome='';
1.209     matthew  3439:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   3440:             $unhome = $desiredhome;
1.620     albertel 3441: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   3442: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  3443:         } else { # load balancing routine for determining $unhome
1.80      www      3444:             my $tryserver;
1.81      www      3445:             my $loadm=10000000;
1.80      www      3446:             foreach $tryserver (keys %libserv) {
                   3447: 	       if ($hostdom{$tryserver} eq $udom) {
                   3448:                   my $answer=reply('load',$tryserver);
                   3449:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   3450: 		      $loadm=$answer;
                   3451:                       $unhome=$tryserver;
                   3452:                   }
                   3453: 	       }
                   3454: 	    }
                   3455:         }
                   3456:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  3457: 	    return 'error: unable to find a home server for '.$uname.
                   3458:                    ' in domain '.$udom;
1.80      www      3459:         }
                   3460:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   3461:                          &escape($upass),$unhome);
                   3462: 	unless ($reply eq 'ok') {
                   3463:             return 'error: '.$reply;
                   3464:         }   
1.230     stredwic 3465:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      3466:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  3467: 	    return 'error: unable verify users home machine.';
1.80      www      3468:         }
1.209     matthew  3469:     }   # End of creation of new user
1.80      www      3470: # ---------------------------------------------------------------------- Add ID
                   3471:     if ($uid) {
                   3472:        $uid=~tr/A-Z/a-z/;
                   3473:        my %uidhash=&idrget($udom,$uname);
1.196     www      3474:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   3475:          && (!$forceid)) {
1.80      www      3476: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  3477: 	      return 'error: user id "'.$uid.'" does not match '.
                   3478:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      3479:           }
                   3480:        } else {
                   3481: 	  &idput($udom,($uname => $uid));
                   3482:        }
                   3483:     }
                   3484: # -------------------------------------------------------------- Add names, etc
1.313     matthew  3485:     my @tmp=&get('environment',
1.134     albertel 3486: 		   ['firstname','middlename','lastname','generation'],
                   3487: 		   $udom,$uname);
1.313     matthew  3488:     my %names;
                   3489:     if ($tmp[0] =~ m/^error:.*/) { 
                   3490:         %names=(); 
                   3491:     } else {
                   3492:         %names = @tmp;
                   3493:     }
1.388     www      3494: #
                   3495: # Make sure to not trash student environment if instructor does not bother
                   3496: # to supply name and email information
                   3497: #
                   3498:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  3499:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      3500:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  3501:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      3502:     if ($email) {
                   3503:        $email=~s/[^\w\@\.\-\,]//gs;
                   3504:        if ($email=~/\@/) { $names{'notification'} = $email;
                   3505: 			   $names{'critnotification'} = $email;
                   3506: 			   $names{'permanentemail'} = $email; }
                   3507:     }
1.134     albertel 3508:     my $reply = &put('environment', \%names, $udom,$uname);
                   3509:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.81      www      3510:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      3511:              $umode.', '.$first.', '.$middle.', '.
                   3512: 	     $last.', '.$gene.' by '.
1.620     albertel 3513:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 3514:     return 'ok';
1.80      www      3515: }
                   3516: 
1.81      www      3517: # -------------------------------------------------------------- Modify student
1.80      www      3518: 
1.81      www      3519: sub modifystudent {
                   3520:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  3521:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 3522:     if (!$cid) {
1.620     albertel 3523: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 3524: 	    return 'not_in_class';
                   3525: 	}
1.80      www      3526:     }
                   3527: # --------------------------------------------------------------- Make the user
1.81      www      3528:     my $reply=&modifyuser
1.209     matthew  3529: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      3530:          $desiredhome,$email);
1.80      www      3531:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  3532:     # This will cause &modify_student_enrollment to get the uid from the
                   3533:     # students environment
                   3534:     $uid = undef if (!$forceid);
1.455     albertel 3535:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  3536: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  3537:     return $reply;
                   3538: }
                   3539: 
                   3540: sub modify_student_enrollment {
1.515     raeburn  3541:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 3542:     my ($cdom,$cnum,$chome);
                   3543:     if (!$cid) {
1.620     albertel 3544: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 3545: 	    return 'not_in_class';
                   3546: 	}
1.620     albertel 3547: 	$cdom=$env{'course.'.$cid.'.domain'};
                   3548: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 3549:     } else {
                   3550: 	($cdom,$cnum)=split(/_/,$cid);
                   3551:     }
1.620     albertel 3552:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 3553:     if (!$chome) {
1.457     raeburn  3554: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  3555:     }
1.455     albertel 3556:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  3557:     # Make sure the user exists
1.81      www      3558:     my $uhome=&homeserver($uname,$udom);
                   3559:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3560: 	return 'error: no such user';
                   3561:     }
1.297     matthew  3562:     # Get student data if we were not given enough information
                   3563:     if (!defined($first)  || $first  eq '' || 
                   3564:         !defined($last)   || $last   eq '' || 
                   3565:         !defined($uid)    || $uid    eq '' || 
                   3566:         !defined($middle) || $middle eq '' || 
                   3567:         !defined($gene)   || $gene   eq '') {
1.294     matthew  3568:         # They did not supply us with enough data to enroll the student, so
                   3569:         # we need to pick up more information.
1.297     matthew  3570:         my %tmp = &get('environment',
1.294     matthew  3571:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  3572:                        ,$udom,$uname);
                   3573: 
1.455     albertel 3574:         #foreach (keys(%tmp)) {
                   3575:         #    &logthis("key $_ = ".$tmp{$_});
                   3576:         #}
1.294     matthew  3577:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   3578:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   3579:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  3580:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  3581:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   3582:     }
1.556     albertel 3583:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 3584:     my $reply=cput('classlist',
                   3585: 		   {"$uname:$udom" => 
1.515     raeburn  3586: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 3587: 		   $cdom,$cnum);
1.81      www      3588:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   3589: 	return 'error: '.$reply;
                   3590:     }
1.297     matthew  3591:     # Add student role to user
1.83      www      3592:     my $uurl='/'.$cid;
1.81      www      3593:     $uurl=~s/\_/\//g;
                   3594:     if ($usec) {
                   3595: 	$uurl.='/'.$usec;
                   3596:     }
                   3597:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      3598: }
                   3599: 
1.556     albertel 3600: sub format_name {
                   3601:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   3602:     my $name;
                   3603:     if ($first ne 'lastname') {
                   3604: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   3605:     } else {
                   3606: 	if ($lastname=~/\S/) {
                   3607: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   3608: 	    $name=~s/\s+,/,/;
                   3609: 	} else {
                   3610: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   3611: 	}
                   3612:     }
                   3613:     $name=~s/^\s+//;
                   3614:     $name=~s/\s+$//;
                   3615:     $name=~s/\s+/ /g;
                   3616:     return $name;
                   3617: }
                   3618: 
1.84      www      3619: # ------------------------------------------------- Write to course preferences
                   3620: 
                   3621: sub writecoursepref {
                   3622:     my ($courseid,%prefs)=@_;
                   3623:     $courseid=~s/^\///;
                   3624:     $courseid=~s/\_/\//g;
                   3625:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   3626:     my $chome=homeserver($cnum,$cdomain);
                   3627:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   3628: 	return 'error: no such course';
                   3629:     }
                   3630:     my $cstring='';
1.191     harris41 3631:     foreach (keys %prefs) {
1.84      www      3632: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 3633:     }
1.84      www      3634:     $cstring=~s/\&$//;
                   3635:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   3636: }
                   3637: 
                   3638: # ---------------------------------------------------------- Make/modify course
                   3639: 
                   3640: sub createcourse {
1.571     raeburn  3641:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
1.84      www      3642:     $url=&declutter($url);
                   3643:     my $cid='';
1.264     matthew  3644:     unless (&allowed('ccc',$udom)) {
1.84      www      3645:         return 'refused';
                   3646:     }
                   3647: # ------------------------------------------------------------------- Create ID
                   3648:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3649:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   3650: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 3651:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      3652:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3653:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   3654:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 3655:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      3656:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   3657:            return 'error: unable to generate unique course-ID';
                   3658:        } 
                   3659:    }
1.264     matthew  3660: # ------------------------------------------------ Check supplied server name
1.620     albertel 3661:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  3662:     if (! exists($libserv{$course_server})) {
                   3663:         return 'error:bad server name '.$course_server;
                   3664:     }
1.84      www      3665: # ------------------------------------------------------------- Make the course
                   3666:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  3667:                       $course_server);
1.84      www      3668:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 3669:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      3670:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   3671: 	return 'error: no such course';
                   3672:     }
1.271     www      3673: # ----------------------------------------------------------------- Course made
1.516     raeburn  3674: # log existence
                   3675:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.571     raeburn  3676:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
1.358     www      3677:     &flushcourselogs();
                   3678: # set toplevel url
1.271     www      3679:     my $topurl=$url;
                   3680:     unless ($nonstandard) {
                   3681: # ------------------------------------------ For standard courses, make top url
                   3682:         my $mapurl=&clutter($url);
1.278     www      3683:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 3684:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      3685: <map>
                   3686: <resource id="1" type="start"></resource>
                   3687: <resource id="2" src="$mapurl"></resource>
                   3688: <resource id="3" type="finish"></resource>
                   3689: <link index="1" from="1" to="2"></link>
                   3690: <link index="2" from="2" to="3"></link>
                   3691: </map>
                   3692: ENDINITMAP
                   3693:         $topurl=&declutter(
                   3694:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
                   3695:                           );
                   3696:     }
                   3697: # ----------------------------------------------------------- Write preferences
1.84      www      3698:     &writecoursepref($udom.'_'.$uname,
                   3699:                      ('description' => $description,
1.271     www      3700:                       'url'         => $topurl));
1.84      www      3701:     return '/'.$udom.'/'.$uname;
                   3702: }
                   3703: 
1.21      www      3704: # ---------------------------------------------------------- Assign Custom Role
                   3705: 
                   3706: sub assigncustomrole {
1.357     www      3707:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      3708:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      3709:                        $end,$start,$deleteflag);
1.21      www      3710: }
                   3711: 
                   3712: # ----------------------------------------------------------------- Revoke Role
                   3713: 
                   3714: sub revokerole {
1.357     www      3715:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      3716:     my $now=time;
1.357     www      3717:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      3718: }
                   3719: 
                   3720: # ---------------------------------------------------------- Revoke Custom Role
                   3721: 
                   3722: sub revokecustomrole {
1.357     www      3723:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      3724:     my $now=time;
1.357     www      3725:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   3726:            $deleteflag);
1.17      www      3727: }
                   3728: 
1.533     banghart 3729: # ------------------------------------------------------------ Disk usage
1.535     albertel 3730: sub diskusage {
1.533     banghart 3731:     my ($udom,$uname,$directoryRoot)=@_;
                   3732:     $directoryRoot =~ s/\/$//;
1.535     albertel 3733:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 3734:     return $listing;
1.512     banghart 3735: }
                   3736: 
1.566     banghart 3737: sub is_locked {
                   3738:     my ($file_name, $domain, $user) = @_;
                   3739:     my @check;
                   3740:     my $is_locked;
                   3741:     push @check, $file_name;
1.613     albertel 3742:     my %locked = &get('file_permissions',\@check,
1.620     albertel 3743: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 3744:     my ($tmp)=keys(%locked);
                   3745:     if ($tmp=~/^error:/) { undef(%locked); }
1.613     albertel 3746: 
1.566     banghart 3747:     if (ref($locked{$file_name}) eq 'ARRAY') {
                   3748:         $is_locked = 'true';
                   3749:     } else {
                   3750:         $is_locked = 'false';
                   3751:     }
                   3752: }
                   3753: 
1.559     banghart 3754: # ------------------------------------------------------------- Mark as Read Only
                   3755: 
                   3756: sub mark_as_readonly {
                   3757:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 3758:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 3759:     my ($tmp)=keys(%current_permissions);
                   3760:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3761: 
1.560     banghart 3762:     foreach my $file (@{$files}) {
1.561     banghart 3763:         push(@{$current_permissions{$file}},$what);
1.559     banghart 3764:     }
1.613     albertel 3765:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 3766:     return;
                   3767: }
                   3768: 
1.572     banghart 3769: # ------------------------------------------------------------Save Selected Files
                   3770: 
                   3771: sub save_selected_files {
                   3772:     my ($user, $path, @files) = @_;
                   3773:     my $filename = $user."savedfiles";
1.573     banghart 3774:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 3775:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 3776:     foreach my $file (@files) {
1.620     albertel 3777:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 3778:     }
                   3779:     foreach my $file (@other_files) {
1.574     banghart 3780:         print (OUT $file."\n");
1.572     banghart 3781:     }
1.574     banghart 3782:     close (OUT);
1.572     banghart 3783:     return 'ok';
                   3784: }
                   3785: 
1.574     banghart 3786: sub clear_selected_files {
                   3787:     my ($user) = @_;
                   3788:     my $filename = $user."savedfiles";
                   3789:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   3790:     print (OUT undef);
                   3791:     close (OUT);
                   3792:     return ("ok");    
                   3793: }
                   3794: 
1.572     banghart 3795: sub files_in_path {
                   3796:     my ($user, $path) = @_;
                   3797:     my $filename = $user."savedfiles";
                   3798:     my %return_files;
1.574     banghart 3799:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 3800:     while (my $line_in = <IN>) {
1.574     banghart 3801:         chomp ($line_in);
                   3802:         my @paths_and_file = split (m!/!, $line_in);
                   3803:         my $file_part = pop (@paths_and_file);
                   3804:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 3805:         $path_part.='/';
                   3806:         my $path_and_file = $path_part.$file_part;
                   3807:         if ($path_part eq $path) {
                   3808:             $return_files{$file_part}= 'selected';
                   3809:         }
                   3810:     }
1.574     banghart 3811:     close (IN);
                   3812:     return (\%return_files);
1.572     banghart 3813: }
                   3814: 
                   3815: # called in portfolio select mode, to show files selected NOT in current directory
                   3816: sub files_not_in_path {
                   3817:     my ($user, $path) = @_;
                   3818:     my $filename = $user."savedfiles";
                   3819:     my @return_files;
                   3820:     my $path_part;
1.574     banghart 3821:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 3822:     while (<IN>) {
                   3823:         #ok, I know it's clunky, but I want it to work
                   3824:         my @paths_and_file = split m!/!, $_;
1.574     banghart 3825:         my $file_part = pop (@paths_and_file);
                   3826:         chomp ($file_part);
                   3827:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 3828:         $path_part .= '/';
                   3829:         my $path_and_file = $path_part.$file_part;
                   3830:         if ($path_part ne $path) {
1.574     banghart 3831:             push (@return_files, ($path_and_file));
1.572     banghart 3832:         }
                   3833:     }
1.574     banghart 3834:     close (OUT);
                   3835:     return (@return_files);
1.572     banghart 3836: }
                   3837: 
1.561     banghart 3838: #--------------------------------------------------------------Get Marked as Read Only
                   3839: 
                   3840: sub get_marked_as_readonly {
                   3841:     my ($domain,$user,$what) = @_;
1.613     albertel 3842:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 3843:     my ($tmp)=keys(%current_permissions);
                   3844:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3845: 
1.563     banghart 3846:     my @readonly_files;
                   3847:     while (my ($file_name,$value) = each(%current_permissions)) {
1.561     banghart 3848:         if (ref($value) eq "ARRAY"){
                   3849:             foreach my $stored_what (@{$value}) {
                   3850:                 if ($stored_what eq $what) {
                   3851:                     push(@readonly_files, $file_name);
1.563     banghart 3852:                 } elsif (!defined($what)) {
                   3853:                     push(@readonly_files, $file_name);
1.561     banghart 3854:                 }
                   3855:             }
                   3856:         } 
                   3857:     }
                   3858:     return @readonly_files;
                   3859: }
1.577     banghart 3860: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 3861: 
1.577     banghart 3862: sub get_marked_as_readonly_hash {
                   3863:     my ($domain,$user,$what) = @_;
1.613     albertel 3864:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 3865:     my ($tmp)=keys(%current_permissions);
                   3866:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3867: 
1.577     banghart 3868:     my %readonly_files;
                   3869:     while (my ($file_name,$value) = each(%current_permissions)) {
                   3870:         if (ref($value) eq "ARRAY"){
                   3871:             foreach my $stored_what (@{$value}) {
                   3872:                 if ($stored_what eq $what) {
                   3873:                     $readonly_files{$file_name} = 'locked';
                   3874:                 } elsif (!defined($what)) {
                   3875:                     $readonly_files{$file_name} = 'locked';
                   3876:                 }
                   3877:             }
                   3878:         } 
                   3879:     }
                   3880:     return %readonly_files;
                   3881: }
1.559     banghart 3882: # ------------------------------------------------------------ Unmark as Read Only
                   3883: 
                   3884: sub unmark_as_readonly {
1.561     banghart 3885:     # unmarks all files locked by $what 
                   3886:     # for portfolio submissions, $what contains $crsid and $symb
                   3887:     my ($domain,$user,$what) = @_;
1.613     albertel 3888:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 3889:     my ($tmp)=keys(%current_permissions);
                   3890:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.613     albertel 3891: 
                   3892:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
1.561     banghart 3893:     foreach my $file(@readonly_files){
1.563     banghart 3894:         my $current_locks = $current_permissions{$file};
                   3895:         my @new_locks;
                   3896:         my @del_keys;
                   3897:         if (ref($current_locks) eq "ARRAY"){
                   3898:             foreach my $locker (@{$current_locks}) {
                   3899:                 unless ($locker eq $what) {
                   3900:                     push(@new_locks, $what);
                   3901:                 }
                   3902:             }
                   3903:             if (@new_locks > 0) {
                   3904:                 $current_permissions{$file} = \@new_locks;
                   3905:             } else {
                   3906:                 push(@del_keys, $file);
1.613     albertel 3907:                 &del('file_permissions',\@del_keys, $domain, $user);
1.563     banghart 3908:                 delete $current_permissions{$file};
                   3909:             }
                   3910:         }
1.561     banghart 3911:     }
1.613     albertel 3912:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 3913:     return;
                   3914: }
1.512     banghart 3915: 
1.17      www      3916: # ------------------------------------------------------------ Directory lister
                   3917: 
                   3918: sub dirlist {
1.253     stredwic 3919:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   3920: 
1.18      www      3921:     $uri=~s/^\///;
                   3922:     $uri=~s/\/$//;
1.253     stredwic 3923:     my ($udom, $uname);
                   3924:     (undef,$udom,$uname)=split(/\//,$uri);
                   3925:     if(defined($userdomain)) {
                   3926:         $udom = $userdomain;
                   3927:     }
                   3928:     if(defined($username)) {
                   3929:         $uname = $username;
                   3930:     }
                   3931: 
                   3932:     my $dirRoot = $perlvar{'lonDocRoot'};
                   3933:     if(defined($alternateDirectoryRoot)) {
                   3934:         $dirRoot = $alternateDirectoryRoot;
                   3935:         $dirRoot =~ s/\/$//;
                   3936:     }
                   3937: 
                   3938:     if($udom) {
                   3939:         if($uname) {
1.605     matthew  3940:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 3941:                               homeserver($uname,$udom));
1.605     matthew  3942:             my @listing_results;
                   3943:             if ($listing eq 'unknown_cmd') {
                   3944:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   3945:                                homeserver($uname,$udom));
                   3946:                 @listing_results = split(/:/,$listing);
                   3947:             } else {
                   3948:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   3949:             }
                   3950:             return @listing_results;
1.253     stredwic 3951:         } elsif(!defined($alternateDirectoryRoot)) {
                   3952:             my $tryserver;
                   3953:             my %allusers=();
                   3954:             foreach $tryserver (keys %libserv) {
                   3955:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  3956:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 3957:                                       $udom, $tryserver);
1.605     matthew  3958:                     my @listing_results;
                   3959:                     if ($listing eq 'unknown_cmd') {
                   3960:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   3961:                                        $udom, $tryserver);
                   3962:                         @listing_results = split(/:/,$listing);
                   3963:                     } else {
                   3964:                         @listing_results =
                   3965:                             map { &unescape($_); } split(/:/,$listing);
                   3966:                     }
                   3967:                     if ($listing_results[0] ne 'no_such_dir' && 
                   3968:                         $listing_results[0] ne 'empty'       &&
                   3969:                         $listing_results[0] ne 'con_lost') {
                   3970:                         foreach (@listing_results) {
1.253     stredwic 3971:                             my ($entry,@stat)=split(/&/,$_);
                   3972:                             $allusers{$entry}=1;
                   3973:                         }
                   3974:                     }
1.191     harris41 3975:                 }
1.253     stredwic 3976:             }
                   3977:             my $alluserstr='';
                   3978:             foreach (sort keys %allusers) {
                   3979:                 $alluserstr.=$_.'&user:';
                   3980:             }
                   3981:             $alluserstr=~s/:$//;
                   3982:             return split(/:/,$alluserstr);
                   3983:         } else {
                   3984:             my @emptyResults = ();
                   3985:             push(@emptyResults, 'missing user name');
                   3986:             return split(':',@emptyResults);
                   3987:         }
                   3988:     } elsif(!defined($alternateDirectoryRoot)) {
                   3989:         my $tryserver;
                   3990:         my %alldom=();
                   3991:         foreach $tryserver (keys %libserv) {
                   3992:             $alldom{$hostdom{$tryserver}}=1;
                   3993:         }
                   3994:         my $alldomstr='';
                   3995:         foreach (sort keys %alldom) {
1.397     albertel 3996:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 3997:         }
                   3998:         $alldomstr=~s/:$//;
                   3999:         return split(/:/,$alldomstr);       
                   4000:     } else {
                   4001:         my @emptyResults = ();
                   4002:         push(@emptyResults, 'missing domain');
                   4003:         return split(':',@emptyResults);
1.275     stredwic 4004:     }
                   4005: }
                   4006: 
                   4007: # --------------------------------------------- GetFileTimestamp
                   4008: # This function utilizes dirlist and returns the date stamp for
                   4009: # when it was last modified.  It will also return an error of -1
                   4010: # if an error occurs
                   4011: 
1.410     matthew  4012: ##
                   4013: ## FIXME: This subroutine assumes its caller knows something about the
                   4014: ## directory structure of the home server for the student ($root).
                   4015: ## Not a good assumption to make.  Since this is for looking up files
                   4016: ## in user directories, the full path should be constructed by lond, not
                   4017: ## whatever machine we request data from.
                   4018: ##
1.275     stredwic 4019: sub GetFileTimestamp {
                   4020:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   4021:     $studentDomain=~s/\W//g;
                   4022:     $studentName=~s/\W//g;
                   4023:     my $subdir=$studentName.'__';
                   4024:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   4025:     my $proname="$studentDomain/$subdir/$studentName";
                   4026:     $proname .= '/'.$filename;
1.375     matthew  4027:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   4028:                                               $studentName, $root);
1.275     stredwic 4029:     my @stats = split('&', $fileStat);
                   4030:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  4031:         # @stats contains first the filename, then the stat output
                   4032:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 4033:     } else {
                   4034:         return -1;
1.253     stredwic 4035:     }
1.26      www      4036: }
                   4037: 
                   4038: # -------------------------------------------------------- Value of a Condition
                   4039: 
1.40      www      4040: sub directcondval {
                   4041:     my $number=shift;
1.620     albertel 4042:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 4043: 	&Apache::lonuserstate::evalstate();
                   4044:     }
1.620     albertel 4045:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   4046:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      4047:     } else {
                   4048:        return 2;
                   4049:     }
                   4050: }
                   4051: 
1.26      www      4052: sub condval {
                   4053:     my $condidx=shift;
                   4054:     my $result=0;
1.54      www      4055:     my $allpathcond='';
1.191     harris41 4056:     foreach (split(/\|/,$condidx)) {
1.620     albertel 4057:        if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$_})) {
1.54      www      4058: 	   $allpathcond.=
1.620     albertel 4059:                '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$_}.')|';
1.54      www      4060:        }
1.191     harris41 4061:     }
1.54      www      4062:     $allpathcond=~s/\|$//;
1.620     albertel 4063:     if ($env{'request.course.id'}) {
1.54      www      4064:        if ($allpathcond) {
1.26      www      4065:           my $operand='|';
                   4066: 	  my @stack;
1.191     harris41 4067:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
1.26      www      4068:               if ($_ eq '(') {
                   4069:                  push @stack,($operand,$result)
                   4070:               } elsif ($_ eq ')') {
                   4071:                   my $before=pop @stack;
                   4072: 		  if (pop @stack eq '&') {
                   4073: 		      $result=$result>$before?$before:$result;
                   4074:                   } else {
                   4075:                       $result=$result>$before?$result:$before;
                   4076:                   }
                   4077:               } elsif (($_ eq '&') || ($_ eq '|')) {
                   4078:                   $operand=$_;
                   4079:               } else {
1.40      www      4080:                   my $new=directcondval($_);
1.26      www      4081:                   if ($operand eq '&') {
                   4082:                      $result=$result>$new?$new:$result;
                   4083:                   } else {
                   4084:                      $result=$result>$new?$result:$new;
1.191     harris41 4085:                   }
1.26      www      4086:               }
1.191     harris41 4087:           }
1.26      www      4088:        }
                   4089:     }
                   4090:     return $result;
1.421     albertel 4091: }
                   4092: 
                   4093: # ---------------------------------------------------- Devalidate courseresdata
                   4094: 
                   4095: sub devalidatecourseresdata {
                   4096:     my ($coursenum,$coursedomain)=@_;
                   4097:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4098:     &devalidate_cache_new('courseres',$hashid);
1.28      www      4099: }
                   4100: 
1.200     www      4101: # --------------------------------------------------- Course Resourcedata Query
                   4102: 
1.624     albertel 4103: sub get_courseresdata {
                   4104:     my ($coursenum,$coursedomain)=@_;
1.200     www      4105:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   4106:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 4107:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 4108:     my %dumpreply;
1.417     albertel 4109:     unless (defined($cached)) {
1.624     albertel 4110: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 4111: 	$result=\%dumpreply;
1.251     albertel 4112: 	my ($tmp) = keys(%dumpreply);
                   4113: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 4114: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 4115: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   4116: 	    return $tmp;
1.416     albertel 4117: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 4118: 	    $result=undef;
1.599     albertel 4119: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 4120: 	}
                   4121:     }
1.624     albertel 4122:     return $result;
                   4123: }
                   4124: 
                   4125: sub get_userresdata {
                   4126:     my ($uname,$udom)=@_;
                   4127:     #most student don\'t have any data set, check if there is some data
                   4128:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   4129: 
                   4130:     my $hashid="$udom:$uname";
                   4131:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   4132:     if (!defined($cached)) {
                   4133: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   4134: 	$result=\%resourcedata;
                   4135: 	&do_cache_new('userres',$hashid,$result,600);
                   4136:     }
                   4137:     my ($tmp)=keys(%$result);
                   4138:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   4139: 	return $result;
                   4140:     }
                   4141:     #error 2 occurs when the .db doesn't exist
                   4142:     if ($tmp!~/error: 2 /) {
                   4143: 	&logthis("<font color=blue>WARNING:".
                   4144: 		 " Trying to get resource data for ".
                   4145: 		 $uname." at ".$udom.": ".
                   4146: 		 $tmp."</font>");
                   4147:     } elsif ($tmp=~/error: 2 /) {
                   4148: 	&EXT_cache_set($udom,$uname);
                   4149:     }
                   4150:     return $tmp;
                   4151: }
                   4152: 
                   4153: sub resdata {
                   4154:     my ($name,$domain,$type,@which)=@_;
                   4155:     my $result;
                   4156:     if ($type eq 'course') {
                   4157: 	$result=&get_courseresdata($name,$domain);
                   4158:     } elsif ($type eq 'user') {
                   4159: 	$result=&get_userresdata($name,$domain);
                   4160:     }
                   4161:     if (!ref($result)) { return $result; }    
1.251     albertel 4162:     foreach my $item (@which) {
1.417     albertel 4163: 	if (defined($result->{$item})) {
                   4164: 	    return $result->{$item};
1.251     albertel 4165: 	}
1.250     albertel 4166:     }
1.291     albertel 4167:     return undef;
1.200     www      4168: }
                   4169: 
1.379     matthew  4170: #
                   4171: # EXT resource caching routines
                   4172: #
                   4173: 
                   4174: sub clear_EXT_cache_status {
1.383     albertel 4175:     &delenv('cache.EXT.');
1.379     matthew  4176: }
                   4177: 
                   4178: sub EXT_cache_status {
                   4179:     my ($target_domain,$target_user) = @_;
1.383     albertel 4180:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 4181:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  4182:         # We know already the user has no data
                   4183:         return 1;
                   4184:     } else {
                   4185:         return 0;
                   4186:     }
                   4187: }
                   4188: 
                   4189: sub EXT_cache_set {
                   4190:     my ($target_domain,$target_user) = @_;
1.383     albertel 4191:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.379     matthew  4192:     &appenv($cachename => time);
                   4193: }
                   4194: 
1.28      www      4195: # --------------------------------------------------------- Value of a Variable
1.58      www      4196: sub EXT {
1.395     albertel 4197:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.218     albertel 4198: 
1.68      www      4199:     unless ($varname) { return ''; }
1.218     albertel 4200:     #get real user name/domain, courseid and symb
                   4201:     my $courseid;
1.359     albertel 4202:     my $publicuser;
1.427     www      4203:     if ($symbparm) {
                   4204: 	$symbparm=&get_symb_from_alias($symbparm);
                   4205:     }
1.218     albertel 4206:     if (!($uname && $udom)) {
1.360     albertel 4207:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378     matthew  4208: 	  &Apache::lonxml::whichuser($symbparm);
1.218     albertel 4209:       if (!$symbparm) {	$symbparm=$cursymb; }
                   4210:     } else {
1.620     albertel 4211: 	$courseid=$env{'request.course.id'};
1.218     albertel 4212:     }
1.48      www      4213:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   4214:     my $rest;
1.320     albertel 4215:     if (defined($therest[0])) {
1.48      www      4216:        $rest=join('.',@therest);
                   4217:     } else {
                   4218:        $rest='';
                   4219:     }
1.320     albertel 4220: 
1.57      www      4221:     my $qualifierrest=$qualifier;
                   4222:     if ($rest) { $qualifierrest.='.'.$rest; }
                   4223:     my $spacequalifierrest=$space;
                   4224:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      4225:     if ($realm eq 'user') {
1.48      www      4226: # --------------------------------------------------------------- user.resource
                   4227: 	if ($space eq 'resource') {
1.618     albertel 4228: 	    if (defined($Apache::lonhomework::parsing_a_problem) ||
                   4229: 		defined($Apache::lonhomework::parsing_a_task)) {
1.335     albertel 4230: 		return $Apache::lonhomework::history{$qualifierrest};
                   4231: 	    } else {
1.359     albertel 4232: 		my %restored;
1.620     albertel 4233: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 4234: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   4235: 		} else {
                   4236: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   4237: 		}
1.335     albertel 4238: 		return $restored{$qualifierrest};
                   4239: 	    }
1.48      www      4240: # ----------------------------------------------------------------- user.access
                   4241:         } elsif ($space eq 'access') {
1.218     albertel 4242: 	    # FIXME - not supporting calls for a specific user
1.48      www      4243:             return &allowed($qualifier,$rest);
                   4244: # ------------------------------------------ user.preferences, user.environment
                   4245:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 4246: 	    if (($uname eq $env{'user.name'}) &&
                   4247: 		($udom eq $env{'user.domain'})) {
                   4248: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 4249: 	    } else {
1.359     albertel 4250: 		my %returnhash;
                   4251: 		if (!$publicuser) {
                   4252: 		    %returnhash=&userenvironment($udom,$uname,
                   4253: 						 $qualifierrest);
                   4254: 		}
1.218     albertel 4255: 		return $returnhash{$qualifierrest};
                   4256: 	    }
1.48      www      4257: # ----------------------------------------------------------------- user.course
                   4258:         } elsif ($space eq 'course') {
1.218     albertel 4259: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4260:             return $env{join('.',('request.course',$qualifier))};
1.48      www      4261: # ------------------------------------------------------------------- user.role
                   4262:         } elsif ($space eq 'role') {
1.218     albertel 4263: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 4264:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      4265:             if ($qualifier eq 'value') {
                   4266: 		return $role;
                   4267:             } elsif ($qualifier eq 'extent') {
                   4268:                 return $where;
                   4269:             }
                   4270: # ----------------------------------------------------------------- user.domain
                   4271:         } elsif ($space eq 'domain') {
1.218     albertel 4272:             return $udom;
1.48      www      4273: # ------------------------------------------------------------------- user.name
                   4274:         } elsif ($space eq 'name') {
1.218     albertel 4275:             return $uname;
1.48      www      4276: # ---------------------------------------------------- Any other user namespace
1.29      www      4277:         } else {
1.359     albertel 4278: 	    my %reply;
                   4279: 	    if (!$publicuser) {
                   4280: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   4281: 	    }
                   4282: 	    return $reply{$qualifierrest};
1.48      www      4283:         }
1.236     www      4284:     } elsif ($realm eq 'query') {
                   4285: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 4286:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   4287: 						[$spacequalifierrest]);
1.620     albertel 4288: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      4289:    } elsif ($realm eq 'request') {
1.48      www      4290: # ------------------------------------------------------------- request.browser
                   4291:         if ($space eq 'browser') {
1.430     www      4292: 	    if ($qualifier eq 'textremote') {
                   4293: 		if (&mt('textual_remote_display') eq 'on') {
                   4294: 		    return 1;
                   4295: 		} else {
                   4296: 		    return 0;
                   4297: 		}
                   4298: 	    } else {
1.620     albertel 4299: 		return $env{'browser.'.$qualifier};
1.430     www      4300: 	    }
1.57      www      4301: # ------------------------------------------------------------ request.filename
                   4302:         } else {
1.620     albertel 4303:             return $env{'request.'.$spacequalifierrest};
1.29      www      4304:         }
1.28      www      4305:     } elsif ($realm eq 'course') {
1.48      www      4306: # ---------------------------------------------------------- course.description
1.620     albertel 4307:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      4308:     } elsif ($realm eq 'resource') {
1.165     www      4309: 
1.395     albertel 4310: 	my $section;
1.620     albertel 4311: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 4312: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   4313: 	}
1.593     albertel 4314: 	my ($courselevelm,$courselevel);
1.539     albertel 4315: 	if ($symbparm && defined($courseid) && 
1.620     albertel 4316: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      4317: 
1.218     albertel 4318: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      4319: 
1.60      www      4320: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 4321: 	    my $symbp=$symbparm;
1.409     www      4322: 	    my $mapp=(&decode_symb($symbp))[0];
1.218     albertel 4323: 
                   4324: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   4325: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   4326: 
1.620     albertel 4327: 	    if (($env{'user.name'} eq $uname) &&
                   4328: 		($env{'user.domain'} eq $udom)) {
                   4329: 		$section=$env{'request.course.sec'};
1.218     albertel 4330: 	    } else {
1.539     albertel 4331: 		if (! defined($usection)) {
1.551     albertel 4332: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 4333: 		} else {
                   4334: 		    $section = $usection;
                   4335: 		}
1.218     albertel 4336: 	    }
                   4337: 
                   4338: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   4339: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   4340: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   4341: 
1.593     albertel 4342: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 4343: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 4344: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      4345: 
1.60      www      4346: # ----------------------------------------------------------- first, check user
1.624     albertel 4347: 
                   4348: 	    my $userreply=&resdata($uname,$udom,'user',
                   4349: 				       ($courselevelr,$courselevelm,
                   4350: 					$courselevel));
                   4351: 
                   4352: 	    if (defined($userreply)) { return $userreply; }
1.95      www      4353: 
1.594     albertel 4354: # ------------------------------------------------ second, check some of course
1.96      www      4355: 
1.624     albertel 4356: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   4357: 				     $env{'course.'.$courseid.'.domain'},
                   4358: 				     'course',
                   4359: 				     ($seclevelr,$seclevelm,$seclevel,
                   4360: 				      $courselevelr));
1.287     albertel 4361: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      4362: 
1.60      www      4363: # ------------------------------------------------------ third, check map parms
1.218     albertel 4364: 	    my %parmhash=();
                   4365: 	    my $thisparm='';
                   4366: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 4367: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 4368: 		    &GDBM_READER(),0640)) {
1.218     albertel 4369: 		$thisparm=$parmhash{$symbparm};
                   4370: 		untie(%parmhash);
                   4371: 	    }
                   4372: 	    if ($thisparm) { return $thisparm; }
                   4373: 	}
1.594     albertel 4374: # ------------------------------------------ fourth, look in resource metadata
1.71      www      4375: 
1.218     albertel 4376: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 4377: 	my $filename;
                   4378: 	if (!$symbparm) { $symbparm=&symbread(); }
                   4379: 	if ($symbparm) {
1.409     www      4380: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 4381: 	} else {
1.620     albertel 4382: 	    $filename=$env{'request.filename'};
1.282     albertel 4383: 	}
                   4384: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 4385: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 4386: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 4387: 	if (defined($metadata)) { return $metadata; }
1.142     www      4388: 
1.594     albertel 4389: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 4390: 	if ($symbparm && defined($courseid) && 
1.620     albertel 4391: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 4392: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   4393: 				     $env{'course.'.$courseid.'.domain'},
                   4394: 				     'course',
                   4395: 				     ($courselevelm,$courselevel));
1.593     albertel 4396: 	    if (defined($coursereply)) { return $coursereply; }
                   4397: 	}
1.145     www      4398: # ------------------------------------------------------------------ Cascade up
1.218     albertel 4399: 	unless ($space eq '0') {
1.336     albertel 4400: 	    my @parts=split(/_/,$space);
                   4401: 	    my $id=pop(@parts);
                   4402: 	    my $part=join('_',@parts);
                   4403: 	    if ($part eq '') { $part='0'; }
                   4404: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 4405: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 4406: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 4407: 	}
1.395     albertel 4408: 	if ($recurse) { return undef; }
                   4409: 	my $pack_def=&packages_tab_default($filename,$varname);
                   4410: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      4411: 
1.48      www      4412: # ---------------------------------------------------- Any other user namespace
                   4413:     } elsif ($realm eq 'environment') {
                   4414: # ----------------------------------------------------------------- environment
1.620     albertel 4415: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   4416: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 4417: 	} else {
                   4418: 	    my %returnhash=&userenvironment($udom,$uname,
                   4419: 					    $spacequalifierrest);
                   4420: 	    return $returnhash{$spacequalifierrest};
                   4421: 	}
1.28      www      4422:     } elsif ($realm eq 'system') {
1.48      www      4423: # ----------------------------------------------------------------- system.time
                   4424: 	if ($space eq 'time') {
                   4425: 	    return time;
                   4426:         }
1.28      www      4427:     }
1.48      www      4428:     return '';
1.61      www      4429: }
                   4430: 
1.395     albertel 4431: sub packages_tab_default {
                   4432:     my ($uri,$varname)=@_;
                   4433:     my (undef,$part,$name)=split(/\./,$varname);
                   4434:     my $packages=&metadata($uri,'packages');
                   4435:     foreach my $package (split(/,/,$packages)) {
                   4436: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.468     albertel 4437: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   4438: 	    return $packagetab{"$pack_type&$name&default"};
                   4439: 	}
1.585     albertel 4440: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 4441: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   4442: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 4443: 	}
                   4444:     }
                   4445:     return undef;
                   4446: }
                   4447: 
1.334     albertel 4448: sub add_prefix_and_part {
                   4449:     my ($prefix,$part)=@_;
                   4450:     my $keyroot;
                   4451:     if (defined($prefix) && $prefix !~ /^__/) {
                   4452: 	# prefix that has a part already
                   4453: 	$keyroot=$prefix;
                   4454:     } elsif (defined($prefix)) {
                   4455: 	# prefix that is missing a part
                   4456: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   4457:     } else {
                   4458: 	# no prefix at all
                   4459: 	if (defined($part)) { $keyroot='_'.$part; }
                   4460:     }
                   4461:     return $keyroot;
                   4462: }
                   4463: 
1.71      www      4464: # ---------------------------------------------------------------- Get metadata
                   4465: 
1.599     albertel 4466: my %metaentry;
1.71      www      4467: sub metadata {
1.176     www      4468:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      4469:     $uri=&declutter($uri);
1.288     albertel 4470:     # if it is a non metadata possible uri return quickly
1.529     albertel 4471:     if (($uri eq '') || 
                   4472: 	(($uri =~ m|^/*adm/|) && 
                   4473: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 4474:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 4475: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 4476: 	return undef;
1.288     albertel 4477:     }
1.73      www      4478:     my $filename=$uri;
                   4479:     $uri=~s/\.meta$//;
1.172     www      4480: #
                   4481: # Is the metadata already cached?
1.177     www      4482: # Look at timestamp of caching
1.172     www      4483: # Everything is cached by the main uri, libraries are never directly cached
                   4484: #
1.428     albertel 4485:     if (!defined($liburi)) {
1.599     albertel 4486: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 4487: 	if (defined($cached)) { return $result->{':'.$what}; }
                   4488:     }
                   4489:     {
1.172     www      4490: #
                   4491: # Is this a recursive call for a library?
                   4492: #
1.599     albertel 4493: #	if (! exists($metacache{$uri})) {
                   4494: #	    $metacache{$uri}={};
                   4495: #	}
1.171     www      4496:         if ($liburi) {
                   4497: 	    $liburi=&declutter($liburi);
                   4498:             $filename=$liburi;
1.401     bowersj2 4499:         } else {
1.599     albertel 4500: 	    &devalidate_cache_new('meta',$uri);
                   4501: 	    undef(%metaentry);
1.401     bowersj2 4502: 	}
1.140     www      4503:         my %metathesekeys=();
1.73      www      4504:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 4505: 	my $metastring;
1.609     banghart 4506: 	if ($uri !~ m -^(uploaded|editupload)/-) {
1.543     albertel 4507: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 4508: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 4509: 	    $metastring=&getfile($file);
1.489     albertel 4510: 	}
1.208     albertel 4511:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      4512:         my $token;
1.140     www      4513:         undef %metathesekeys;
1.71      www      4514:         while ($token=$parser->get_token) {
1.339     albertel 4515: 	    if ($token->[0] eq 'S') {
                   4516: 		if (defined($token->[2]->{'package'})) {
1.172     www      4517: #
                   4518: # This is a package - get package info
                   4519: #
1.339     albertel 4520: 		    my $package=$token->[2]->{'package'};
                   4521: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   4522: 		    if (defined($token->[2]->{'id'})) { 
                   4523: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   4524: 		    }
1.599     albertel 4525: 		    if ($metaentry{':packages'}) {
                   4526: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 4527: 		    } else {
1.599     albertel 4528: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 4529: 		    }
1.613     albertel 4530: 		    foreach (sort keys %packagetab) {
1.432     albertel 4531: 			my $part=$keyroot;
                   4532: 			$part=~s/^\_//;
                   4533: 			if ($_=~/^\Q$package\E\&/ || 
                   4534: 			    $_=~/^\Q$package\E_0\&/) {
1.339     albertel 4535: 			    my ($pack,$name,$subp)=split(/\&/,$_);
1.395     albertel 4536: 			    # ignore package.tab specified default values
                   4537:                             # here &package_tab_default() will fetch those
                   4538: 			    if ($subp eq 'default') { next; }
1.339     albertel 4539: 			    my $value=$packagetab{$_};
1.432     albertel 4540: 			    my $unikey;
                   4541: 			    if ($pack =~ /_0$/) {
                   4542: 				$unikey='parameter_0_'.$name;
                   4543: 				$part=0;
                   4544: 			    } else {
                   4545: 				$unikey='parameter'.$keyroot.'_'.$name;
                   4546: 			    }
1.339     albertel 4547: 			    if ($subp eq 'display') {
                   4548: 				$value.=' [Part: '.$part.']';
                   4549: 			    }
1.599     albertel 4550: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 4551: 			    $metathesekeys{$unikey}=1;
1.599     albertel 4552: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   4553: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 4554: 			    }
1.599     albertel 4555: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   4556: 				$metaentry{':'.$unikey}=
                   4557: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 4558: 			    }
1.339     albertel 4559: 			}
                   4560: 		    }
                   4561: 		} else {
1.172     www      4562: #
                   4563: # This is not a package - some other kind of start tag
1.339     albertel 4564: #
                   4565: 		    my $entry=$token->[1];
                   4566: 		    my $unikey;
                   4567: 		    if ($entry eq 'import') {
                   4568: 			$unikey='';
                   4569: 		    } else {
                   4570: 			$unikey=$entry;
                   4571: 		    }
                   4572: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   4573: 
                   4574: 		    if (defined($token->[2]->{'id'})) { 
                   4575: 			$unikey.='_'.$token->[2]->{'id'}; 
                   4576: 		    }
1.175     www      4577: 
1.339     albertel 4578: 		    if ($entry eq 'import') {
1.175     www      4579: #
                   4580: # Importing a library here
1.339     albertel 4581: #
                   4582: 			if ($depthcount<20) {
                   4583: 			    my $location=$parser->get_text('/import');
                   4584: 			    my $dir=$filename;
                   4585: 			    $dir=~s|[^/]*$||;
                   4586: 			    $location=&filelocation($dir,$location);
                   4587: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
                   4588: 							       $location,$unikey,
                   4589: 							       $depthcount+1)))) {
1.599     albertel 4590: 				$metaentry{':'.$_}=$metaentry{':'.$_};
1.339     albertel 4591: 				$metathesekeys{$_}=1;
                   4592: 			    }
                   4593: 			}
                   4594: 		    } else { 
                   4595: 			
                   4596: 			if (defined($token->[2]->{'name'})) { 
                   4597: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   4598: 			}
                   4599: 			$metathesekeys{$unikey}=1;
                   4600: 			foreach (@{$token->[3]}) {
1.599     albertel 4601: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
1.339     albertel 4602: 			}
                   4603: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 4604: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 4605: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   4606: 		 # only ws inside the tag, and not in default, so use default
                   4607: 		 # as value
1.599     albertel 4608: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 4609: 			} else {
1.321     albertel 4610: 		  # either something interesting inside the tag or default
                   4611:                   # uninteresting
1.599     albertel 4612: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 4613: 			}
1.172     www      4614: # end of not-a-package not-a-library import
1.339     albertel 4615: 		    }
1.172     www      4616: # end of not-a-package start tag
1.339     albertel 4617: 		}
1.172     www      4618: # the next is the end of "start tag"
1.339     albertel 4619: 	    }
                   4620: 	}
1.483     albertel 4621: 	my ($extension) = ($uri =~ /\.(\w+)$/);
                   4622: 	foreach my $key (sort(keys(%packagetab))) {
                   4623: 	    #&logthis("extsion1 $extension $key !!");
                   4624: 	    #no specific packages #how's our extension
                   4625: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 4626: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 4627: 					 \%metathesekeys);
                   4628: 	}
1.599     albertel 4629: 	if (!exists($metaentry{':packages'})) {
1.483     albertel 4630: 	    foreach my $key (sort(keys(%packagetab))) {
                   4631: 		#no specific packages well let's get default then
                   4632: 		if ($key!~/^default&/) { next; }
1.488     albertel 4633: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 4634: 					     \%metathesekeys);
                   4635: 	    }
                   4636: 	}
1.338     www      4637: # are there custom rights to evaluate
1.599     albertel 4638: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 4639: 
1.338     www      4640:     #
                   4641:     # Importing a rights file here
1.339     albertel 4642:     #
                   4643: 	    unless ($depthcount) {
1.599     albertel 4644: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 4645: 		my $dir=$filename;
                   4646: 		$dir=~s|[^/]*$||;
                   4647: 		$location=&filelocation($dir,$location);
                   4648: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
                   4649: 						   $location,'_rights',
                   4650: 						   $depthcount+1)))) {
1.599     albertel 4651: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
1.339     albertel 4652: 		    $metathesekeys{$_}=1;
                   4653: 		}
                   4654: 	    }
                   4655: 	}
1.599     albertel 4656: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
                   4657: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   4658: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.623     albertel 4659: 	&do_cache_new('meta',$uri,\%metaentry,60*60*24);
1.177     www      4660: # this is the end of "was not already recently cached
1.71      www      4661:     }
1.599     albertel 4662:     return $metaentry{':'.$what};
1.261     albertel 4663: }
                   4664: 
1.488     albertel 4665: sub metadata_create_package_def {
1.483     albertel 4666:     my ($uri,$key,$package,$metathesekeys)=@_;
                   4667:     my ($pack,$name,$subp)=split(/\&/,$key);
                   4668:     if ($subp eq 'default') { next; }
                   4669:     
1.599     albertel 4670:     if (defined($metaentry{':packages'})) {
                   4671: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 4672:     } else {
1.599     albertel 4673: 	$metaentry{':packages'}=$package;
1.483     albertel 4674:     }
                   4675:     my $value=$packagetab{$key};
                   4676:     my $unikey;
                   4677:     $unikey='parameter_0_'.$name;
1.599     albertel 4678:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 4679:     $$metathesekeys{$unikey}=1;
1.599     albertel 4680:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   4681: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 4682:     }
1.599     albertel 4683:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   4684: 	$metaentry{':'.$unikey}=
                   4685: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 4686:     }
                   4687: }
                   4688: 
1.261     albertel 4689: sub metadata_generate_part0 {
                   4690:     my ($metadata,$metacache,$uri) = @_;
                   4691:     my %allnames;
                   4692:     foreach my $metakey (sort keys %$metadata) {
                   4693: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 4694: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   4695: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 4696: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 4697: 	    $allnames{$name}=$part;
                   4698: 	  }
                   4699: 	}
                   4700:     }
                   4701:     foreach my $name (keys(%allnames)) {
                   4702:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 4703:       my $key=":parameter_0_$name";
1.261     albertel 4704:       $$metacache{"$key.part"}='0';
                   4705:       $$metacache{"$key.name"}=$name;
1.428     albertel 4706:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 4707: 					   $allnames{$name}.'_'.$name.
                   4708: 					   '.type'};
1.428     albertel 4709:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 4710: 			     '.display'};
                   4711:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
1.479     albertel 4712:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 4713:       $$metacache{"$key.display"}=$olddis;
                   4714:     }
1.71      www      4715: }
                   4716: 
1.301     www      4717: # ------------------------------------------------- Get the title of a resource
                   4718: 
                   4719: sub gettitle {
                   4720:     my $urlsymb=shift;
                   4721:     my $symb=&symbread($urlsymb);
1.534     albertel 4722:     if ($symb) {
1.620     albertel 4723: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 4724: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 4725: 	if (defined($cached)) { 
                   4726: 	    return $result;
                   4727: 	}
1.534     albertel 4728: 	my ($map,$resid,$url)=&decode_symb($symb);
                   4729: 	my $title='';
                   4730: 	my %bighash;
1.620     albertel 4731: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 4732: 		&GDBM_READER(),0640)) {
                   4733: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   4734: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   4735: 	    untie %bighash;
                   4736: 	}
                   4737: 	$title=~s/\&colon\;/\:/gs;
                   4738: 	if ($title) {
1.599     albertel 4739: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 4740: 	}
                   4741: 	$urlsymb=$url;
                   4742:     }
                   4743:     my $title=&metadata($urlsymb,'title');
                   4744:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   4745:     return $title;
1.301     www      4746: }
1.613     albertel 4747: 
1.614     albertel 4748: sub get_slot {
                   4749:     my ($which,$cnum,$cdom)=@_;
                   4750:     if (!$cnum || !$cdom) {
                   4751: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
1.620     albertel 4752: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   4753: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 4754:     }
                   4755:     my %slotinfo=&get('slots',[$which],$cdom,$cnum);
                   4756:     &Apache::lonhomework::showhash(%slotinfo);
                   4757:     my ($tmp)=keys(%slotinfo);
                   4758:     if ($tmp=~/^error:/) { return (); }
1.616     albertel 4759:     if (ref($slotinfo{$which}) eq 'HASH') {
                   4760: 	return %{$slotinfo{$which}};
                   4761:     }
                   4762:     return $slotinfo{$which};
1.614     albertel 4763: }
1.31      www      4764: # ------------------------------------------------- Update symbolic store links
                   4765: 
                   4766: sub symblist {
                   4767:     my ($mapname,%newhash)=@_;
1.438     www      4768:     $mapname=&deversion(&declutter($mapname));
1.31      www      4769:     my %hash;
1.620     albertel 4770:     if (($env{'request.course.fn'}) && (%newhash)) {
                   4771:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 4772:                       &GDBM_WRCREAT(),0640)) {
1.191     harris41 4773: 	    foreach (keys %newhash) {
1.601     albertel 4774:                 $hash{declutter($_)}=&encode_symb($mapname,$newhash{$_}->[1],
                   4775: 						  $newhash{$_}->[0]);
1.191     harris41 4776:             }
1.31      www      4777:             if (untie(%hash)) {
                   4778: 		return 'ok';
                   4779:             }
                   4780:         }
                   4781:     }
                   4782:     return 'error';
1.212     www      4783: }
                   4784: 
                   4785: # --------------------------------------------------------------- Verify a symb
                   4786: 
                   4787: sub symbverify {
1.510     www      4788:     my ($symb,$thisurl)=@_;
                   4789:     my $thisfn=$thisurl;
                   4790: # wrapper not part of symbs
                   4791:     $thisfn=~s/^\/adm\/wrapper//;
1.439     www      4792:     $thisfn=&declutter($thisfn);
1.215     www      4793: # direct jump to resource in page or to a sequence - will construct own symbs
                   4794:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   4795: # check URL part
1.409     www      4796:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      4797: 
1.431     www      4798:     unless ($url eq $thisfn) { return 0; }
1.213     www      4799: 
1.216     www      4800:     $symb=&symbclean($symb);
1.510     www      4801:     $thisurl=&deversion($thisurl);
1.439     www      4802:     $thisfn=&deversion($thisfn);
1.213     www      4803: 
                   4804:     my %bighash;
                   4805:     my $okay=0;
1.431     www      4806: 
1.620     albertel 4807:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 4808:                             &GDBM_READER(),0640)) {
1.510     www      4809:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      4810:         unless ($ids) { 
1.510     www      4811:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      4812:         }
                   4813:         if ($ids) {
                   4814: # ------------------------------------------------------------------- Has ID(s)
                   4815: 	    foreach (split(/\,/,$ids)) {
                   4816:                my ($mapid,$resid)=split(/\./,$_);
                   4817:                if (
                   4818:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   4819:    eq $symb) { 
1.620     albertel 4820: 		   if (($env{'request.role.adv'}) ||
                   4821: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 4822: 		       $okay=1; 
                   4823: 		   }
                   4824: 	       }
1.216     www      4825: 	   }
                   4826:         }
1.213     www      4827: 	untie(%bighash);
                   4828:     }
                   4829:     return $okay;
1.31      www      4830: }
                   4831: 
1.210     www      4832: # --------------------------------------------------------------- Clean-up symb
                   4833: 
                   4834: sub symbclean {
                   4835:     my $symb=shift;
1.568     albertel 4836:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      4837: # remove version from map
                   4838:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      4839: 
1.210     www      4840: # remove version from URL
                   4841:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      4842: 
1.507     www      4843: # remove wrapper
                   4844: 
1.510     www      4845:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.210     www      4846:     return $symb;
1.409     www      4847: }
                   4848: 
                   4849: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 4850: 
                   4851: sub encode_symb {
                   4852:     my ($map,$resid,$url)=@_;
                   4853:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   4854: }
1.409     www      4855: 
                   4856: sub decode_symb {
1.568     albertel 4857:     my $symb=shift;
                   4858:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   4859:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      4860:     return (&fixversion($map),$resid,&fixversion($url));
                   4861: }
                   4862: 
                   4863: sub fixversion {
                   4864:     my $fn=shift;
1.609     banghart 4865:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      4866:     my %bighash;
                   4867:     my $uri=&clutter($fn);
1.620     albertel 4868:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      4869: # is this cached?
1.599     albertel 4870:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      4871:     if (defined($cached)) { return $result; }
                   4872: # unfortunately not cached, or expired
1.620     albertel 4873:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      4874: 	    &GDBM_READER(),0640)) {
                   4875:  	if ($bighash{'version_'.$uri}) {
                   4876:  	    my $version=$bighash{'version_'.$uri};
1.444     www      4877:  	    unless (($version eq 'mostrecent') || 
                   4878: 		    ($version==&getversion($uri))) {
1.440     www      4879:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   4880:  	    }
                   4881:  	}
                   4882:  	untie %bighash;
1.413     www      4883:     }
1.599     albertel 4884:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      4885: }
                   4886: 
                   4887: sub deversion {
                   4888:     my $url=shift;
                   4889:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   4890:     return $url;
1.210     www      4891: }
                   4892: 
1.31      www      4893: # ------------------------------------------------------ Return symb list entry
                   4894: 
                   4895: sub symbread {
1.249     www      4896:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 4897:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 4898:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      4899: # no filename provided? try from environment
1.44      www      4900:     unless ($thisfn) {
1.620     albertel 4901:         if ($env{'request.symb'}) {
                   4902: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 4903: 	}
1.620     albertel 4904: 	$thisfn=$env{'request.filename'};
1.44      www      4905:     }
1.569     albertel 4906:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      4907: # is that filename actually a symb? Verify, clean, and return
                   4908:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 4909: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 4910: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 4911: 	}
1.242     www      4912:     }
1.44      www      4913:     $thisfn=declutter($thisfn);
1.31      www      4914:     my %hash;
1.37      www      4915:     my %bighash;
                   4916:     my $syval='';
1.620     albertel 4917:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  4918:         my $targetfn = $thisfn;
1.609     banghart 4919:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  4920:             $targetfn = 'adm/wrapper/'.$thisfn;
                   4921:         }
1.620     albertel 4922:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 4923:                       &GDBM_READER(),0640)) {
1.481     raeburn  4924: 	    $syval=$hash{$targetfn};
1.37      www      4925:             untie(%hash);
                   4926:         }
                   4927: # ---------------------------------------------------------- There was an entry
                   4928:         if ($syval) {
1.601     albertel 4929: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 4930: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 4931: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 4932: 		    #return $env{$cache_str}='';
1.601     albertel 4933: 		#}    
                   4934: 		#$syval.=$1;
                   4935: 	    #}
1.37      www      4936:         } else {
                   4937: # ------------------------------------------------------- Was not in symb table
1.620     albertel 4938:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 4939:                             &GDBM_READER(),0640)) {
1.37      www      4940: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      4941:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      4942:               unless ($ids) { 
                   4943:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      4944:               }
                   4945:               unless ($ids) {
                   4946: # alias?
                   4947: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      4948:               }
1.37      www      4949:               if ($ids) {
                   4950: # ------------------------------------------------------------------- Has ID(s)
                   4951:                  my @possibilities=split(/\,/,$ids);
1.39      www      4952:                  if ($#possibilities==0) {
                   4953: # ----------------------------------------------- There is only one possibility
1.37      www      4954: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626   ! albertel 4955: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
        !          4956: 						    $resid,$thisfn);
1.249     www      4957:                  } elsif (!$donotrecurse) {
1.39      www      4958: # ------------------------------------------ There is more than one possibility
                   4959:                      my $realpossible=0;
1.191     harris41 4960:                      foreach (@possibilities) {
1.39      www      4961: 			 my $file=$bighash{'src_'.$_};
                   4962:                          if (&allowed('bre',$file)) {
                   4963:          		    my ($mapid,$resid)=split(/\./,$_);
                   4964:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   4965: 				$realpossible++;
1.626   ! albertel 4966:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
        !          4967: 						    $resid,$thisfn);
1.39      www      4968:                             }
                   4969: 			 }
1.191     harris41 4970:                      }
1.39      www      4971: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      4972:                  } else {
                   4973:                      $syval='';
1.37      www      4974:                  }
                   4975: 	      }
                   4976:               untie(%bighash)
1.481     raeburn  4977:            }
1.31      www      4978:         }
1.62      www      4979:         if ($syval) {
1.620     albertel 4980: 	    return $env{$cache_str}=$syval;
1.62      www      4981:         }
1.31      www      4982:     }
1.44      www      4983:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 4984:     return $env{$cache_str}='';
1.31      www      4985: }
                   4986: 
                   4987: # ---------------------------------------------------------- Return random seed
                   4988: 
1.32      www      4989: sub numval {
                   4990:     my $txt=shift;
                   4991:     $txt=~tr/A-J/0-9/;
                   4992:     $txt=~tr/a-j/0-9/;
                   4993:     $txt=~tr/K-T/0-9/;
                   4994:     $txt=~tr/k-t/0-9/;
                   4995:     $txt=~tr/U-Z/0-5/;
                   4996:     $txt=~tr/u-z/0-5/;
                   4997:     $txt=~s/\D//g;
1.564     albertel 4998:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      4999:     return int($txt);
1.368     albertel 5000: }
                   5001: 
1.484     albertel 5002: sub numval2 {
                   5003:     my $txt=shift;
                   5004:     $txt=~tr/A-J/0-9/;
                   5005:     $txt=~tr/a-j/0-9/;
                   5006:     $txt=~tr/K-T/0-9/;
                   5007:     $txt=~tr/k-t/0-9/;
                   5008:     $txt=~tr/U-Z/0-5/;
                   5009:     $txt=~tr/u-z/0-5/;
                   5010:     $txt=~s/\D//g;
                   5011:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5012:     my $total;
                   5013:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 5014:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 5015:     return int($total);
                   5016: }
                   5017: 
1.575     albertel 5018: sub numval3 {
                   5019:     use integer;
                   5020:     my $txt=shift;
                   5021:     $txt=~tr/A-J/0-9/;
                   5022:     $txt=~tr/a-j/0-9/;
                   5023:     $txt=~tr/K-T/0-9/;
                   5024:     $txt=~tr/k-t/0-9/;
                   5025:     $txt=~tr/U-Z/0-5/;
                   5026:     $txt=~tr/u-z/0-5/;
                   5027:     $txt=~s/\D//g;
                   5028:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   5029:     my $total;
                   5030:     foreach my $val (@txts) { $total+=$val; }
                   5031:     if ($_64bit) { $total=(($total<<32)>>32); }
                   5032:     return $total;
                   5033: }
                   5034: 
1.368     albertel 5035: sub latest_rnd_algorithm_id {
1.575     albertel 5036:     return '64bit4';
1.366     albertel 5037: }
1.32      www      5038: 
1.503     albertel 5039: sub get_rand_alg {
                   5040:     my ($courseid)=@_;
                   5041:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
                   5042:     if ($courseid) {
1.620     albertel 5043: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 5044:     }
                   5045:     return &latest_rnd_algorithm_id();
                   5046: }
                   5047: 
1.562     albertel 5048: sub validCODE {
                   5049:     my ($CODE)=@_;
                   5050:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   5051:     return 0;
                   5052: }
                   5053: 
1.491     albertel 5054: sub getCODE {
1.620     albertel 5055:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 5056:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   5057: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   5058: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 5059: 	return $Apache::lonhomework::history{'resource.CODE'};
                   5060:     }
                   5061:     return undef;
                   5062: }
                   5063: 
1.31      www      5064: sub rndseed {
1.155     albertel 5065:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 5066: 
                   5067:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155     albertel 5068:     if (!$symb) {
1.366     albertel 5069: 	unless ($symb=$wsymb) { return time; }
                   5070:     }
                   5071:     if (!$courseid) { $courseid=$wcourseid; }
                   5072:     if (!$domain) { $domain=$wdomain; }
                   5073:     if (!$username) { $username=$wusername }
1.503     albertel 5074:     my $which=&get_rand_alg();
1.491     albertel 5075:     if (defined(&getCODE())) {
1.575     albertel 5076: 	if ($which eq '64bit4') {
                   5077: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   5078: 	} else {
                   5079: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   5080: 	}
                   5081:     } elsif ($which eq '64bit4') {
                   5082: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 5083:     } elsif ($which eq '64bit3') {
                   5084: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 5085:     } elsif ($which eq '64bit2') {
                   5086: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 5087:     } elsif ($which eq '64bit') {
                   5088: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   5089:     }
                   5090:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   5091: }
                   5092: 
                   5093: sub rndseed_32bit {
                   5094:     my ($symb,$courseid,$domain,$username)=@_;
                   5095:     {
                   5096: 	use integer;
                   5097: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   5098: 	my $symbseed=numval($symb) << 22;
                   5099: 	my $namechck=unpack("%32C*",$username) << 17;
                   5100: 	my $nameseed=numval($username) << 12;
                   5101: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   5102: 	my $courseseed=unpack("%32C*",$courseid);
                   5103: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
                   5104: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5105: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5106: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 5107: 	return $num;
                   5108:     }
                   5109: }
                   5110: 
                   5111: sub rndseed_64bit {
                   5112:     my ($symb,$courseid,$domain,$username)=@_;
                   5113:     {
                   5114: 	use integer;
                   5115: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   5116: 	my $symbseed=numval($symb) << 10;
                   5117: 	my $namechck=unpack("%32S*",$username);
                   5118: 	
                   5119: 	my $nameseed=numval($username) << 21;
                   5120: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   5121: 	my $courseseed=unpack("%32S*",$courseid);
                   5122: 	
                   5123: 	my $num1=$symbchck+$symbseed+$namechck;
                   5124: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5125: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5126: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
1.564     albertel 5127: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5128: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 5129: 	return "$num1,$num2";
1.155     albertel 5130:     }
1.366     albertel 5131: }
                   5132: 
1.443     albertel 5133: sub rndseed_64bit2 {
                   5134:     my ($symb,$courseid,$domain,$username)=@_;
                   5135:     {
                   5136: 	use integer;
                   5137: 	# strings need to be an even # of cahracters long, it it is odd the
                   5138:         # last characters gets thrown away
                   5139: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5140: 	my $symbseed=numval($symb) << 10;
                   5141: 	my $namechck=unpack("%32S*",$username.' ');
                   5142: 	
                   5143: 	my $nameseed=numval($username) << 21;
1.501     albertel 5144: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5145: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5146: 	
                   5147: 	my $num1=$symbchck+$symbseed+$namechck;
                   5148: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5149: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5150: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
                   5151: 	return "$num1,$num2";
                   5152:     }
                   5153: }
                   5154: 
                   5155: sub rndseed_64bit3 {
                   5156:     my ($symb,$courseid,$domain,$username)=@_;
                   5157:     {
                   5158: 	use integer;
                   5159: 	# strings need to be an even # of cahracters long, it it is odd the
                   5160:         # last characters gets thrown away
                   5161: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5162: 	my $symbseed=numval2($symb) << 10;
                   5163: 	my $namechck=unpack("%32S*",$username.' ');
                   5164: 	
                   5165: 	my $nameseed=numval2($username) << 21;
1.443     albertel 5166: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5167: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5168: 	
                   5169: 	my $num1=$symbchck+$symbseed+$namechck;
                   5170: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5171: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564     albertel 5172: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5173: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5174: 	
1.503     albertel 5175: 	return "$num1:$num2";
1.443     albertel 5176:     }
                   5177: }
                   5178: 
1.575     albertel 5179: sub rndseed_64bit4 {
                   5180:     my ($symb,$courseid,$domain,$username)=@_;
                   5181:     {
                   5182: 	use integer;
                   5183: 	# strings need to be an even # of cahracters long, it it is odd the
                   5184:         # last characters gets thrown away
                   5185: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   5186: 	my $symbseed=numval3($symb) << 10;
                   5187: 	my $namechck=unpack("%32S*",$username.' ');
                   5188: 	
                   5189: 	my $nameseed=numval3($username) << 21;
                   5190: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   5191: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5192: 	
                   5193: 	my $num1=$symbchck+$symbseed+$namechck;
                   5194: 	my $num2=$nameseed+$domainseed+$courseseed;
                   5195: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   5196: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
                   5197: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   5198: 	
                   5199: 	return "$num1:$num2";
                   5200:     }
                   5201: }
                   5202: 
1.366     albertel 5203: sub rndseed_CODE_64bit {
                   5204:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 5205:     {
1.366     albertel 5206: 	use integer;
1.443     albertel 5207: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 5208: 	my $symbseed=numval2($symb);
1.491     albertel 5209: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5210: 	my $CODEseed=numval(&getCODE());
1.443     albertel 5211: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 5212: 	my $num1=$symbseed+$CODEchck;
                   5213: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5214: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366     albertel 5215: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564     albertel 5216: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5217: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 5218: 	return "$num1:$num2";
1.366     albertel 5219:     }
                   5220: }
                   5221: 
1.575     albertel 5222: sub rndseed_CODE_64bit4 {
                   5223:     my ($symb,$courseid,$domain,$username)=@_;
                   5224:     {
                   5225: 	use integer;
                   5226: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   5227: 	my $symbseed=numval3($symb);
                   5228: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   5229: 	my $CODEseed=numval3(&getCODE());
                   5230: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   5231: 	my $num1=$symbseed+$CODEchck;
                   5232: 	my $num2=$CODEseed+$courseseed+$symbchck;
                   5233: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   5234: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
                   5235: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   5236: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   5237: 	return "$num1:$num2";
                   5238:     }
                   5239: }
                   5240: 
1.366     albertel 5241: sub setup_random_from_rndseed {
                   5242:     my ($rndseed)=@_;
1.503     albertel 5243:     if ($rndseed =~/([,:])/) {
                   5244: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 5245: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   5246:     } else {
                   5247: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 5248:     }
1.36      albertel 5249: }
                   5250: 
1.474     albertel 5251: sub latest_receipt_algorithm_id {
                   5252:     return 'receipt2';
                   5253: }
                   5254: 
1.480     www      5255: sub recunique {
                   5256:     my $fucourseid=shift;
                   5257:     my $unique;
1.620     albertel 5258:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5259: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      5260:     } else {
                   5261: 	$unique=$perlvar{'lonReceipt'};
                   5262:     }
                   5263:     return unpack("%32C*",$unique);
                   5264: }
                   5265: 
                   5266: sub recprefix {
                   5267:     my $fucourseid=shift;
                   5268:     my $prefix;
1.620     albertel 5269:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   5270: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      5271:     } else {
                   5272: 	$prefix=$perlvar{'lonHostID'};
                   5273:     }
                   5274:     return unpack("%32C*",$prefix);
                   5275: }
                   5276: 
1.76      www      5277: sub ireceipt {
1.474     albertel 5278:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      5279:     my $cuname=unpack("%32C*",$funame);
                   5280:     my $cudom=unpack("%32C*",$fudom);
                   5281:     my $cucourseid=unpack("%32C*",$fucourseid);
                   5282:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      5283:     my $cunique=&recunique($fucourseid);
1.474     albertel 5284:     my $cpart=unpack("%32S*",$part);
1.480     www      5285:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 5286:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   5287: 	$env{'request.state'} eq 'construct') {
1.474     albertel 5288: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
                   5289: 			       " and ".($cpart%$cudom));
                   5290: 			       
                   5291: 	$return.= ($cunique%$cuname+
                   5292: 		   $cunique%$cudom+
                   5293: 		   $cusymb%$cuname+
                   5294: 		   $cusymb%$cudom+
                   5295: 		   $cucourseid%$cuname+
                   5296: 		   $cucourseid%$cudom+
                   5297: 		   $cpart%$cuname+
                   5298: 		   $cpart%$cudom);
                   5299:     } else {
                   5300: 	$return.= ($cunique%$cuname+
                   5301: 		   $cunique%$cudom+
                   5302: 		   $cusymb%$cuname+
                   5303: 		   $cusymb%$cudom+
                   5304: 		   $cucourseid%$cuname+
                   5305: 		   $cucourseid%$cudom);
                   5306:     }
                   5307:     return $return;
1.76      www      5308: }
                   5309: 
                   5310: sub receipt {
1.474     albertel 5311:     my ($part)=@_;
                   5312:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
                   5313:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      5314: }
1.260     ng       5315: 
1.36      albertel 5316: # ------------------------------------------------------------ Serves up a file
1.472     albertel 5317: # returns either the contents of the file or 
                   5318: # -1 if the file doesn't exist
1.481     raeburn  5319: #
                   5320: # if the target is a file that was uploaded via DOCS, 
                   5321: # a check will be made to see if a current copy exists on the local server,
                   5322: # if it does this will be served, otherwise a copy will be retrieved from
                   5323: # the home server for the course and stored in /home/httpd/html/userfiles on
                   5324: # the local server.   
1.472     albertel 5325: 
1.36      albertel 5326: sub getfile {
1.538     albertel 5327:     my ($file) = @_;
1.609     banghart 5328:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 5329:     &repcopy($file);
                   5330:     return &readfile($file);
                   5331: }
                   5332: 
                   5333: sub repcopy_userfile {
                   5334:     my ($file)=@_;
1.609     banghart 5335:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 5336:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 5337:     my ($cdom,$cnum,$filename) = 
                   5338: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   5339:     my ($info,$rtncode);
                   5340:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   5341:     if (-e "$file") {
                   5342: 	my @fileinfo = stat($file);
                   5343: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5344: 	if ($lwpresp ne 'ok') {
                   5345: 	    if ($rtncode eq '404') {
1.538     albertel 5346: 		unlink($file);
1.482     albertel 5347: 	    }
1.517     albertel 5348: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 5349: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5350: 	    #my $response=$ua->request($request);
                   5351: 	    #if ($response->is_success()) {
                   5352: 	#	return $response->content;
                   5353: 	#    } else {
                   5354: 	#	return -1;
                   5355: 	#    }
1.482     albertel 5356: 	    return -1;
                   5357: 	}
                   5358: 	if ($info < $fileinfo[9]) {
1.607     raeburn  5359: 	    return 'ok';
1.482     albertel 5360: 	}
                   5361: 	$info = '';
1.538     albertel 5362: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5363: 	if ($lwpresp ne 'ok') {
                   5364: 	    return -1;
                   5365: 	}
                   5366:     } else {
1.538     albertel 5367: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 5368: 	if ($lwpresp ne 'ok') {
1.517     albertel 5369: 	    my $ua=new LWP::UserAgent;
1.538     albertel 5370: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 5371: 	    my $response=$ua->request($request);
                   5372: 	    if ($response->is_success()) {
1.538     albertel 5373: 		$info=$response->content;
1.517     albertel 5374: 	    } else {
                   5375: 		return -1;
                   5376: 	    }
1.482     albertel 5377: 	}
                   5378: 	my @parts = ($cdom,$cnum); 
                   5379: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   5380: 	    push @parts, split(/\//,$1);
1.518     albertel 5381: 	}
1.538     albertel 5382: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 5383: 	foreach my $part (@parts) {
                   5384: 	    $path .= '/'.$part;
                   5385: 	    if (!-e $path) {
                   5386: 		mkdir($path,0770);
                   5387: 	    }
                   5388: 	}
                   5389:     }
1.538     albertel 5390:     open(FILE,">$file");
1.482     albertel 5391:     print FILE $info;
                   5392:     close(FILE);
1.607     raeburn  5393:     return 'ok';
1.481     raeburn  5394: }
                   5395: 
1.517     albertel 5396: sub tokenwrapper {
                   5397:     my $uri=shift;
1.552     albertel 5398:     $uri=~s|^http\://([^/]+)||;
                   5399:     $uri=~s|^/||;
1.620     albertel 5400:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 5401:     my $token=$1;
1.552     albertel 5402:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   5403:     if ($udom && $uname && $file) {
                   5404: 	$file=~s|(\?\.*)*$||;
1.620     albertel 5405:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 5406:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 5407:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   5408:                                '&tokenissued='.$perlvar{'lonHostID'};
                   5409:     } else {
                   5410:         return '/adm/notfound.html';
                   5411:     }
                   5412: }
                   5413: 
1.481     raeburn  5414: sub getuploaded {
                   5415:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   5416:     $uri=~s/^\///;
                   5417:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   5418:     my $ua=new LWP::UserAgent;
                   5419:     my $request=new HTTP::Request($reqtype,$uri);
                   5420:     my $response=$ua->request($request);
                   5421:     $$rtncode = $response->code;
1.482     albertel 5422:     if (! $response->is_success()) {
                   5423: 	return 'failed';
                   5424:     }      
                   5425:     if ($reqtype eq 'HEAD') {
1.486     www      5426: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 5427:     } elsif ($reqtype eq 'GET') {
                   5428: 	$$info = $response->content;
1.472     albertel 5429:     }
1.482     albertel 5430:     return 'ok';
1.36      albertel 5431: }
                   5432: 
1.481     raeburn  5433: sub readfile {
                   5434:     my $file = shift;
                   5435:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   5436:     my $fh;
                   5437:     open($fh,"<$file");
                   5438:     my $a='';
                   5439:     while (<$fh>) { $a .=$_; }
                   5440:     return $a;
                   5441: }
                   5442: 
1.36      albertel 5443: sub filelocation {
1.590     banghart 5444:     my ($dir,$file) = @_;
                   5445:     my $location;
                   5446:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
                   5447:     if ($file=~m:^/~:) { # is a contruction space reference
                   5448:         $location = $file;
                   5449:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.609     banghart 5450:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 5451:         my ($udom,$uname,$filename)=
1.609     banghart 5452:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 5453:         my $home=&homeserver($uname,$udom);
                   5454:         my $is_me=0;
                   5455:         my @ids=&current_machine_ids();
                   5456:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   5457:         if ($is_me) {
                   5458:   	    $location=&Apache::loncommon::propath($udom,$uname).
                   5459:   	      '/userfiles/'.$filename;
                   5460:         } else {
                   5461:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   5462:   	      $udom.'/'.$uname.'/'.$filename;
                   5463:         }
                   5464:     } else {
                   5465:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   5466:         $file=~s:^/res/:/:;
                   5467:         if ( !( $file =~ m:^/:) ) {
                   5468:             $location = $dir. '/'.$file;
                   5469:         } else {
                   5470:             $location = '/home/httpd/html/res'.$file;
                   5471:         }
1.59      albertel 5472:     }
1.590     banghart 5473:     $location=~s://+:/:g; # remove duplicate /
                   5474:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   5475:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   5476:     return $location;
1.46      www      5477: }
1.36      albertel 5478: 
1.46      www      5479: sub hreflocation {
                   5480:     my ($dir,$file)=@_;
1.460     albertel 5481:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
                   5482: 	my $finalpath=filelocation($dir,$file);
                   5483: 	$finalpath=~s-^/home/httpd/html--;
1.462     albertel 5484: 	$finalpath=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460     albertel 5485: 	return $finalpath;
                   5486:     } elsif ($file=~m-^/home-) {
                   5487: 	$file=~s-^/home/httpd/html--;
1.462     albertel 5488: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.460     albertel 5489: 	return $file;
1.46      www      5490:     }
1.462     albertel 5491:     return $file;
1.465     albertel 5492: }
                   5493: 
                   5494: sub current_machine_domains {
                   5495:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   5496:     my @domains;
                   5497:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  5498: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 5499: 	if ($hostname eq $name) {
                   5500: 	    push(@domains,$hostdom{$id});
                   5501: 	}
                   5502:     }
                   5503:     return @domains;
                   5504: }
                   5505: 
                   5506: sub current_machine_ids {
                   5507:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   5508:     my @ids;
                   5509:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  5510: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 5511: 	if ($hostname eq $name) {
                   5512: 	    push(@ids,$id);
                   5513: 	}
                   5514:     }
                   5515:     return @ids;
1.31      www      5516: }
                   5517: 
                   5518: # ------------------------------------------------------------- Declutters URLs
                   5519: 
                   5520: sub declutter {
                   5521:     my $thisfn=shift;
1.569     albertel 5522:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 5523:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      5524:     $thisfn=~s/^\///;
                   5525:     $thisfn=~s/^res\///;
1.235     www      5526:     $thisfn=~s/\?.+$//;
1.268     www      5527:     return $thisfn;
                   5528: }
                   5529: 
                   5530: # ------------------------------------------------------------- Clutter up URLs
                   5531: 
                   5532: sub clutter {
                   5533:     my $thisfn='/'.&declutter(shift);
1.609     banghart 5534:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      5535:        $thisfn='/res'.$thisfn; 
                   5536:     }
1.31      www      5537:     return $thisfn;
1.12      www      5538: }
                   5539: 
1.557     albertel 5540: sub freeze_escape {
                   5541:     my ($value)=@_;
                   5542:     if (ref($value)) {
                   5543: 	$value=&nfreeze($value);
                   5544: 	return '__FROZEN__'.&escape($value);
                   5545:     }
                   5546:     return &escape($value);
                   5547: }
                   5548: 
1.12      www      5549: # -------------------------------------------------------- Escape Special Chars
                   5550: 
                   5551: sub escape {
                   5552:     my $str=shift;
                   5553:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                   5554:     return $str;
                   5555: }
                   5556: 
                   5557: # ----------------------------------------------------- Un-Escape Special Chars
                   5558: 
                   5559: sub unescape {
                   5560:     my $str=shift;
                   5561:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                   5562:     return $str;
                   5563: }
1.11      www      5564: 
1.557     albertel 5565: sub thaw_unescape {
                   5566:     my ($value)=@_;
                   5567:     if ($value =~ /^__FROZEN__/) {
                   5568: 	substr($value,0,10,undef);
                   5569: 	$value=&unescape($value);
                   5570: 	return &thaw($value);
                   5571:     }
                   5572:     return &unescape($value);
                   5573: }
                   5574: 
1.415     albertel 5575: sub mod_perl_version {
1.580     albertel 5576:     return 1;
1.415     albertel 5577:     if (defined($perlvar{'MODPERL2'})) {
                   5578: 	return 2;
                   5579:     }
1.436     albertel 5580: }
                   5581: 
                   5582: sub correct_line_ends {
                   5583:     my ($result)=@_;
                   5584:     $$result =~s/\r\n/\n/mg;
                   5585:     $$result =~s/\r/\n/mg;
1.415     albertel 5586: }
1.1       albertel 5587: # ================================================================ Main Program
                   5588: 
1.184     www      5589: sub goodbye {
1.204     albertel 5590:    &logthis("Starting Shut down");
1.443     albertel 5591: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 5592:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 5593: #converted
1.599     albertel 5594: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   5595:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   5596: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   5597: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 5598: #1.1 only
1.599     albertel 5599: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   5600: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   5601: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   5602: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   5603:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   5604:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   5605:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      5606:    &flushcourselogs();
                   5607:    &logthis("Shutting down");
1.362     albertel 5608:    return DONE;
1.184     www      5609: }
                   5610: 
1.179     www      5611: BEGIN {
1.228     harris41 5612: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      5613:     unless ($readit) {
1.217     harris41 5614: {
1.581     matthew  5615:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
1.448     albertel 5616:     open(my $config,"</etc/httpd/conf/loncapa.conf");
1.217     harris41 5617: 
                   5618:     while (my $configline=<$config>) {
1.484     albertel 5619:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
1.1       albertel 5620: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
1.8       www      5621:            chomp($varvalue);
1.1       albertel 5622:            $perlvar{$varname}=$varvalue;
                   5623:         }
                   5624:     }
1.448     albertel 5625:     close($config);
1.1       albertel 5626: }
1.227     harris41 5627: {
1.448     albertel 5628:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
1.227     harris41 5629: 
                   5630:     while (my $configline=<$config>) {
                   5631:         if ($configline =~ /^[^\#]*PerlSetVar/) {
                   5632: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
                   5633:            chomp($varvalue);
                   5634:            $perlvar{$varname}=$varvalue;
                   5635:         }
                   5636:     }
1.448     albertel 5637:     close($config);
1.227     harris41 5638: }
1.1       albertel 5639: 
1.327     albertel 5640: # ------------------------------------------------------------ Read domain file
                   5641: {
                   5642:     %domaindescription = ();
                   5643:     %domain_auth_def = ();
                   5644:     %domain_auth_arg_def = ();
1.448     albertel 5645:     my $fh;
                   5646:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 5647:        while (<$fh>) {
1.390     matthew  5648:            next if (/^(\#|\s*$)/);
                   5649: #           next if /^\#/;
1.327     albertel 5650:            chomp;
1.403     www      5651:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
                   5652: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
                   5653: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 5654:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      5655: 	   $domaindescription{$domain}=$domain_description;
                   5656: 	   $domain_lang_def{$domain}=$def_lang;
                   5657: 	   $domain_city{$domain}=$city;
                   5658: 	   $domain_longi{$domain}=$longi;
                   5659: 	   $domain_lati{$domain}=$lati;
                   5660: 
1.448     albertel 5661:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 5662: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 5663: 	}
1.327     albertel 5664:     }
1.448     albertel 5665:     close ($fh);
1.327     albertel 5666: }
                   5667: 
                   5668: 
1.1       albertel 5669: # ------------------------------------------------------------- Read hosts file
                   5670: {
1.448     albertel 5671:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 5672: 
                   5673:     while (my $configline=<$config>) {
1.303     matthew  5674:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      5675:        chomp($configline);
1.595     albertel 5676:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 5677:        $name=~s/\s//g;
1.595     albertel 5678:        if ($id && $domain && $role && $name) {
1.252     albertel 5679: 	 $hostname{$id}=$name;
                   5680: 	 $hostdom{$id}=$domain;
                   5681: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      5682:        }
1.1       albertel 5683:     }
1.448     albertel 5684:     close($config);
1.619     albertel 5685:     # FIXME: dev server don't want this, production servers _do_ want this
                   5686:     #&get_iphost();
1.1       albertel 5687: }
                   5688: 
1.598     albertel 5689: sub get_iphost {
                   5690:     if (%iphost) { return %iphost; }
                   5691:     foreach my $id (keys(%hostname)) {
                   5692: 	my $name=$hostname{$id};
                   5693: 	my $ip = gethostbyname($name);
                   5694: 	if (!$ip || length($ip) ne 4) {
                   5695: 	    &logthis("Skipping host $id name $name no IP found\n");
                   5696: 	    next;
                   5697: 	}
                   5698: 	$ip=inet_ntoa($ip);
                   5699: 	push(@{$iphost{$ip}},$id);
                   5700:     }
                   5701:     return %iphost;
                   5702: }
                   5703: 
1.1       albertel 5704: # ------------------------------------------------------ Read spare server file
                   5705: {
1.448     albertel 5706:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 5707: 
                   5708:     while (my $configline=<$config>) {
                   5709:        chomp($configline);
1.284     matthew  5710:        if ($configline) {
1.1       albertel 5711:           $spareid{$configline}=1;
                   5712:        }
                   5713:     }
1.448     albertel 5714:     close($config);
1.1       albertel 5715: }
1.11      www      5716: # ------------------------------------------------------------ Read permissions
                   5717: {
1.448     albertel 5718:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      5719: 
                   5720:     while (my $configline=<$config>) {
1.448     albertel 5721: 	chomp($configline);
                   5722: 	if ($configline) {
                   5723: 	    my ($role,$perm)=split(/ /,$configline);
                   5724: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   5725: 	}
1.11      www      5726:     }
1.448     albertel 5727:     close($config);
1.11      www      5728: }
                   5729: 
                   5730: # -------------------------------------------- Read plain texts for permissions
                   5731: {
1.448     albertel 5732:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      5733: 
                   5734:     while (my $configline=<$config>) {
1.448     albertel 5735: 	chomp($configline);
                   5736: 	if ($configline) {
                   5737: 	    my ($short,$plain)=split(/:/,$configline);
                   5738: 	    if ($plain ne '') { $prp{$short}=$plain; }
                   5739: 	}
1.135     www      5740:     }
1.448     albertel 5741:     close($config);
1.135     www      5742: }
                   5743: 
                   5744: # ---------------------------------------------------------- Read package table
                   5745: {
1.448     albertel 5746:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      5747: 
                   5748:     while (my $configline=<$config>) {
1.483     albertel 5749: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 5750: 	chomp($configline);
                   5751: 	my ($short,$plain)=split(/:/,$configline);
                   5752: 	my ($pack,$name)=split(/\&/,$short);
                   5753: 	if ($plain ne '') {
                   5754: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   5755: 	    $packagetab{$short}=$plain; 
                   5756: 	}
1.11      www      5757:     }
1.448     albertel 5758:     close($config);
1.329     matthew  5759: }
                   5760: 
                   5761: # ------------- set up temporary directory
                   5762: {
                   5763:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   5764: 
1.11      www      5765: }
                   5766: 
1.599     albertel 5767: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185     www      5768: 
1.281     www      5769: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      5770: $dumpcount=0;
1.22      www      5771: 
1.163     harris41 5772: &logtouch();
1.12      www      5773: &logthis('<font color=yellow>INFO: Read configuration</font>');
1.195     www      5774: $readit=1;
1.564     albertel 5775:     {
                   5776: 	use integer;
                   5777: 	my $test=(2**32)+1;
1.568     albertel 5778: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 5779: 	&logthis(" Detected 64bit platform ($_64bit)");
                   5780:     }
1.195     www      5781: }
1.1       albertel 5782: }
1.179     www      5783: 
1.1       albertel 5784: 1;
1.191     harris41 5785: __END__
                   5786: 
1.243     albertel 5787: =pod
                   5788: 
1.191     harris41 5789: =head1 NAME
                   5790: 
1.243     albertel 5791: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 5792: 
                   5793: =head1 SYNOPSIS
                   5794: 
1.243     albertel 5795: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 5796: 
                   5797:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   5798: 
1.243     albertel 5799: Common parameters:
                   5800: 
                   5801: =over 4
                   5802: 
                   5803: =item *
                   5804: 
                   5805: $uname : an internal username (if $cname expecting a course Id specifically)
                   5806: 
                   5807: =item *
                   5808: 
                   5809: $udom : a domain (if $cdom expecting a course's domain specifically)
                   5810: 
                   5811: =item *
                   5812: 
                   5813: $symb : a resource instance identifier
                   5814: 
                   5815: =item *
                   5816: 
                   5817: $namespace : the name of a .db file that contains the data needed or
                   5818: being set.
                   5819: 
                   5820: =back
                   5821: 
1.394     bowersj2 5822: =head1 OVERVIEW
1.191     harris41 5823: 
1.394     bowersj2 5824: lonnet provides subroutines which interact with the
                   5825: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   5826: about classes, users, and resources.
1.243     albertel 5827: 
                   5828: For many of these objects you can also use this to store data about
                   5829: them or modify them in various ways.
1.191     harris41 5830: 
1.394     bowersj2 5831: =head2 Symbs
1.191     harris41 5832: 
1.394     bowersj2 5833: To identify a specific instance of a resource, LON-CAPA uses symbols
                   5834: or "symbs"X<symb>. These identifiers are built from the URL of the
                   5835: map, the resource number of the resource in the map, and the URL of
                   5836: the resource itself. The latter is somewhat redundant, but might help
                   5837: if maps change.
                   5838: 
                   5839: An example is
                   5840: 
                   5841:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   5842: 
                   5843: The respective map entry is
                   5844: 
                   5845:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   5846:   title="Problem 2">
                   5847:  </resource>
                   5848: 
                   5849: Symbs are used by the random number generator, as well as to store and
                   5850: restore data specific to a certain instance of for example a problem.
                   5851: 
                   5852: =head2 Storing And Retrieving Data
                   5853: 
                   5854: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   5855: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   5856: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   5857: is is the non-critical message twin of cstore. These functions are for
                   5858: handlers to store a perl hash to a user's permanent data space in an
                   5859: easy manner, and to retrieve it again on another call. It is expected
                   5860: that a handler would use this once at the beginning to retrieve data,
                   5861: and then again once at the end to send only the new data back.
                   5862: 
                   5863: The data is stored in the user's data directory on the user's
                   5864: homeserver under the ID of the course.
                   5865: 
                   5866: The hash that is returned by restore will have all of the previous
                   5867: value for all of the elements of the hash.
                   5868: 
                   5869: Example:
                   5870: 
                   5871:  #creating a hash
                   5872:  my %hash;
                   5873:  $hash{'foo'}='bar';
                   5874: 
                   5875:  #storing it
                   5876:  &Apache::lonnet::cstore(\%hash);
                   5877: 
                   5878:  #changing a value
                   5879:  $hash{'foo'}='notbar';
                   5880: 
                   5881:  #adding a new value
                   5882:  $hash{'bar'}='foo';
                   5883:  &Apache::lonnet::cstore(\%hash);
                   5884: 
                   5885:  #retrieving the hash
                   5886:  my %history=&Apache::lonnet::restore();
                   5887: 
                   5888:  #print the hash
                   5889:  foreach my $key (sort(keys(%history))) {
                   5890:    print("\%history{$key} = $history{$key}");
                   5891:  }
                   5892: 
                   5893: Will print out:
1.191     harris41 5894: 
1.394     bowersj2 5895:  %history{1:foo} = bar
                   5896:  %history{1:keys} = foo:timestamp
                   5897:  %history{1:timestamp} = 990455579
                   5898:  %history{2:bar} = foo
                   5899:  %history{2:foo} = notbar
                   5900:  %history{2:keys} = foo:bar:timestamp
                   5901:  %history{2:timestamp} = 990455580
                   5902:  %history{bar} = foo
                   5903:  %history{foo} = notbar
                   5904:  %history{timestamp} = 990455580
                   5905:  %history{version} = 2
                   5906: 
                   5907: Note that the special hash entries C<keys>, C<version> and
                   5908: C<timestamp> were added to the hash. C<version> will be equal to the
                   5909: total number of versions of the data that have been stored. The
                   5910: C<timestamp> attribute will be the UNIX time the hash was
                   5911: stored. C<keys> is available in every historical section to list which
                   5912: keys were added or changed at a specific historical revision of a
                   5913: hash.
                   5914: 
                   5915: B<Warning>: do not store the hash that restore returns directly. This
                   5916: will cause a mess since it will restore the historical keys as if the
                   5917: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 5918: 
1.394     bowersj2 5919: Calling convention:
1.191     harris41 5920: 
1.394     bowersj2 5921:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   5922:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 5923: 
1.394     bowersj2 5924: For more detailed information, see lonnet specific documentation.
1.191     harris41 5925: 
1.394     bowersj2 5926: =head1 RETURN MESSAGES
1.191     harris41 5927: 
1.394     bowersj2 5928: =over 4
1.191     harris41 5929: 
1.394     bowersj2 5930: =item * B<con_lost>: unable to contact remote host
1.191     harris41 5931: 
1.394     bowersj2 5932: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   5933: when the connection is brought back up
1.191     harris41 5934: 
1.394     bowersj2 5935: =item * B<con_failed>: unable to contact remote host and unable to save message
                   5936: for later delivery
1.191     harris41 5937: 
1.394     bowersj2 5938: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 5939: 
1.394     bowersj2 5940: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 5941: that was requested
1.191     harris41 5942: 
1.243     albertel 5943: =back
1.191     harris41 5944: 
1.243     albertel 5945: =head1 PUBLIC SUBROUTINES
1.191     harris41 5946: 
1.243     albertel 5947: =head2 Session Environment Functions
1.191     harris41 5948: 
1.243     albertel 5949: =over 4
1.191     harris41 5950: 
1.394     bowersj2 5951: =item * 
                   5952: X<appenv()>
                   5953: B<appenv(%hash)>: the value of %hash is written to
                   5954: the user envirnoment file, and will be restored for each access this
1.620     albertel 5955: user makes during this session, also modifies the %env for the current
1.394     bowersj2 5956: process
1.191     harris41 5957: 
                   5958: =item *
1.394     bowersj2 5959: X<delenv()>
                   5960: B<delenv($regexp)>: removes all items from the session
                   5961: environment file that matches the regular expression in $regexp. The
1.620     albertel 5962: values are also delted from the current processes %env.
1.191     harris41 5963: 
1.243     albertel 5964: =back
                   5965: 
                   5966: =head2 User Information
1.191     harris41 5967: 
1.243     albertel 5968: =over 4
1.191     harris41 5969: 
                   5970: =item *
1.394     bowersj2 5971: X<queryauthenticate()>
                   5972: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 5973: authentication scheme
                   5974: 
                   5975: =item *
1.394     bowersj2 5976: X<authenticate()>
                   5977: B<authenticate($uname,$upass,$udom)>: try to
                   5978: authenticate user from domain's lib servers (first use the current
                   5979: one). C<$upass> should be the users password.
1.191     harris41 5980: 
                   5981: =item *
1.394     bowersj2 5982: X<homeserver()>
                   5983: B<homeserver($uname,$udom)>: find the server which has
                   5984: the user's directory and files (there must be only one), this caches
                   5985: the answer, and also caches if there is a borken connection.
1.191     harris41 5986: 
                   5987: =item *
1.394     bowersj2 5988: X<idget()>
                   5989: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   5990: (IDs are a unique resource in a domain, there must be only 1 ID per
                   5991: username, and only 1 username per ID in a specific domain) (returns
                   5992: hash: id=>name,id=>name)
1.191     harris41 5993: 
                   5994: =item *
1.394     bowersj2 5995: X<idrget()>
                   5996: B<idrget($udom,@unames)>: find the IDs behind a list of
                   5997: usernames (returns hash: name=>id,name=>id)
1.191     harris41 5998: 
                   5999: =item *
1.394     bowersj2 6000: X<idput()>
                   6001: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 6002: 
                   6003: =item *
1.394     bowersj2 6004: X<rolesinit()>
                   6005: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 6006: 
                   6007: =item *
1.551     albertel 6008: X<getsection()>
                   6009: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 6010: course $cname, return section name/number or '' for "not in course"
                   6011: and '-1' for "no section"
                   6012: 
                   6013: =item *
1.394     bowersj2 6014: X<userenvironment()>
                   6015: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 6016: passed in @what from the requested user's environment, returns a hash
                   6017: 
                   6018: =back
                   6019: 
                   6020: =head2 User Roles
                   6021: 
                   6022: =over 4
                   6023: 
                   6024: =item *
                   6025: 
                   6026: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   6027: actions
                   6028:  F: full access
                   6029:  U,I,K: authentication modes (cxx only)
                   6030:  '': forbidden
                   6031:  1: user needs to choose course
                   6032:  2: browse allowed
                   6033: 
                   6034: =item *
                   6035: 
                   6036: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   6037: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   6038: and course level
                   6039: 
                   6040: =item *
                   6041: 
                   6042: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   6043: explanation of a user role term
                   6044: 
                   6045: =back
                   6046: 
                   6047: =head2 User Modification
                   6048: 
                   6049: =over 4
                   6050: 
                   6051: =item *
                   6052: 
                   6053: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   6054: user for the level given by URL.  Optional start and end dates (leave empty
                   6055: string or zero for "no date")
1.191     harris41 6056: 
                   6057: =item *
                   6058: 
1.243     albertel 6059: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   6060: change a users, password, possible return values are: ok,
                   6061: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   6062: refused
1.191     harris41 6063: 
                   6064: =item *
                   6065: 
1.243     albertel 6066: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 6067: 
                   6068: =item *
                   6069: 
1.243     albertel 6070: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   6071: modify user
1.191     harris41 6072: 
                   6073: =item *
                   6074: 
1.286     matthew  6075: modifystudent
                   6076: 
                   6077: modify a students enrollment and identification information.
                   6078: The course id is resolved based on the current users environment.  
                   6079: This means the envoking user must be a course coordinator or otherwise
                   6080: associated with a course.
                   6081: 
1.297     matthew  6082: This call is essentially a wrapper for lonnet::modifyuser and
                   6083: lonnet::modify_student_enrollment
1.286     matthew  6084: 
                   6085: Inputs: 
                   6086: 
                   6087: =over 4
                   6088: 
                   6089: =item B<$udom> Students loncapa domain
                   6090: 
                   6091: =item B<$uname> Students loncapa login name
                   6092: 
                   6093: =item B<$uid> Students id/student number
                   6094: 
                   6095: =item B<$umode> Students authentication mode
                   6096: 
                   6097: =item B<$upass> Students password
                   6098: 
                   6099: =item B<$first> Students first name
                   6100: 
                   6101: =item B<$middle> Students middle name
                   6102: 
                   6103: =item B<$last> Students last name
                   6104: 
                   6105: =item B<$gene> Students generation
                   6106: 
                   6107: =item B<$usec> Students section in course
                   6108: 
                   6109: =item B<$end> Unix time of the roles expiration
                   6110: 
                   6111: =item B<$start> Unix time of the roles start date
                   6112: 
                   6113: =item B<$forceid> If defined, allow $uid to be changed
                   6114: 
                   6115: =item B<$desiredhome> server to use as home server for student
                   6116: 
                   6117: =back
1.297     matthew  6118: 
                   6119: =item *
                   6120: 
                   6121: modify_student_enrollment
                   6122: 
                   6123: Change a students enrollment status in a class.  The environment variable
                   6124: 'role.request.course' must be defined for this function to proceed.
                   6125: 
                   6126: Inputs:
                   6127: 
                   6128: =over 4
                   6129: 
                   6130: =item $udom, students domain
                   6131: 
                   6132: =item $uname, students name
                   6133: 
                   6134: =item $uid, students user id
                   6135: 
                   6136: =item $first, students first name
                   6137: 
                   6138: =item $middle
                   6139: 
                   6140: =item $last
                   6141: 
                   6142: =item $gene
                   6143: 
                   6144: =item $usec
                   6145: 
                   6146: =item $end
                   6147: 
                   6148: =item $start
                   6149: 
                   6150: =back
                   6151: 
1.191     harris41 6152: 
                   6153: =item *
                   6154: 
1.243     albertel 6155: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   6156: custom role; give a custom role to a user for the level given by URL.  Specify
                   6157: name and domain of role author, and role name
1.191     harris41 6158: 
                   6159: =item *
                   6160: 
1.243     albertel 6161: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 6162: 
                   6163: =item *
                   6164: 
1.243     albertel 6165: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   6166: 
                   6167: =back
                   6168: 
                   6169: =head2 Course Infomation
                   6170: 
                   6171: =over 4
1.191     harris41 6172: 
                   6173: =item *
                   6174: 
1.243     albertel 6175: coursedescription($courseid) : course description
1.191     harris41 6176: 
                   6177: =item *
                   6178: 
1.624     albertel 6179: resdata($name,$domain,$type,@which) : request for current parameter
                   6180: setting for a specific $type, where $type is either 'course' or 'user',
                   6181: @what should be a list of parameters to ask about. This routine caches
                   6182: answers for 5 minutes.
1.243     albertel 6183: 
                   6184: =back
                   6185: 
                   6186: =head2 Course Modification
                   6187: 
                   6188: =over 4
1.191     harris41 6189: 
                   6190: =item *
                   6191: 
1.243     albertel 6192: writecoursepref($courseid,%prefs) : write preferences (environment
                   6193: database) for a course
1.191     harris41 6194: 
                   6195: =item *
                   6196: 
1.243     albertel 6197: createcourse($udom,$description,$url) : make/modify course
                   6198: 
                   6199: =back
                   6200: 
                   6201: =head2 Resource Subroutines
                   6202: 
                   6203: =over 4
1.191     harris41 6204: 
                   6205: =item *
                   6206: 
1.243     albertel 6207: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 6208: 
                   6209: =item *
                   6210: 
1.243     albertel 6211: repcopy($filename) : subscribes to the requested file, and attempts to
                   6212: replicate from the owning library server, Might return
1.607     raeburn  6213: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   6214: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 6215: resource. Expects the local filesystem pathname
                   6216: (/home/httpd/html/res/....)
                   6217: 
                   6218: =back
                   6219: 
                   6220: =head2 Resource Information
                   6221: 
                   6222: =over 4
1.191     harris41 6223: 
                   6224: =item *
                   6225: 
1.243     albertel 6226: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   6227: a vairety of different possible values, $varname should be a request
                   6228: string, and the other parameters can be used to specify who and what
                   6229: one is asking about.
                   6230: 
                   6231: Possible values for $varname are environment.lastname (or other item
                   6232: from the envirnment hash), user.name (or someother aspect about the
                   6233: user), resource.0.maxtries (or some other part and parameter of a
                   6234: resource)
1.204     albertel 6235: 
                   6236: =item *
                   6237: 
1.243     albertel 6238: directcondval($number) : get current value of a condition; reads from a state
                   6239: string
1.204     albertel 6240: 
                   6241: =item *
                   6242: 
1.243     albertel 6243: condval($condidx) : value of condition index based on state
1.204     albertel 6244: 
                   6245: =item *
                   6246: 
1.243     albertel 6247: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   6248: resource's metadata, $what should be either a specific key, or either
                   6249: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   6250: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   6251: 
                   6252: this function automatically caches all requests
1.191     harris41 6253: 
                   6254: =item *
                   6255: 
1.243     albertel 6256: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   6257: network of library servers; returns file handle of where SQL and regex results
                   6258: will be stored for query
1.191     harris41 6259: 
                   6260: =item *
                   6261: 
1.243     albertel 6262: symbread($filename) : return symbolic list entry (filename argument optional);
                   6263: returns the data handle
1.191     harris41 6264: 
                   6265: =item *
                   6266: 
1.243     albertel 6267: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 6268: a possible symb for the URL in $thisfn, and if is an encryypted
                   6269: resource that the user accessed using /enc/ returns a 1 on success, 0
                   6270: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 6271: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 6272: 
1.191     harris41 6273: 
                   6274: =item *
                   6275: 
1.243     albertel 6276: symbclean($symb) : removes versions numbers from a symb, returns the
                   6277: cleaned symb
1.191     harris41 6278: 
                   6279: =item *
                   6280: 
1.243     albertel 6281: is_on_map($uri) : checks if the $uri is somewhere on the current
                   6282: course map, user must be in a course for it to work.
1.191     harris41 6283: 
                   6284: =item *
                   6285: 
1.243     albertel 6286: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 6287: 
                   6288: =item *
                   6289: 
1.243     albertel 6290: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   6291: a random seed, all arguments are optional, if they aren't sent it uses the
                   6292: environment to derive them. Note: if symb isn't sent and it can't get one
                   6293: from &symbread it will use the current time as its return value
1.191     harris41 6294: 
                   6295: =item *
                   6296: 
1.243     albertel 6297: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   6298: unfakeable, receipt
1.191     harris41 6299: 
                   6300: =item *
                   6301: 
1.620     albertel 6302: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 6303: 
                   6304: =item *
                   6305: 
1.243     albertel 6306: countacc($url) : count the number of accesses to a given URL
1.191     harris41 6307: 
                   6308: =item *
                   6309: 
1.243     albertel 6310: 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 6311: 
                   6312: =item *
                   6313: 
1.243     albertel 6314: 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 6315: 
                   6316: =item *
                   6317: 
1.243     albertel 6318: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 6319: 
                   6320: =item *
                   6321: 
1.243     albertel 6322: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   6323: forcing spreadsheet to reevaluate the resource scores next time.
                   6324: 
                   6325: =back
                   6326: 
                   6327: =head2 Storing/Retreiving Data
                   6328: 
                   6329: =over 4
1.191     harris41 6330: 
                   6331: =item *
                   6332: 
1.243     albertel 6333: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   6334: for this url; hashref needs to be given and should be a \%hashname; the
                   6335: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 6336: be derived from the env
1.191     harris41 6337: 
                   6338: =item *
                   6339: 
1.243     albertel 6340: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   6341: uses critical subroutine
1.191     harris41 6342: 
                   6343: =item *
                   6344: 
1.243     albertel 6345: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   6346: all args are optional
1.191     harris41 6347: 
                   6348: =item *
                   6349: 
1.243     albertel 6350: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   6351: works very similar to store/cstore, but all data is stored in a
                   6352: temporary location and can be reset using tmpreset, $storehash should
                   6353: be a hash reference, returns nothing on success
1.191     harris41 6354: 
                   6355: =item *
                   6356: 
1.243     albertel 6357: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   6358: similar to restore, but all data is stored in a temporary location and
                   6359: can be reset using tmpreset. Returns a hash of values on success,
                   6360: error string otherwise.
1.191     harris41 6361: 
                   6362: =item *
                   6363: 
1.243     albertel 6364: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   6365: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 6366: 
                   6367: =item *
                   6368: 
1.243     albertel 6369: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6370: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 6371: 
                   6372: =item *
                   6373: 
1.243     albertel 6374: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   6375: namesp ($udom and $uname are optional)
1.191     harris41 6376: 
                   6377: =item *
                   6378: 
1.243     albertel 6379: dump($namespace,$udom,$uname,$regexp) : 
                   6380: dumps the complete (or key matching regexp) namespace into a hash
                   6381: ($udom, $uname and $regexp are optional)
1.449     matthew  6382: 
                   6383: =item *
                   6384: 
                   6385: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   6386: $store can be a scalar, an array reference, or if the amount to be 
                   6387: incremented is > 1, a hash reference.
                   6388: 
                   6389: ($udom and $uname are optional)
1.191     harris41 6390: 
                   6391: =item *
                   6392: 
1.243     albertel 6393: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   6394: ($udom and $uname are optional)
1.191     harris41 6395: 
                   6396: =item *
                   6397: 
1.524     raeburn  6398: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
                   6399: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
                   6400: used in records written by &store and retrieved by &restore.  This function 
                   6401: was created for use in editing discussion posts, without incrementing the
                   6402: version number included in the key for a particular post. The colon 
                   6403: separated list of attribute names (e.g., the value associated with the key 
                   6404: 1:keys:$symb) is also generated and passed in the ampersand separated 
                   6405: items sent to lonnet::reply().  
                   6406: 
                   6407: =item *
                   6408: 
1.243     albertel 6409: cput($namespace,$storehash,$udom,$uname) : critical put
                   6410: ($udom and $uname are optional)
1.191     harris41 6411: 
                   6412: =item *
                   6413: 
1.243     albertel 6414: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   6415: reference filled in from namesp (encrypts the return communication)
                   6416: ($udom and $uname are optional)
1.191     harris41 6417: 
                   6418: =item *
                   6419: 
1.243     albertel 6420: log($udom,$name,$home,$message) : write to permanent log for user; use
                   6421: critical subroutine
                   6422: 
                   6423: =back
                   6424: 
                   6425: =head2 Network Status Functions
                   6426: 
                   6427: =over 4
1.191     harris41 6428: 
                   6429: =item *
                   6430: 
                   6431: dirlist($uri) : return directory list based on URI
                   6432: 
                   6433: =item *
                   6434: 
1.243     albertel 6435: spareserver() : find server with least workload from spare.tab
                   6436: 
                   6437: =back
                   6438: 
                   6439: =head2 Apache Request
                   6440: 
                   6441: =over 4
1.191     harris41 6442: 
                   6443: =item *
                   6444: 
1.243     albertel 6445: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   6446: localhost, posts hash
                   6447: 
                   6448: =back
                   6449: 
                   6450: =head2 Data to String to Data
                   6451: 
                   6452: =over 4
1.191     harris41 6453: 
                   6454: =item *
                   6455: 
1.243     albertel 6456: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   6457: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 6458: 
                   6459: =item *
                   6460: 
1.243     albertel 6461: hashref2str($hashref) : convert a hashref into a string complete with
                   6462: escaping and '=' and '&' separators, supports elements that are
                   6463: arrayrefs and hashrefs
1.191     harris41 6464: 
                   6465: =item *
                   6466: 
1.243     albertel 6467: arrayref2str($arrayref) : convert an arrayref into a string complete
                   6468: with escaping and '&' separators, supports elements that are arrayrefs
                   6469: and hashrefs
1.191     harris41 6470: 
                   6471: =item *
                   6472: 
1.243     albertel 6473: str2hash($string) : convert string to hash using unescaping and
                   6474: splitting on '=' and '&', supports elements that are arrayrefs and
                   6475: hashrefs
1.191     harris41 6476: 
                   6477: =item *
                   6478: 
1.243     albertel 6479: str2array($string) : convert string to hash using unescaping and
                   6480: splitting on '&', supports elements that are arrayrefs and hashrefs
                   6481: 
                   6482: =back
                   6483: 
                   6484: =head2 Logging Routines
                   6485: 
                   6486: =over 4
                   6487: 
                   6488: These routines allow one to make log messages in the lonnet.log and
                   6489: lonnet.perm logfiles.
1.191     harris41 6490: 
                   6491: =item *
                   6492: 
1.243     albertel 6493: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 6494: 
                   6495: =item *
                   6496: 
1.243     albertel 6497: logthis() : append message to the normal lonnet.log file, it gets
                   6498: preiodically rolled over and deleted.
1.191     harris41 6499: 
                   6500: =item *
                   6501: 
1.243     albertel 6502: logperm() : append a permanent message to lonnet.perm.log, this log
                   6503: file never gets deleted by any automated portion of the system, only
                   6504: messages of critical importance should go in here.
                   6505: 
                   6506: =back
                   6507: 
                   6508: =head2 General File Helper Routines
                   6509: 
                   6510: =over 4
1.191     harris41 6511: 
                   6512: =item *
                   6513: 
1.481     raeburn  6514: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   6515: (a) files in /uploaded
                   6516:   (i) If a local copy of the file exists - 
                   6517:       compares modification date of local copy with last-modified date for 
                   6518:       definitive version stored on home server for course. If local copy is 
                   6519:       stale, requests a new version from the home server and stores it. 
                   6520:       If the original has been removed from the home server, then local copy 
                   6521:       is unlinked.
                   6522:   (ii) If local copy does not exist -
                   6523:       requests the file from the home server and stores it. 
                   6524:   
                   6525:   If $caller is 'uploadrep':  
                   6526:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   6527:     for request for files originally uploaded via DOCS. 
                   6528:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   6529:   
                   6530:   Otherwise:
                   6531:      This indicates a call from the content generation phase of the request.
                   6532:      -  returns the entire contents of the file or -1.
                   6533:      
                   6534: (b) files in /res
                   6535:    - returns the entire contents of a file or -1; 
                   6536:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 6537: 
                   6538: =item *
                   6539: 
1.243     albertel 6540: filelocation($dir,$file) : returns file system location of a file
                   6541: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   6542: directory that relative $file lookups are to looked in ($dir of /a/dir
                   6543: and a file of ../bob will become /a/bob)
1.191     harris41 6544: 
                   6545: =item *
                   6546: 
                   6547: hreflocation($dir,$file) : returns file system location or a URL; same as
                   6548: filelocation except for hrefs
                   6549: 
                   6550: =item *
                   6551: 
                   6552: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   6553: 
1.243     albertel 6554: =back
                   6555: 
1.608     albertel 6556: =head2 Usererfile file routines (/uploaded*)
                   6557: 
                   6558: =over 4
                   6559: 
                   6560: =item *
                   6561: 
                   6562: userfileupload(): main rotine for putting a file in a user or course's
                   6563:                   filespace, arguments are,
                   6564: 
1.620     albertel 6565:  formname - required - this is the name of the element in $env where the
1.608     albertel 6566:            filename, and the contents of the file to create/modifed exist
1.620     albertel 6567:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   6568:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 6569:  coursedoc - if true, store the file in the course of the active role
                   6570:              of the current user
                   6571:  subdir - required - subdirectory to put the file in under ../userfiles/
                   6572:          if undefined, it will be placed in "unknown"
                   6573: 
                   6574:  (This routine calls clean_filename() to remove any dangerous
                   6575:  characters from the filename, and then calls finuserfileupload() to
                   6576:  complete the transaction)
                   6577: 
                   6578:  returns either the url of the uploaded file (/uploaded/....) if successful
                   6579:  and /adm/notfound.html if unsuccessful
                   6580: 
                   6581: =item *
                   6582: 
                   6583: clean_filename(): routine for cleaing a filename up for storage in
                   6584:                  userfile space, argument is:
                   6585: 
                   6586:  filename - proposed filename
                   6587: 
                   6588: returns: the new clean filename
                   6589: 
                   6590: =item *
                   6591: 
                   6592: finishuserfileupload(): routine that creaes and sends the file to
                   6593: userspace, probably shouldn't be called directly
                   6594: 
                   6595:   docuname: username or courseid of destination for the file
                   6596:   docudom: domain of user/course of destination for the file
                   6597:   docuhome: loncapa id of the library server that is getting the file
                   6598:   formname: same as for userfileupload()
                   6599:   fname: filename (inculding subdirectories) for the file
                   6600: 
                   6601:  returns either the url of the uploaded file (/uploaded/....) if successful
                   6602:  and /adm/notfound.html if unsuccessful
                   6603: 
                   6604: =item *
                   6605: 
                   6606: renameuserfile(): renames an existing userfile to a new name
                   6607: 
                   6608:   Args:
                   6609:    docuname: username or courseid of destination for the file
                   6610:    docudom: domain of user/course of destination for the file
                   6611:    old: current file name (including any subdirs under userfiles)
                   6612:    new: desired file name (including any subdirs under userfiles)
                   6613: 
                   6614: =item *
                   6615: 
                   6616: mkdiruserfile(): creates a directory is a userfiles dir
                   6617: 
                   6618:   Args:
                   6619:    docuname: username or courseid of destination for the file
                   6620:    docudom: domain of user/course of destination for the file
                   6621:    dir: dir to create (including any subdirs under userfiles)
                   6622: 
                   6623: =item *
                   6624: 
                   6625: removeuserfile(): removes a file that exists in userfiles
                   6626: 
                   6627:   Args:
                   6628:    docuname: username or courseid of destination for the file
                   6629:    docudom: domain of user/course of destination for the file
                   6630:    fname: filname to delete (including any subdirs under userfiles)
                   6631: 
                   6632: =item *
                   6633: 
                   6634: removeuploadedurl(): convience function for removeuserfile()
                   6635: 
                   6636:   Args:
                   6637:    url:  a full /uploaded/... url to delete
                   6638: 
                   6639: =back
                   6640: 
1.243     albertel 6641: =head2 HTTP Helper Routines
                   6642: 
                   6643: =over 4
                   6644: 
1.191     harris41 6645: =item *
                   6646: 
                   6647: escape() : unpack non-word characters into CGI-compatible hex codes
                   6648: 
                   6649: =item *
                   6650: 
                   6651: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   6652: 
1.243     albertel 6653: =back
                   6654: 
                   6655: =head1 PRIVATE SUBROUTINES
                   6656: 
                   6657: =head2 Underlying communication routines (Shouldn't call)
                   6658: 
                   6659: =over 4
                   6660: 
                   6661: =item *
                   6662: 
                   6663: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   6664: 
                   6665: =item *
                   6666: 
                   6667: reply() : uses subreply to send a message to remote machine, logs all failures
                   6668: 
                   6669: =item *
                   6670: 
                   6671: critical() : passes a critical message to another server; if cannot
                   6672: get through then place message in connection buffer directory and
                   6673: returns con_delayed, if incapable of saving message, returns
                   6674: con_failed
                   6675: 
                   6676: =item *
                   6677: 
                   6678: reconlonc() : tries to reconnect lonc client processes.
                   6679: 
                   6680: =back
                   6681: 
                   6682: =head2 Resource Access Logging
                   6683: 
                   6684: =over 4
                   6685: 
                   6686: =item *
                   6687: 
                   6688: flushcourselogs() : flush (save) buffer logs and access logs
                   6689: 
                   6690: =item *
                   6691: 
                   6692: courselog($what) : save message for course in hash
                   6693: 
                   6694: =item *
                   6695: 
                   6696: courseacclog($what) : save message for course using &courselog().  Perform
                   6697: special processing for specific resource types (problems, exams, quizzes, etc).
                   6698: 
1.191     harris41 6699: =item *
                   6700: 
                   6701: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   6702: as a PerlChildExitHandler
1.243     albertel 6703: 
                   6704: =back
                   6705: 
                   6706: =head2 Other
                   6707: 
                   6708: =over 4
                   6709: 
                   6710: =item *
                   6711: 
                   6712: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 6713: 
                   6714: =back
                   6715: 
                   6716: =cut

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