Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.789
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.789 ! albertel 4: # $Id: lonnet.pm,v 1.788 2006/10/04 19:48:32 albertel Exp $
1.178 www 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
1.169 harris41 28: ###
29:
1.1 albertel 30: package Apache::lonnet;
31:
32: use strict;
1.8 www 33: use LWP::UserAgent();
1.15 www 34: use HTTP::Headers;
1.486 www 35: use HTTP::Date;
36: # use Date::Parse;
1.11 www 37: use vars
1.599 albertel 38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom
39: %libserv %pr %prp $memcache %packagetab
1.662 raeburn 40: %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount
1.741 raeburn 41: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599 albertel 42: %domaindescription %domain_auth_def %domain_auth_arg_def
1.685 raeburn 43: %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
44: $tmpdir $_64bit %env);
1.403 www 45:
1.1 albertel 46: use IO::Socket;
1.31 www 47: use GDBM_File;
1.208 albertel 48: use HTML::LCParser;
1.637 raeburn 49: use HTML::Parser;
1.88 www 50: use Fcntl qw(:flock);
1.557 albertel 51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539 albertel 52: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 53: use Cache::Memcached;
1.676 albertel 54: use Digest::MD5;
1.740 www 55: use lib '/home/httpd/lib/perl';
56: use LONCAPA;
57: use LONCAPA::Configuration;
1.676 albertel 58:
1.195 www 59: my $readit;
1.550 foxr 60: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 61:
1.619 albertel 62: require Exporter;
63:
64: our @ISA = qw (Exporter);
65: our @EXPORT = qw(%env);
66:
1.449 matthew 67: =pod
68:
69: =head1 Package Variables
70:
71: These are largely undocumented, so if you decipher one please note it here.
72:
73: =over 4
74:
75: =item $processmarker
76:
77: Contains the time this process was started and this servers host id.
78:
79: =item $dumpcount
80:
81: Counts the number of times a message log flush has been attempted (regardless
82: of success) by this process. Used as part of the filename when messages are
83: delayed.
84:
85: =back
86:
87: =cut
88:
89:
1.1 albertel 90: # --------------------------------------------------------------------- Logging
1.729 www 91: {
92: my $logid;
93: sub instructor_log {
94: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
95: $logid++;
96: my $id=time().'00000'.$$.'00000'.$logid;
97: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 98: { $id => {
99: 'exe_uname' => $env{'user.name'},
100: 'exe_udom' => $env{'user.domain'},
101: 'exe_time' => time(),
102: 'exe_ip' => $ENV{'REMOTE_ADDR'},
103: 'delflag' => $delflag,
104: 'logentry' => $storehash,
105: 'uname' => $uname,
106: 'udom' => $udom,
107: }
108: },
1.729 www 109: $env{'course.'.$env{'request.course.id'}.'.domain'},
110: $env{'course.'.$env{'request.course.id'}.'.num'}
111: );
112: }
113: }
1.1 albertel 114:
1.163 harris41 115: sub logtouch {
116: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 117: unless (-e "$execdir/logs/lonnet.log") {
118: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 119: close $fh;
120: }
121: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
122: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
123: }
124:
1.1 albertel 125: sub logthis {
126: my $message=shift;
127: my $execdir=$perlvar{'lonDaemons'};
128: my $now=time;
129: my $local=localtime($now);
1.448 albertel 130: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
131: print $fh "$local ($$): $message\n";
132: close($fh);
133: }
1.1 albertel 134: return 1;
135: }
136:
137: sub logperm {
138: my $message=shift;
139: my $execdir=$perlvar{'lonDaemons'};
140: my $now=time;
141: my $local=localtime($now);
1.448 albertel 142: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
143: print $fh "$now:$message:$local\n";
144: close($fh);
145: }
1.1 albertel 146: return 1;
147: }
148:
149: # -------------------------------------------------- Non-critical communication
150: sub subreply {
151: my ($cmd,$server)=@_;
1.704 albertel 152: my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549 foxr 153: #
154: # With loncnew process trimming, there's a timing hole between lonc server
155: # process exit and the master server picking up the listen on the AF_UNIX
156: # socket. In that time interval, a lock file will exist:
157:
158: my $lockfile=$peerfile.".lock";
159: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
160: sleep(1);
161: }
162: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 163: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 164: #
1.550 foxr 165: # We'll give the connection a few tries before abandoning it. If
166: # connection is not possible, we'll con_lost back to the client.
167: #
168: my $client;
169: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
170: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
171: Type => SOCK_STREAM,
172: Timeout => 10);
173: if($client) {
174: last; # Connected!
175: }
176: sleep(1); # Try again later if failed connection.
177: }
178: my $answer;
179: if ($client) {
1.704 albertel 180: print $client "sethost:$server:$cmd\n";
1.550 foxr 181: $answer=<$client>;
182: if (!$answer) { $answer="con_lost"; }
183: chomp($answer);
184: } else {
185: $answer = 'con_lost'; # Failed connection.
186: }
1.1 albertel 187: return $answer;
188: }
189:
190: sub reply {
191: my ($cmd,$server)=@_;
1.205 www 192: unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1 albertel 193: my $answer=subreply($cmd,$server);
1.65 www 194: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 195: &logthis("<font color=\"blue\">WARNING:".
1.12 www 196: " $cmd to $server returned $answer</font>");
197: }
1.1 albertel 198: return $answer;
199: }
200:
201: # ----------------------------------------------------------- Send USR1 to lonc
202:
203: sub reconlonc {
204: my $peerfile=shift;
205: &logthis("Trying to reconnect for $peerfile");
206: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 207: if (open(my $fh,"<$loncfile")) {
1.1 albertel 208: my $loncpid=<$fh>;
209: chomp($loncpid);
210: if (kill 0 => $loncpid) {
211: &logthis("lonc at pid $loncpid responding, sending USR1");
212: kill USR1 => $loncpid;
213: sleep 1;
214: if (-e "$peerfile") { return; }
215: &logthis("$peerfile still not there, give it another try");
216: sleep 5;
217: if (-e "$peerfile") { return; }
1.12 www 218: &logthis(
1.672 albertel 219: "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1 albertel 220: } else {
1.12 www 221: &logthis(
1.672 albertel 222: "<font color=\"blue\">WARNING:".
1.12 www 223: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 224: }
225: } else {
1.672 albertel 226: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 227: }
228: }
229:
230: # ------------------------------------------------------ Critical communication
1.12 www 231:
1.1 albertel 232: sub critical {
233: my ($cmd,$server)=@_;
1.89 www 234: unless ($hostname{$server}) {
1.672 albertel 235: &logthis("<font color=\"blue\">WARNING:".
1.89 www 236: " Critical message to unknown server ($server)</font>");
237: return 'no_such_host';
238: }
1.1 albertel 239: my $answer=reply($cmd,$server);
240: if ($answer eq 'con_lost') {
241: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 242: my $answer=reply($cmd,$server);
1.1 albertel 243: if ($answer eq 'con_lost') {
244: my $now=time;
245: my $middlename=$cmd;
1.5 www 246: $middlename=substr($middlename,0,16);
1.1 albertel 247: $middlename=~s/\W//g;
248: my $dfilename=
1.305 www 249: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
250: $dumpcount++;
1.1 albertel 251: {
1.448 albertel 252: my $dfh;
253: if (open($dfh,">$dfilename")) {
254: print $dfh "$cmd\n";
255: close($dfh);
256: }
1.1 albertel 257: }
258: sleep 2;
259: my $wcmd='';
260: {
1.448 albertel 261: my $dfh;
262: if (open($dfh,"<$dfilename")) {
263: $wcmd=<$dfh>;
264: close($dfh);
265: }
1.1 albertel 266: }
267: chomp($wcmd);
1.7 www 268: if ($wcmd eq $cmd) {
1.672 albertel 269: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 270: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 271: &logperm("D:$server:$cmd");
272: return 'con_delayed';
273: } else {
1.672 albertel 274: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 275: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 276: &logperm("F:$server:$cmd");
277: return 'con_failed';
278: }
279: }
280: }
281: return $answer;
1.405 albertel 282: }
283:
1.755 albertel 284: # ------------------------------------------- check if return value is an error
285:
286: sub error {
287: my ($result) = @_;
1.756 albertel 288: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 289: if ($2 == 2) { return undef; }
290: return $1;
291: }
292: return undef;
293: }
294:
1.783 albertel 295: sub convert_and_load_session_env {
296: my ($lonidsdir,$handle)=@_;
297: my @profile;
298: {
299: open(my $idf,"$lonidsdir/$handle.id");
300: flock($idf,LOCK_SH);
301: @profile=<$idf>;
302: close($idf);
303: }
304: my %temp_env;
305: foreach my $line (@profile) {
1.786 albertel 306: if ($line !~ m/=/) {
307: return 0;
308: }
1.783 albertel 309: chomp($line);
310: my ($envname,$envvalue)=split(/=/,$line,2);
311: $temp_env{&unescape($envname)} = &unescape($envvalue);
312: }
313: unlink("$lonidsdir/$handle.id");
314: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
315: 0640)) {
316: %disk_env = %temp_env;
317: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
318: untie(%disk_env);
319: }
1.786 albertel 320: return 1;
1.783 albertel 321: }
322:
1.374 www 323: # ------------------------------------------- Transfer profile into environment
1.780 albertel 324: my $env_loaded;
325: sub transfer_profile_to_env {
1.788 albertel 326: my ($lonidsdir,$handle,$force_transfer) = @_;
327: if (!$force_transfer && $env_loaded) { return; }
1.374 www 328:
1.720 albertel 329: if (!defined($lonidsdir)) {
330: $lonidsdir = $perlvar{'lonIDsDir'};
331: }
332: if (!defined($handle)) {
333: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
334: }
335:
1.786 albertel 336: my $convert;
337: {
338: open(my $idf,"$lonidsdir/$handle.id");
339: flock($idf,LOCK_SH);
340: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
341: &GDBM_READER(),0640)) {
342: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
343: untie(%disk_env);
344: } else {
345: $convert = 1;
346: }
347: }
348: if ($convert) {
349: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
350: &logthis("Failed to load session, or convert session.");
351: }
1.374 www 352: }
1.783 albertel 353:
1.786 albertel 354: my %remove;
1.783 albertel 355: while ( my $envname = each(%env) ) {
1.433 matthew 356: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
357: if ($time < time-300) {
1.783 albertel 358: $remove{$key}++;
1.433 matthew 359: }
360: }
361: }
1.783 albertel 362:
1.619 albertel 363: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 364: $env_loaded=1;
1.783 albertel 365: foreach my $expired_key (keys(%remove)) {
1.433 matthew 366: &delenv($expired_key);
1.374 www 367: }
1.1 albertel 368: }
369:
1.5 www 370: # ---------------------------------------------------------- Append Environment
371:
372: sub appenv {
1.6 www 373: my %newenv=@_;
1.692 albertel 374: foreach my $key (keys(%newenv)) {
375: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672 albertel 376: &logthis("<font color=\"blue\">WARNING: ".
1.692 albertel 377: "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151 www 378: .'</font>');
1.692 albertel 379: delete($newenv{$key});
1.35 www 380: } else {
1.692 albertel 381: $env{$key}=$newenv{$key};
1.35 www 382: }
1.191 harris41 383: }
1.783 albertel 384: if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
385: 0640)) {
386: while (my ($key,$value) = each(%newenv)) {
387: $disk_env{$key} = $value;
1.448 albertel 388: }
1.783 albertel 389: untie(%disk_env);
1.56 www 390: }
391: return 'ok';
392: }
393: # ----------------------------------------------------- Delete from Environment
394:
395: sub delenv {
396: my $delthis=shift;
397: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 398: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 399: "Attempt to delete from environment ".$delthis);
400: return 'error';
401: }
1.783 albertel 402: if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
403: 0640)) {
404: foreach my $key (keys(%disk_env)) {
405: if ($key=~/^$delthis/) {
1.619 albertel 406: delete($env{$key});
1.783 albertel 407: delete($disk_env{$key});
1.473 matthew 408: }
1.448 albertel 409: }
1.783 albertel 410: untie(%disk_env);
1.5 www 411: }
412: return 'ok';
1.369 albertel 413: }
414:
415: # ------------------------------------------ Find out current server userload
416: # there is a copy in lond
417: sub userload {
418: my $numusers=0;
419: {
420: opendir(LONIDS,$perlvar{'lonIDsDir'});
421: my $filename;
422: my $curtime=time;
423: while ($filename=readdir(LONIDS)) {
424: if ($filename eq '.' || $filename eq '..') {next;}
1.404 albertel 425: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 426: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 427: }
428: closedir(LONIDS);
429: }
430: my $userloadpercent=0;
431: my $maxuserload=$perlvar{'lonUserLoadLim'};
432: if ($maxuserload) {
1.371 albertel 433: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 434: }
1.372 albertel 435: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 436: return $userloadpercent;
1.283 www 437: }
438:
439: # ------------------------------------------ Fight off request when overloaded
440:
441: sub overloaderror {
442: my ($r,$checkserver)=@_;
443: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
444: my $loadavg;
445: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 446: open(my $loadfile,'/proc/loadavg');
1.283 www 447: $loadavg=<$loadfile>;
448: $loadavg =~ s/\s.*//g;
1.285 matthew 449: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 450: close($loadfile);
1.283 www 451: } else {
452: $loadavg=&reply('load',$checkserver);
453: }
1.285 matthew 454: my $overload=$loadavg-100;
1.283 www 455: if ($overload>0) {
1.285 matthew 456: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 457: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 458: return 413;
1.283 www 459: }
460: return '';
1.5 www 461: }
1.1 albertel 462:
463: # ------------------------------ Find server with least workload from spare.tab
1.11 www 464:
1.1 albertel 465: sub spareserver {
1.670 albertel 466: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 467: my $spare_server;
1.370 albertel 468: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 469: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
470: : $userloadpercent;
471:
472: foreach my $try_server (@{ $spareid{'primary'} }) {
473: ($spare_server, $lowest_load) =
474: &compare_server_load($try_server, $spare_server, $lowest_load);
475: }
476:
477: my $found_server = ($spare_server ne '' && $lowest_load < 100);
478:
479: if (!$found_server) {
480: foreach my $try_server (@{ $spareid{'default'} }) {
481: ($spare_server, $lowest_load) =
482: &compare_server_load($try_server, $spare_server, $lowest_load);
483: }
484: }
485:
486: if (!$want_server_name) {
487: $spare_server="http://$hostname{$spare_server}";
488: }
489: return $spare_server;
490: }
491:
492: sub compare_server_load {
493: my ($try_server, $spare_server, $lowest_load) = @_;
494:
495: my $loadans = &reply('load', $try_server);
496: my $userloadans = &reply('userload',$try_server);
497:
498: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
499: next; #didn't get a number from the server
500: }
501:
502: my $load;
503: if ($loadans =~ /\d/) {
504: if ($userloadans =~ /\d/) {
505: #both are numbers, pick the bigger one
506: $load = ($loadans > $userloadans) ? $loadans
507: : $userloadans;
1.411 albertel 508: } else {
1.784 albertel 509: $load = $loadans;
1.411 albertel 510: }
1.784 albertel 511: } else {
512: $load = $userloadans;
513: }
514:
515: if (($load =~ /\d/) && ($load < $lowest_load)) {
516: $spare_server = $try_server;
517: $lowest_load = $load;
1.370 albertel 518: }
1.784 albertel 519: return ($spare_server,$lowest_load);
1.202 matthew 520: }
521: # --------------------------------------------- Try to change a user's password
522:
523: sub changepass {
524: my ($uname,$udom,$currentpass,$newpass,$server)=@_;
525: $currentpass = &escape($currentpass);
526: $newpass = &escape($newpass);
527: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
528: $server);
529: if (! $answer) {
530: &logthis("No reply on password change request to $server ".
531: "by $uname in domain $udom.");
532: } elsif ($answer =~ "^ok") {
533: &logthis("$uname in $udom successfully changed their password ".
534: "on $server.");
535: } elsif ($answer =~ "^pwchange_failure") {
536: &logthis("$uname in $udom was unable to change their password ".
537: "on $server. The action was blocked by either lcpasswd ".
538: "or pwchange");
539: } elsif ($answer =~ "^non_authorized") {
540: &logthis("$uname in $udom did not get their password correct when ".
541: "attempting to change it on $server.");
542: } elsif ($answer =~ "^auth_mode_error") {
543: &logthis("$uname in $udom attempted to change their password despite ".
544: "not being locally or internally authenticated on $server.");
545: } elsif ($answer =~ "^unknown_user") {
546: &logthis("$uname in $udom attempted to change their password ".
547: "on $server but were unable to because $server is not ".
548: "their home server.");
549: } elsif ($answer =~ "^refused") {
550: &logthis("$server refused to change $uname in $udom password because ".
551: "it was sent an unencrypted request to change the password.");
552: }
553: return $answer;
1.1 albertel 554: }
555:
1.169 harris41 556: # ----------------------- Try to determine user's current authentication scheme
557:
558: sub queryauthenticate {
559: my ($uname,$udom)=@_;
1.456 albertel 560: my $uhome=&homeserver($uname,$udom);
561: if (!$uhome) {
562: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
563: return 'no_host';
564: }
565: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
566: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
567: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 568: }
1.456 albertel 569: return $answer;
1.169 harris41 570: }
571:
1.1 albertel 572: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 573:
1.1 albertel 574: sub authenticate {
575: my ($uname,$upass,$udom)=@_;
1.12 www 576: $upass=escape($upass);
1.199 www 577: $uname=~s/\W//g;
1.471 albertel 578: my $uhome=&homeserver($uname,$udom);
579: if (!$uhome) {
580: &logthis("User $uname at $udom is unknown in authenticate");
581: return 'no_host';
1.1 albertel 582: }
1.471 albertel 583: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
584: if ($answer eq 'authorized') {
585: &logthis("User $uname at $udom authorized by $uhome");
586: return $uhome;
587: }
588: if ($answer eq 'non_authorized') {
589: &logthis("User $uname at $udom rejected by $uhome");
590: return 'no_host';
1.9 www 591: }
1.471 albertel 592: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 593: return 'no_host';
594: }
595:
596: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 597:
1.599 albertel 598: my %homecache;
1.1 albertel 599: sub homeserver {
1.230 stredwic 600: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 601: my $index="$uname:$udom";
1.426 albertel 602:
1.599 albertel 603: if (exists($homecache{$index})) { return $homecache{$index}; }
1.1 albertel 604: my $tryserver;
605: foreach $tryserver (keys %libserv) {
1.230 stredwic 606: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 607: exists($badServerCache{$tryserver}));
1.1 albertel 608: if ($hostdom{$tryserver} eq $udom) {
609: my $answer=reply("home:$udom:$uname",$tryserver);
610: if ($answer eq 'found') {
1.599 albertel 611: return $homecache{$index}=$tryserver;
1.231 stredwic 612: } elsif ($answer eq 'no_host') {
613: $badServerCache{$tryserver}=1;
1.221 matthew 614: }
1.1 albertel 615: }
616: }
617: return 'no_host';
1.70 www 618: }
619:
620: # ------------------------------------- Find the usernames behind a list of IDs
621:
622: sub idget {
623: my ($udom,@ids)=@_;
624: my %returnhash=();
625:
626: my $tryserver;
627: foreach $tryserver (keys %libserv) {
628: if ($hostdom{$tryserver} eq $udom) {
629: my $idlist=join('&',@ids);
630: $idlist=~tr/A-Z/a-z/;
631: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
632: my @answer=();
1.76 www 633: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70 www 634: @answer=split(/\&/,$reply);
635: } ;
636: my $i;
637: for ($i=0;$i<=$#ids;$i++) {
638: if ($answer[$i]) {
639: $returnhash{$ids[$i]}=$answer[$i];
640: }
641: }
642: }
643: }
644: return %returnhash;
645: }
646:
647: # ------------------------------------- Find the IDs behind a list of usernames
648:
649: sub idrget {
650: my ($udom,@unames)=@_;
651: my %returnhash=();
1.191 harris41 652: foreach (@unames) {
1.70 www 653: $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191 harris41 654: }
1.70 www 655: return %returnhash;
656: }
657:
658: # ------------------------------- Store away a list of names and associated IDs
659:
660: sub idput {
661: my ($udom,%ids)=@_;
662: my %servers=();
1.191 harris41 663: foreach (keys %ids) {
1.487 albertel 664: &cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70 www 665: my $uhom=&homeserver($_,$udom);
666: if ($uhom ne 'no_host') {
667: my $id=&escape($ids{$_});
668: $id=~tr/A-Z/a-z/;
669: my $unam=&escape($_);
670: if ($servers{$uhom}) {
671: $servers{$uhom}.='&'.$id.'='.$unam;
672: } else {
673: $servers{$uhom}=$id.'='.$unam;
674: }
675: }
1.191 harris41 676: }
677: foreach (keys %servers) {
1.70 www 678: &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191 harris41 679: }
1.344 www 680: }
681:
682: # --------------------------------------------------- Assign a key to a student
683:
684: sub assign_access_key {
1.364 www 685: #
686: # a valid key looks like uname:udom#comments
687: # comments are being appended
688: #
1.498 www 689: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
690: $kdom=
1.620 albertel 691: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 692: $knum=
1.620 albertel 693: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 694: $cdom=
1.620 albertel 695: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 696: $cnum=
1.620 albertel 697: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
698: $udom=$env{'user.name'} unless (defined($udom));
699: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 700: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 701: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 702: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 703: # assigned to this person
704: # - this should not happen,
1.345 www 705: # unless something went wrong
706: # the first time around
707: # ready to assign
1.364 www 708: $logentry=$1.'; '.$logentry;
1.496 www 709: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 710: $kdom,$knum) eq 'ok') {
1.345 www 711: # key now belongs to user
1.346 www 712: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 713: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
714: &appenv('environment.'.$envkey => $ckey);
715: return 'ok';
716: } else {
717: return
718: 'error: Count not permanently assign key, will need to be re-entered later.';
719: }
720: } else {
721: return 'error: Could not assign key, try again later.';
722: }
1.364 www 723: } elsif (!$existing{$ckey}) {
1.345 www 724: # the key does not exist
725: return 'error: The key does not exist';
726: } else {
727: # the key is somebody else's
728: return 'error: The key is already in use';
729: }
1.344 www 730: }
731:
1.364 www 732: # ------------------------------------------ put an additional comment on a key
733:
734: sub comment_access_key {
735: #
736: # a valid key looks like uname:udom#comments
737: # comments are being appended
738: #
739: my ($ckey,$cdom,$cnum,$logentry)=@_;
740: $cdom=
1.620 albertel 741: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 742: $cnum=
1.620 albertel 743: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 744: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
745: if ($existing{$ckey}) {
746: $existing{$ckey}.='; '.$logentry;
747: # ready to assign
1.367 www 748: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 749: $cdom,$cnum) eq 'ok') {
750: return 'ok';
751: } else {
752: return 'error: Count not store comment.';
753: }
754: } else {
755: # the key does not exist
756: return 'error: The key does not exist';
757: }
758: }
759:
1.344 www 760: # ------------------------------------------------------ Generate a set of keys
761:
762: sub generate_access_keys {
1.364 www 763: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 764: $cdom=
1.620 albertel 765: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 766: $cnum=
1.620 albertel 767: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 768: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 769: unless (($cdom) && ($cnum)) { return 0; }
770: if ($number>10000) { return 0; }
771: sleep(2); # make sure don't get same seed twice
772: srand(time()^($$+($$<<15))); # from "Programming Perl"
773: my $total=0;
774: for (my $i=1;$i<=$number;$i++) {
775: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
776: sprintf("%lx",int(100000*rand)).'-'.
777: sprintf("%lx",int(100000*rand));
778: $newkey=~s/1/g/g; # folks mix up 1 and l
779: $newkey=~s/0/h/g; # and also 0 and O
780: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
781: if ($existing{$newkey}) {
782: $i--;
783: } else {
1.364 www 784: if (&put('accesskeys',
785: { $newkey => '# generated '.localtime().
1.620 albertel 786: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 787: '; '.$logentry },
788: $cdom,$cnum) eq 'ok') {
1.344 www 789: $total++;
790: }
791: }
792: }
1.620 albertel 793: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 794: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
795: return $total;
796: }
797:
798: # ------------------------------------------------------- Validate an accesskey
799:
800: sub validate_access_key {
801: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
802: $cdom=
1.620 albertel 803: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 804: $cnum=
1.620 albertel 805: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
806: $udom=$env{'user.domain'} unless (defined($udom));
807: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 808: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 809: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 810: }
811:
812: # ------------------------------------- Find the section of student in a course
1.652 albertel 813: sub devalidate_getsection_cache {
814: my ($udom,$unam,$courseid)=@_;
815: $courseid=~s/\_/\//g;
816: $courseid=~s/^(\w)/\/$1/;
817: my $hashid="$udom:$unam:$courseid";
818: &devalidate_cache_new('getsection',$hashid);
819: }
1.298 matthew 820:
821: sub getsection {
822: my ($udom,$unam,$courseid)=@_;
1.599 albertel 823: my $cachetime=1800;
1.298 matthew 824: $courseid=~s/\_/\//g;
825: $courseid=~s/^(\w)/\/$1/;
1.551 albertel 826:
827: my $hashid="$udom:$unam:$courseid";
1.599 albertel 828: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 829: if (defined($cached)) { return $result; }
830:
1.298 matthew 831: my %Pending;
832: my %Expired;
833: #
834: # Each role can either have not started yet (pending), be active,
835: # or have expired.
836: #
837: # If there is an active role, we are done.
838: #
839: # If there is more than one role which has not started yet,
840: # choose the one which will start sooner
841: # If there is one role which has not started yet, return it.
842: #
843: # If there is more than one expired role, choose the one which ended last.
844: # If there is a role which has expired, return it.
845: #
846: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
847: &homeserver($unam,$udom)))) {
848: my ($key,$value)=split(/\=/,$_);
849: $key=&unescape($key);
1.479 albertel 850: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 851: my $section=$1;
852: if ($key eq $courseid.'_st') { $section=''; }
853: my ($dummy,$end,$start)=split(/\_/,&unescape($value));
854: my $now=time;
1.548 albertel 855: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 856: $Expired{$end}=$section;
857: next;
858: }
1.548 albertel 859: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 860: $Pending{$start}=$section;
861: next;
862: }
1.599 albertel 863: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 864: }
865: #
866: # Presumedly there will be few matching roles from the above
867: # loop and the sorting time will be negligible.
868: if (scalar(keys(%Pending))) {
869: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 870: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 871: }
872: if (scalar(keys(%Expired))) {
873: my @sorted = sort {$a <=> $b} keys(%Expired);
874: my $time = pop(@sorted);
1.599 albertel 875: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 876: }
1.599 albertel 877: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 878: }
1.70 www 879:
1.599 albertel 880: sub save_cache {
881: &purge_remembered();
1.722 albertel 882: #&Apache::loncommon::validate_page();
1.620 albertel 883: undef(%env);
1.780 albertel 884: undef($env_loaded);
1.599 albertel 885: }
1.452 albertel 886:
1.599 albertel 887: my $to_remember=-1;
888: my %remembered;
889: my %accessed;
890: my $kicks=0;
891: my $hits=0;
892: sub devalidate_cache_new {
893: my ($name,$id,$debug) = @_;
894: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
895: $id=&escape($name.':'.$id);
896: $memcache->delete($id);
897: delete($remembered{$id});
898: delete($accessed{$id});
899: }
900:
901: sub is_cached_new {
902: my ($name,$id,$debug) = @_;
903: $id=&escape($name.':'.$id);
904: if (exists($remembered{$id})) {
905: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
906: $accessed{$id}=[&gettimeofday()];
907: $hits++;
908: return ($remembered{$id},1);
909: }
910: my $value = $memcache->get($id);
911: if (!(defined($value))) {
912: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 913: return (undef,undef);
1.416 albertel 914: }
1.599 albertel 915: if ($value eq '__undef__') {
916: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
917: $value=undef;
918: }
919: &make_room($id,$value,$debug);
920: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
921: return ($value,1);
922: }
923:
924: sub do_cache_new {
925: my ($name,$id,$value,$time,$debug) = @_;
926: $id=&escape($name.':'.$id);
927: my $setvalue=$value;
928: if (!defined($setvalue)) {
929: $setvalue='__undef__';
930: }
1.623 albertel 931: if (!defined($time) ) {
932: $time=600;
933: }
1.599 albertel 934: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600 albertel 935: $memcache->set($id,$setvalue,$time);
936: # need to make a copy of $value
937: #&make_room($id,$value,$debug);
1.599 albertel 938: return $value;
939: }
940:
941: sub make_room {
942: my ($id,$value,$debug)=@_;
943: $remembered{$id}=$value;
944: if ($to_remember<0) { return; }
945: $accessed{$id}=[&gettimeofday()];
946: if (scalar(keys(%remembered)) <= $to_remember) { return; }
947: my $to_kick;
948: my $max_time=0;
949: foreach my $other (keys(%accessed)) {
950: if (&tv_interval($accessed{$other}) > $max_time) {
951: $to_kick=$other;
952: $max_time=&tv_interval($accessed{$other});
953: }
954: }
955: delete($remembered{$to_kick});
956: delete($accessed{$to_kick});
957: $kicks++;
958: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 959: return;
960: }
961:
1.599 albertel 962: sub purge_remembered {
1.604 albertel 963: #&logthis("Tossing ".scalar(keys(%remembered)));
964: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 965: undef(%remembered);
966: undef(%accessed);
1.428 albertel 967: }
1.70 www 968: # ------------------------------------- Read an entry from a user's environment
969:
970: sub userenvironment {
971: my ($udom,$unam,@what)=@_;
972: my %returnhash=();
973: my @answer=split(/\&/,
974: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
975: &homeserver($unam,$udom)));
976: my $i;
977: for ($i=0;$i<=$#what;$i++) {
978: $returnhash{$what[$i]}=&unescape($answer[$i]);
979: }
980: return %returnhash;
1.1 albertel 981: }
982:
1.617 albertel 983: # ---------------------------------------------------------- Get a studentphoto
984: sub studentphoto {
985: my ($udom,$unam,$ext) = @_;
986: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 987: if (defined($env{'request.course.id'})) {
1.708 raeburn 988: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 989: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
990: return(&retrievestudentphoto($udom,$unam,$ext));
991: } else {
992: my ($result,$perm_reqd)=
1.707 albertel 993: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 994: if ($result eq 'ok') {
995: if (!($perm_reqd eq 'yes')) {
996: return(&retrievestudentphoto($udom,$unam,$ext));
997: }
998: }
999: }
1000: }
1001: } else {
1002: my ($result,$perm_reqd) =
1.707 albertel 1003: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1004: if ($result eq 'ok') {
1005: if (!($perm_reqd eq 'yes')) {
1006: return(&retrievestudentphoto($udom,$unam,$ext));
1007: }
1008: }
1009: }
1010: return '/adm/lonKaputt/lonlogo_broken.gif';
1011: }
1012:
1013: sub retrievestudentphoto {
1014: my ($udom,$unam,$ext,$type) = @_;
1015: my $home=&Apache::lonnet::homeserver($unam,$udom);
1016: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1017: if ($ret eq 'ok') {
1018: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1019: if ($type eq 'thumbnail') {
1020: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1021: }
1022: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1023: return $tokenurl;
1024: } else {
1025: if ($type eq 'thumbnail') {
1026: return '/adm/lonKaputt/genericstudent_tn.gif';
1027: } else {
1028: return '/adm/lonKaputt/lonlogo_broken.gif';
1029: }
1.617 albertel 1030: }
1031: }
1032:
1.263 www 1033: # -------------------------------------------------------------------- New chat
1034:
1035: sub chatsend {
1.724 raeburn 1036: my ($newentry,$anon,$group)=@_;
1.620 albertel 1037: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1038: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1039: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1040: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1041: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1042: &escape($newentry)).':'.$group,$chome);
1.292 www 1043: }
1044:
1045: # ------------------------------------------ Find current version of a resource
1046:
1047: sub getversion {
1048: my $fname=&clutter(shift);
1049: unless ($fname=~/^\/res\//) { return -1; }
1050: return ¤tversion(&filelocation('',$fname));
1051: }
1052:
1053: sub currentversion {
1054: my $fname=shift;
1.599 albertel 1055: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1056: if (defined($cached)) { return $result; }
1.292 www 1057: my $author=$fname;
1058: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1059: my ($udom,$uname)=split(/\//,$author);
1060: my $home=homeserver($uname,$udom);
1061: if ($home eq 'no_host') {
1062: return -1;
1063: }
1064: my $answer=reply("currentversion:$fname",$home);
1065: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1066: return -1;
1067: }
1.599 albertel 1068: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1069: }
1070:
1.1 albertel 1071: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1072:
1.1 albertel 1073: sub subscribe {
1074: my $fname=shift;
1.761 raeburn 1075: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1076: $fname=~s/[\n\r]//g;
1.1 albertel 1077: my $author=$fname;
1078: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1079: my ($udom,$uname)=split(/\//,$author);
1080: my $home=homeserver($uname,$udom);
1.335 albertel 1081: if ($home eq 'no_host') {
1082: return 'not_found';
1.1 albertel 1083: }
1084: my $answer=reply("sub:$fname",$home);
1.64 www 1085: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1086: $answer.=' by '.$home;
1087: }
1.1 albertel 1088: return $answer;
1089: }
1090:
1.8 www 1091: # -------------------------------------------------------------- Replicate file
1092:
1093: sub repcopy {
1094: my $filename=shift;
1.23 www 1095: $filename=~s/\/+/\//g;
1.607 raeburn 1096: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1097: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1098: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1099: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1100: return &repcopy_userfile($filename);
1101: }
1.532 albertel 1102: $filename=~s/[\n\r]//g;
1.8 www 1103: my $transname="$filename.in.transfer";
1.607 raeburn 1104: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1105: my $remoteurl=subscribe($filename);
1.64 www 1106: if ($remoteurl =~ /^con_lost by/) {
1107: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1108: return 'unavailable';
1.8 www 1109: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1110: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1111: return 'not_found';
1.64 www 1112: } elsif ($remoteurl =~ /^rejected by/) {
1113: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1114: return 'forbidden';
1.20 www 1115: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1116: return 'ok';
1.8 www 1117: } else {
1.290 www 1118: my $author=$filename;
1119: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1120: my ($udom,$uname)=split(/\//,$author);
1121: my $home=homeserver($uname,$udom);
1122: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1123: my @parts=split(/\//,$filename);
1124: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1125: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1126: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1127: return 'bad_request';
1.8 www 1128: }
1129: my $count;
1130: for ($count=5;$count<$#parts;$count++) {
1131: $path.="/$parts[$count]";
1132: if ((-e $path)!=1) {
1133: mkdir($path,0777);
1134: }
1135: }
1136: my $ua=new LWP::UserAgent;
1137: my $request=new HTTP::Request('GET',"$remoteurl");
1138: my $response=$ua->request($request,$transname);
1139: if ($response->is_error()) {
1140: unlink($transname);
1141: my $message=$response->status_line;
1.672 albertel 1142: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1143: ." LWP get: $message: $filename</font>");
1.607 raeburn 1144: return 'unavailable';
1.8 www 1145: } else {
1.16 www 1146: if ($remoteurl!~/\.meta$/) {
1147: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1148: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1149: if ($mresponse->is_error()) {
1150: unlink($filename.'.meta');
1151: &logthis(
1.672 albertel 1152: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1153: }
1154: }
1.8 www 1155: rename($transname,$filename);
1.607 raeburn 1156: return 'ok';
1.8 www 1157: }
1.290 www 1158: }
1.8 www 1159: }
1.330 www 1160: }
1161:
1162: # ------------------------------------------------ Get server side include body
1163: sub ssi_body {
1.381 albertel 1164: my ($filelink,%form)=@_;
1.606 matthew 1165: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1166: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1167: }
1.330 www 1168: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1169: &ssi($filelink,%form));
1.778 albertel 1170: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1171: $output=~s/^.*?\<body[^\>]*\>//si;
1172: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330 www 1173: return $output;
1.8 www 1174: }
1175:
1.15 www 1176: # --------------------------------------------------------- Server Side Include
1177:
1.782 albertel 1178: sub absolute_url {
1179: my ($host_name) = @_;
1180: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1181: if ($host_name eq '') {
1182: $host_name = $ENV{'SERVER_NAME'};
1183: }
1184: return $protocol.$host_name;
1185: }
1186:
1.15 www 1187: sub ssi {
1188:
1.23 www 1189: my ($fn,%form)=@_;
1.15 www 1190:
1191: my $ua=new LWP::UserAgent;
1.23 www 1192:
1193: my $request;
1.711 albertel 1194:
1195: $form{'no_update_last_known'}=1;
1196:
1.23 www 1197: if (%form) {
1.782 albertel 1198: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1199: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1200: } else {
1.782 albertel 1201: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1202: }
1203:
1.15 www 1204: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1205: my $response=$ua->request($request);
1206:
1.324 www 1207: return $response->content;
1208: }
1209:
1210: sub externalssi {
1211: my ($url)=@_;
1212: my $ua=new LWP::UserAgent;
1213: my $request=new HTTP::Request('GET',$url);
1214: my $response=$ua->request($request);
1.15 www 1215: return $response->content;
1216: }
1.254 www 1217:
1.492 albertel 1218: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1219:
1220: sub allowuploaded {
1221: my ($srcurl,$url)=@_;
1222: $url=&clutter(&declutter($url));
1223: my $dir=$url;
1224: $dir=~s/\/[^\/]+$//;
1225: my %httpref=();
1226: my $httpurl=&hreflocation('',$url);
1227: $httpref{'httpref.'.$httpurl}=$srcurl;
1228: &Apache::lonnet::appenv(%httpref);
1.254 www 1229: }
1.477 raeburn 1230:
1.478 albertel 1231: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1232: # input: action, courseID, current domain, intended
1.637 raeburn 1233: # path to file, source of file, instruction to parse file for objects,
1234: # ref to hash for embedded objects,
1235: # ref to hash for codebase of java objects.
1236: #
1.485 raeburn 1237: # output: url to file (if action was uploaddoc),
1238: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1239: #
1.478 albertel 1240: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1241: # course.
1.477 raeburn 1242: #
1.478 albertel 1243: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1244: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1245: # course's home server.
1.477 raeburn 1246: #
1.478 albertel 1247: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1248: # be copied from $source (current location) to
1249: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1250: # and will then be copied to
1251: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1252: # course's home server.
1.485 raeburn 1253: #
1.481 raeburn 1254: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1255: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1256: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1257: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1258: # in course's home server.
1.637 raeburn 1259: #
1.477 raeburn 1260:
1261: sub process_coursefile {
1.638 albertel 1262: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1263: my $fetchresult;
1.638 albertel 1264: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1265: if ($action eq 'propagate') {
1.638 albertel 1266: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1267: $home);
1.481 raeburn 1268: } else {
1.477 raeburn 1269: my $fpath = '';
1270: my $fname = $file;
1.478 albertel 1271: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1272: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1273: my $filepath = &build_filepath($fpath);
1.481 raeburn 1274: if ($action eq 'copy') {
1275: if ($source eq '') {
1276: $fetchresult = 'no source file';
1277: return $fetchresult;
1278: } else {
1279: my $destination = $filepath.'/'.$fname;
1280: rename($source,$destination);
1281: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1282: $home);
1.481 raeburn 1283: }
1284: } elsif ($action eq 'uploaddoc') {
1285: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1286: print $fh $env{'form.'.$source};
1.481 raeburn 1287: close($fh);
1.637 raeburn 1288: if ($parser eq 'parse') {
1289: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1290: unless ($parse_result eq 'ok') {
1291: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1292: }
1293: }
1.477 raeburn 1294: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1295: $home);
1.481 raeburn 1296: if ($fetchresult eq 'ok') {
1297: return '/uploaded/'.$fpath.'/'.$fname;
1298: } else {
1299: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1300: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1301: return '/adm/notfound.html';
1302: }
1.477 raeburn 1303: }
1304: }
1.485 raeburn 1305: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1306: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1307: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1308: }
1309: return $fetchresult;
1310: }
1311:
1.637 raeburn 1312: sub build_filepath {
1313: my ($fpath) = @_;
1314: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1315: unless ($fpath eq '') {
1316: my @parts=split('/',$fpath);
1317: foreach my $part (@parts) {
1318: $filepath.= '/'.$part;
1319: if ((-e $filepath)!=1) {
1320: mkdir($filepath,0777);
1321: }
1322: }
1323: }
1324: return $filepath;
1325: }
1326:
1327: sub store_edited_file {
1.638 albertel 1328: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1329: my $file = $primary_url;
1330: $file =~ s#^/uploaded/$docudom/$docuname/##;
1331: my $fpath = '';
1332: my $fname = $file;
1333: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1334: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1335: my $filepath = &build_filepath($fpath);
1336: open(my $fh,'>'.$filepath.'/'.$fname);
1337: print $fh $content;
1338: close($fh);
1.638 albertel 1339: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1340: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1341: $home);
1.637 raeburn 1342: if ($$fetchresult eq 'ok') {
1343: return '/uploaded/'.$fpath.'/'.$fname;
1344: } else {
1.638 albertel 1345: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1346: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1347: return '/adm/notfound.html';
1348: }
1349: }
1350:
1.531 albertel 1351: sub clean_filename {
1352: my ($fname)=@_;
1.315 www 1353: # Replace Windows backslashes by forward slashes
1.257 www 1354: $fname=~s/\\/\//g;
1.315 www 1355: # Get rid of everything but the actual filename
1.257 www 1356: $fname=~s/^.*\/([^\/]+)$/$1/;
1.315 www 1357: # Replace spaces by underscores
1358: $fname=~s/\s+/\_/g;
1359: # Replace all other weird characters by nothing
1.317 www 1360: $fname=~s/[^\w\.\-]//g;
1.540 albertel 1361: # Replace all .\d. sequences with _\d. so they no longer look like version
1362: # numbers
1363: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1364: return $fname;
1365: }
1366:
1.608 albertel 1367: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1368: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1369: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1370: # $coursedoc - if true up to the current course
1371: # if false
1372: # $subdir - directory in userfile to store the file into
1373: # $parser, $allfiles, $codebase - unknown
1374: #
1375: # output: url of file in userspace, or error: <message>
1376: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1377:
1378:
1.531 albertel 1379: sub userfileupload {
1.719 banghart 1380: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531 albertel 1381: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1382: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1383: $fname=&clean_filename($fname);
1.315 www 1384: # See if there is anything left
1.257 www 1385: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1386: chop($env{'form.'.$formname});
1.523 raeburn 1387: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1388: my $now = time;
1389: my $filepath = 'tmp/helprequests/'.$now;
1390: my @parts=split(/\//,$filepath);
1391: my $fullpath = $perlvar{'lonDaemons'};
1392: for (my $i=0;$i<@parts;$i++) {
1393: $fullpath .= '/'.$parts[$i];
1394: if ((-e $fullpath)!=1) {
1395: mkdir($fullpath,0777);
1396: }
1397: }
1398: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1399: print $fh $env{'form.'.$formname};
1.523 raeburn 1400: close($fh);
1.741 raeburn 1401: return $fullpath.'/'.$fname;
1402: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1403: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1404: '_'.$env{'user.domain'}.'/pending';
1405: my @parts=split(/\//,$filepath);
1406: my $fullpath = $perlvar{'lonDaemons'};
1407: for (my $i=0;$i<@parts;$i++) {
1408: $fullpath .= '/'.$parts[$i];
1409: if ((-e $fullpath)!=1) {
1410: mkdir($fullpath,0777);
1411: }
1412: }
1413: open(my $fh,'>'.$fullpath.'/'.$fname);
1414: print $fh $env{'form.'.$formname};
1415: close($fh);
1416: return $fullpath.'/'.$fname;
1.523 raeburn 1417: }
1.719 banghart 1418:
1.258 www 1419: # Create the directory if not present
1.493 albertel 1420: $fname="$subdir/$fname";
1.259 www 1421: if ($coursedoc) {
1.638 albertel 1422: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1423: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1424: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1425: return &finishuserfileupload($docuname,$docudom,
1426: $formname,$fname,$parser,$allfiles,
1427: $codebase);
1.481 raeburn 1428: } else {
1.620 albertel 1429: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1430: return &process_coursefile('uploaddoc',$docuname,$docudom,
1431: $fname,$formname,$parser,
1432: $allfiles,$codebase);
1.481 raeburn 1433: }
1.719 banghart 1434: } elsif (defined($destuname)) {
1435: my $docuname=$destuname;
1436: my $docudom=$destudom;
1437: return &finishuserfileupload($docuname,$docudom,$formname,
1438: $fname,$parser,$allfiles,$codebase);
1439:
1.259 www 1440: } else {
1.638 albertel 1441: my $docuname=$env{'user.name'};
1442: my $docudom=$env{'user.domain'};
1.714 raeburn 1443: if (exists($env{'form.group'})) {
1444: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1445: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1446: }
1.638 albertel 1447: return &finishuserfileupload($docuname,$docudom,$formname,
1448: $fname,$parser,$allfiles,$codebase);
1.259 www 1449: }
1.271 www 1450: }
1451:
1452: sub finishuserfileupload {
1.638 albertel 1453: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477 raeburn 1454: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1455: my $filepath=$perlvar{'lonDocRoot'};
1.494 albertel 1456: my ($fnamepath,$file);
1457: $file=$fname;
1458: if ($fname=~m|/|) {
1459: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1460: $path.=$fnamepath.'/';
1461: }
1.259 www 1462: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1463: my $count;
1464: for ($count=4;$count<=$#parts;$count++) {
1465: $filepath.="/$parts[$count]";
1466: if ((-e $filepath)!=1) {
1467: mkdir($filepath,0777);
1468: }
1469: }
1470: # Save the file
1471: {
1.701 albertel 1472: if (!open(FH,'>'.$filepath.'/'.$file)) {
1473: &logthis('Failed to create '.$filepath.'/'.$file);
1474: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1475: return '/adm/notfound.html';
1476: }
1477: if (!print FH ($env{'form.'.$formname})) {
1478: &logthis('Failed to write to '.$filepath.'/'.$file);
1479: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1480: return '/adm/notfound.html';
1481: }
1.570 albertel 1482: close(FH);
1.258 www 1483: }
1.637 raeburn 1484: if ($parser eq 'parse') {
1.638 albertel 1485: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1486: $codebase);
1.637 raeburn 1487: unless ($parse_result eq 'ok') {
1.638 albertel 1488: &logthis('Failed to parse '.$filepath.$file.
1489: ' for embedded media: '.$parse_result);
1.637 raeburn 1490: }
1491: }
1.259 www 1492: # Notify homeserver to grep it
1493: #
1.638 albertel 1494: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1495: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1496: if ($fetchresult eq 'ok') {
1.259 www 1497: #
1.258 www 1498: # Return the URL to it
1.494 albertel 1499: return '/uploaded/'.$path.$file;
1.263 www 1500: } else {
1.494 albertel 1501: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1502: ': '.$fetchresult);
1.263 www 1503: return '/adm/notfound.html';
1504: }
1.493 albertel 1505: }
1506:
1.637 raeburn 1507: sub extract_embedded_items {
1.648 raeburn 1508: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 1509: my @state = ();
1510: my %javafiles = (
1511: codebase => '',
1512: code => '',
1513: archive => ''
1514: );
1515: my %mediafiles = (
1516: src => '',
1517: movie => '',
1518: );
1.648 raeburn 1519: my $p;
1520: if ($content) {
1521: $p = HTML::LCParser->new($content);
1522: } else {
1523: $p = HTML::LCParser->new($filepath.'/'.$file);
1524: }
1.641 albertel 1525: while (my $t=$p->get_token()) {
1.640 albertel 1526: if ($t->[0] eq 'S') {
1527: my ($tagname, $attr) = ($t->[1],$t->[2]);
1528: push (@state, $tagname);
1.648 raeburn 1529: if (lc($tagname) eq 'allow') {
1530: &add_filetype($allfiles,$attr->{'src'},'src');
1531: }
1.640 albertel 1532: if (lc($tagname) eq 'img') {
1533: &add_filetype($allfiles,$attr->{'src'},'src');
1534: }
1.645 raeburn 1535: if (lc($tagname) eq 'script') {
1536: if ($attr->{'archive'} =~ /\.jar$/i) {
1537: &add_filetype($allfiles,$attr->{'archive'},'archive');
1538: } else {
1539: &add_filetype($allfiles,$attr->{'src'},'src');
1540: }
1541: }
1542: if (lc($tagname) eq 'link') {
1543: if (lc($attr->{'rel'}) eq 'stylesheet') {
1544: &add_filetype($allfiles,$attr->{'href'},'href');
1545: }
1546: }
1.640 albertel 1547: if (lc($tagname) eq 'object' ||
1548: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1549: foreach my $item (keys(%javafiles)) {
1550: $javafiles{$item} = '';
1551: }
1552: }
1553: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1554: my $name = lc($attr->{'name'});
1555: foreach my $item (keys(%javafiles)) {
1556: if ($name eq $item) {
1557: $javafiles{$item} = $attr->{'value'};
1558: last;
1559: }
1560: }
1561: foreach my $item (keys(%mediafiles)) {
1562: if ($name eq $item) {
1563: &add_filetype($allfiles, $attr->{'value'}, 'value');
1564: last;
1565: }
1566: }
1567: }
1568: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1569: foreach my $item (keys(%javafiles)) {
1570: if ($attr->{$item}) {
1571: $javafiles{$item} = $attr->{$item};
1572: last;
1573: }
1574: }
1575: foreach my $item (keys(%mediafiles)) {
1576: if ($attr->{$item}) {
1577: &add_filetype($allfiles,$attr->{$item},$item);
1578: last;
1579: }
1580: }
1581: }
1582: } elsif ($t->[0] eq 'E') {
1583: my ($tagname) = ($t->[1]);
1584: if ($javafiles{'codebase'} ne '') {
1585: $javafiles{'codebase'} .= '/';
1586: }
1587: if (lc($tagname) eq 'applet' ||
1588: lc($tagname) eq 'object' ||
1589: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1590: ) {
1591: foreach my $item (keys(%javafiles)) {
1592: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1593: my $file=$javafiles{'codebase'}.$javafiles{$item};
1594: &add_filetype($allfiles,$file,$item);
1595: }
1596: }
1597: }
1598: pop @state;
1599: }
1600: }
1.637 raeburn 1601: return 'ok';
1602: }
1603:
1.639 albertel 1604: sub add_filetype {
1605: my ($allfiles,$file,$type)=@_;
1606: if (exists($allfiles->{$file})) {
1607: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1608: push(@{$allfiles->{$file}}, &escape($type));
1609: }
1610: } else {
1611: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 1612: }
1613: }
1614:
1.493 albertel 1615: sub removeuploadedurl {
1616: my ($url)=@_;
1617: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 1618: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 1619: }
1620:
1621: sub removeuserfile {
1622: my ($docuname,$docudom,$fname)=@_;
1623: my $home=&homeserver($docuname,$docudom);
1624: return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257 www 1625: }
1.15 www 1626:
1.530 albertel 1627: sub mkdiruserfile {
1628: my ($docuname,$docudom,$dir)=@_;
1629: my $home=&homeserver($docuname,$docudom);
1630: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1631: }
1632:
1.531 albertel 1633: sub renameuserfile {
1634: my ($docuname,$docudom,$old,$new)=@_;
1635: my $home=&homeserver($docuname,$docudom);
1636: return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
1637: &escape("$new"),$home);
1638: }
1639:
1.14 www 1640: # ------------------------------------------------------------------------- Log
1641:
1642: sub log {
1643: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1644: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1645: }
1646:
1647: # ------------------------------------------------------------------ Course Log
1.352 www 1648: #
1649: # This routine flushes several buffers of non-mission-critical nature
1650: #
1.157 www 1651:
1652: sub flushcourselogs {
1.352 www 1653: &logthis('Flushing log buffers');
1654: #
1655: # course logs
1656: # This is a log of all transactions in a course, which can be used
1657: # for data mining purposes
1658: #
1659: # It also collects the courseid database, which lists last transaction
1660: # times and course titles for all courseids
1661: #
1662: my %courseidbuffer=();
1.191 harris41 1663: foreach (keys %courselogs) {
1.157 www 1664: my $crsid=$_;
1.352 www 1665: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1666: &escape($courselogs{$crsid}),
1667: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1668: delete $courselogs{$crsid};
1669: } else {
1670: &logthis('Failed to flush log buffer for '.$crsid);
1671: if (length($courselogs{$crsid})>40000) {
1.672 albertel 1672: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 1673: " exceeded maximum size, deleting.</font>");
1674: delete $courselogs{$crsid};
1675: }
1.352 www 1676: }
1677: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1678: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516 raeburn 1679: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1680: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352 www 1681: } else {
1682: $courseidbuffer{$coursehombuf{$crsid}}=
1.516 raeburn 1683: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1684: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571 raeburn 1685: }
1.191 harris41 1686: }
1.352 www 1687: #
1688: # Write course id database (reverse lookup) to homeserver of courses
1689: # Is used in pickcourse
1690: #
1691: foreach (keys %courseidbuffer) {
1.353 www 1692: &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352 www 1693: }
1694: #
1695: # File accesses
1696: # Writes to the dynamic metadata of resources to get hit counts, etc.
1697: #
1.449 matthew 1698: foreach my $entry (keys(%accesshash)) {
1.458 matthew 1699: if ($entry =~ /___count$/) {
1700: my ($dom,$name);
1701: ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
1702: if (! defined($dom) || $dom eq '' ||
1703: ! defined($name) || $name eq '') {
1.620 albertel 1704: my $cid = $env{'request.course.id'};
1705: $dom = $env{'request.'.$cid.'.domain'};
1706: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 1707: }
1.450 matthew 1708: my $value = $accesshash{$entry};
1709: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1710: my %temphash=($url => $value);
1.449 matthew 1711: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1712: if ($result eq 'ok') {
1713: delete $accesshash{$entry};
1714: } elsif ($result eq 'unknown_cmd') {
1715: # Target server has old code running on it.
1.450 matthew 1716: my %temphash=($entry => $value);
1.449 matthew 1717: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1718: delete $accesshash{$entry};
1719: }
1720: }
1721: } else {
1.458 matthew 1722: my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450 matthew 1723: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 1724: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1725: delete $accesshash{$entry};
1726: }
1.185 www 1727: }
1.191 harris41 1728: }
1.352 www 1729: #
1730: # Roles
1731: # Reverse lookup of user roles for course faculty/staff and co-authorship
1732: #
1.349 www 1733: foreach (keys %userrolehash) {
1734: my $entry=$_;
1.351 www 1735: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 1736: split(/\:/,$entry);
1737: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 1738: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 1739: $rudom,$runame) eq 'ok') {
1740: delete $userrolehash{$entry};
1741: }
1742: }
1.662 raeburn 1743: #
1744: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1745: #
1746: my %domrolebuffer = ();
1747: foreach my $entry (keys %domainrolehash) {
1748: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1749: if ($domrolebuffer{$rudom}) {
1750: $domrolebuffer{$rudom}.='&'.&escape($entry).
1751: '='.&escape($domainrolehash{$entry});
1752: } else {
1753: $domrolebuffer{$rudom}.=&escape($entry).
1754: '='.&escape($domainrolehash{$entry});
1755: }
1756: delete $domainrolehash{$entry};
1757: }
1758: foreach my $dom (keys(%domrolebuffer)) {
1759: foreach my $tryserver (keys %libserv) {
1760: if ($hostdom{$tryserver} eq $dom) {
1761: unless (&reply('domroleput:'.$dom.':'.
1762: $domrolebuffer{$dom},$tryserver) eq 'ok') {
1763: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
1764: }
1765: }
1766: }
1767: }
1.186 www 1768: $dumpcount++;
1.157 www 1769: }
1770:
1771: sub courselog {
1772: my $what=shift;
1.158 www 1773: $what=time.':'.$what;
1.620 albertel 1774: unless ($env{'request.course.id'}) { return ''; }
1775: $coursedombuf{$env{'request.course.id'}}=
1776: $env{'course.'.$env{'request.course.id'}.'.domain'};
1777: $coursenumbuf{$env{'request.course.id'}}=
1778: $env{'course.'.$env{'request.course.id'}.'.num'};
1779: $coursehombuf{$env{'request.course.id'}}=
1780: $env{'course.'.$env{'request.course.id'}.'.home'};
1781: $coursedescrbuf{$env{'request.course.id'}}=
1782: $env{'course.'.$env{'request.course.id'}.'.description'};
1783: $courseinstcodebuf{$env{'request.course.id'}}=
1784: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
1785: $courseownerbuf{$env{'request.course.id'}}=
1786: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 1787: $coursetypebuf{$env{'request.course.id'}}=
1788: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 1789: if (defined $courselogs{$env{'request.course.id'}}) {
1790: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 1791: } else {
1.620 albertel 1792: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 1793: }
1.620 albertel 1794: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 1795: &flushcourselogs();
1796: }
1.158 www 1797: }
1798:
1799: sub courseacclog {
1800: my $fnsymb=shift;
1.620 albertel 1801: unless ($env{'request.course.id'}) { return ''; }
1802: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 1803: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 1804: $what.=':POST';
1.583 matthew 1805: # FIXME: Probably ought to escape things....
1.620 albertel 1806: foreach (keys %env) {
1.158 www 1807: if ($_=~/^form\.(.*)/) {
1.620 albertel 1808: $what.=':'.$1.'='.$env{$_};
1.158 www 1809: }
1.191 harris41 1810: }
1.583 matthew 1811: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
1812: # FIXME: We should not be depending on a form parameter that someone
1813: # editing lonsearchcat.pm might change in the future.
1.620 albertel 1814: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 1815: $what.= ':POST';
1816: # FIXME: Probably ought to escape things....
1817: foreach my $element ('courseexp','crsfulltext','crsrelated',
1818: 'crsdiscuss') {
1.620 albertel 1819: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 1820: }
1821: }
1.158 www 1822: }
1823: &courselog($what);
1.149 www 1824: }
1825:
1.185 www 1826: sub countacc {
1827: my $url=&declutter(shift);
1.458 matthew 1828: return if (! defined($url) || $url eq '');
1.620 albertel 1829: unless ($env{'request.course.id'}) { return ''; }
1830: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 1831: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 1832: $accesshash{$key}++;
1.185 www 1833: }
1.349 www 1834:
1.361 www 1835: sub linklog {
1836: my ($from,$to)=@_;
1837: $from=&declutter($from);
1838: $to=&declutter($to);
1839: $accesshash{$from.'___'.$to.'___comefrom'}=1;
1840: $accesshash{$to.'___'.$from.'___goto'}=1;
1841: }
1842:
1.349 www 1843: sub userrolelog {
1844: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 1845: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 1846: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 1847: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1848: ($trole=~/^ta/)) {
1.350 www 1849: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1850: $userrolehash
1851: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 1852: =$tend.':'.$tstart;
1.662 raeburn 1853: }
1854: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
1855: ($trole=~/^li/) || ($trole=~/^li/) ||
1856: ($trole=~/^au/) || ($trole=~/^dg/) ||
1857: ($trole=~/^sc/)) {
1858: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
1859: $domainrolehash
1860: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1861: = $tend.':'.$tstart;
1862: }
1.351 www 1863: }
1864:
1865: sub get_course_adv_roles {
1866: my $cid=shift;
1.620 albertel 1867: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 1868: my %coursehash=&coursedescription($cid);
1.470 www 1869: my %nothide=();
1870: foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1871: $nothide{join(':',split(/[\@\:]/,$_))}=1;
1872: }
1.351 www 1873: my %returnhash=();
1874: my %dumphash=
1875: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
1876: my $now=time;
1877: foreach (keys %dumphash) {
1878: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1879: if (($tstart) && ($tstart<0)) { next; }
1880: if (($tend) && ($tend<$now)) { next; }
1881: if (($tstart) && ($now<$tstart)) { next; }
1882: my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576 albertel 1883: if ($username eq '' || $domain eq '') { next; }
1.470 www 1884: if ((&privileged($username,$domain)) &&
1885: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 1886: if ($role eq 'cr') { next; }
1.351 www 1887: my $key=&plaintext($role);
1888: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
1889: if ($returnhash{$key}) {
1890: $returnhash{$key}.=','.$username.':'.$domain;
1891: } else {
1892: $returnhash{$key}=$username.':'.$domain;
1893: }
1.400 www 1894: }
1895: return %returnhash;
1896: }
1897:
1898: sub get_my_roles {
1899: my ($uname,$udom)=@_;
1.620 albertel 1900: unless (defined($uname)) { $uname=$env{'user.name'}; }
1901: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400 www 1902: my %dumphash=
1903: &dump('nohist_userroles',$udom,$uname);
1904: my %returnhash=();
1905: my $now=time;
1906: foreach (keys %dumphash) {
1907: my ($tend,$tstart)=split(/\:/,$dumphash{$_});
1908: if (($tstart) && ($tstart<0)) { next; }
1909: if (($tend) && ($tend<$now)) { next; }
1910: if (($tstart) && ($now<$tstart)) { next; }
1911: my ($role,$username,$domain,$section)=split(/\:/,$_);
1912: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373 www 1913: }
1914: return %returnhash;
1.399 www 1915: }
1916:
1917: # ----------------------------------------------------- Frontpage Announcements
1918: #
1919: #
1920:
1921: sub postannounce {
1922: my ($server,$text)=@_;
1923: unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
1924: unless ($text=~/\w/) { $text=''; }
1925: return &reply('setannounce:'.&escape($text),$server);
1926: }
1927:
1928: sub getannounce {
1.448 albertel 1929:
1930: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 1931: my $announcement='';
1932: while (<$fh>) { $announcement .=$_; }
1.448 albertel 1933: close($fh);
1.399 www 1934: if ($announcement=~/\w/) {
1935: return
1936: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 1937: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 1938: } else {
1939: return '';
1940: }
1941: } else {
1942: return '';
1943: }
1.351 www 1944: }
1.353 www 1945:
1946: # ---------------------------------------------------------- Course ID routines
1947: # Deal with domain's nohist_courseid.db files
1948: #
1949:
1950: sub courseidput {
1951: my ($domain,$what,$coursehome)=@_;
1952: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
1953: }
1954:
1955: sub courseiddump {
1.741 raeburn 1956: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
1.353 www 1957: my %returnhash=();
1.355 www 1958: unless ($domfilter) { $domfilter=''; }
1.353 www 1959: foreach my $tryserver (keys %libserv) {
1.511 raeburn 1960: if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506 raeburn 1961: if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1962: foreach (
1963: split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571 raeburn 1964: $sincefilter.':'.&escape($descfilter).':'.
1.741 raeburn 1965: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
1.354 www 1966: $tryserver))) {
1.506 raeburn 1967: my ($key,$value)=split(/\=/,$_);
1968: if (($key) && ($value)) {
1.516 raeburn 1969: $returnhash{&unescape($key)}=$value;
1.506 raeburn 1970: }
1.353 www 1971: }
1972: }
1973: }
1974: }
1975: return %returnhash;
1976: }
1977:
1.658 raeburn 1978: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 1979:
1980: sub dcmailput {
1.685 raeburn 1981: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 1982: my $status = &Apache::lonnet::critical(
1.740 www 1983: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
1984: &escape($message),$server);
1.662 raeburn 1985: return $status;
1986: }
1987:
1.658 raeburn 1988: sub dcmaildump {
1989: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 1990: my %returnhash=();
1991: if (exists($domain_primary{$dom})) {
1992: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
1993: &escape($enddate).':';
1994: my @esc_senders=map { &escape($_)} @$senders;
1995: $cmd.=&escape(join('&',@esc_senders));
1996: foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
1997: my ($key,$value) = split(/\=/,$_);
1998: if (($key) && ($value)) {
1999: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2000: }
2001: }
2002: }
2003: return %returnhash;
2004: }
1.662 raeburn 2005: # ---------------------------------------------------------- Domain roles
2006:
2007: sub get_domain_roles {
2008: my ($dom,$roles,$startdate,$enddate)=@_;
2009: if (undef($startdate) || $startdate eq '') {
2010: $startdate = '.';
2011: }
2012: if (undef($enddate) || $enddate eq '') {
2013: $enddate = '.';
2014: }
2015: my $rolelist = join(':',@{$roles});
2016: my %personnel = ();
2017: foreach my $tryserver (keys(%libserv)) {
2018: if ($hostdom{$tryserver} eq $dom) {
2019: %{$personnel{$tryserver}}=();
2020: foreach (
2021: split(/\&/,&reply('domrolesdump:'.$dom.':'.
2022: &escape($startdate).':'.&escape($enddate).':'.
2023: &escape($rolelist), $tryserver))) {
2024: my($key,$value) = split(/\=/,$_);
2025: if (($key) && ($value)) {
2026: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2027: }
2028: }
2029: }
2030: }
2031: return %personnel;
2032: }
1.658 raeburn 2033:
1.149 www 2034: # ----------------------------------------------------------- Check out an item
2035:
1.504 albertel 2036: sub get_first_access {
2037: my ($type,$argsymb)=@_;
2038: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
2039: if ($argsymb) { $symb=$argsymb; }
2040: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2041: if ($type eq 'map') {
2042: $res=&symbread($map);
2043: } else {
2044: $res=$symb;
2045: }
2046: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2047: return $times{"$courseid\0$res"};
1.504 albertel 2048: }
2049:
2050: sub set_first_access {
2051: my ($type)=@_;
2052: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
2053: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2054: if ($type eq 'map') {
2055: $res=&symbread($map);
2056: } else {
2057: $res=$symb;
2058: }
2059: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2060: if (!$firstaccess) {
1.588 albertel 2061: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2062: }
2063: return 'already_set';
1.504 albertel 2064: }
2065:
1.149 www 2066: sub checkout {
2067: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2068: my $now=time;
2069: my $lonhost=$perlvar{'lonHostID'};
2070: my $infostr=&escape(
1.234 www 2071: 'CHECKOUTTOKEN&'.
1.149 www 2072: $tuname.'&'.
2073: $tudom.'&'.
2074: $tcrsid.'&'.
2075: $symb.'&'.
2076: $now.'&'.$ENV{'REMOTE_ADDR'});
2077: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2078: if ($token=~/^error\:/) {
1.672 albertel 2079: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2080: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2081: "</font>");
2082: return '';
2083: }
2084:
1.149 www 2085: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2086: $token=~tr/a-z/A-Z/;
2087:
1.153 www 2088: my %infohash=('resource.0.outtoken' => $token,
2089: 'resource.0.checkouttime' => $now,
2090: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2091:
2092: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2093: return '';
1.151 www 2094: } else {
1.672 albertel 2095: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2096: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2097: "</font>");
1.149 www 2098: }
2099:
2100: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2101: &escape('Checkout '.$infostr.' - '.
2102: $token)) ne 'ok') {
2103: return '';
1.151 www 2104: } else {
1.672 albertel 2105: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2106: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2107: "</font>");
1.149 www 2108: }
1.151 www 2109: return $token;
1.149 www 2110: }
2111:
2112: # ------------------------------------------------------------ Check in an item
2113:
2114: sub checkin {
2115: my $token=shift;
1.150 www 2116: my $now=time;
2117: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2118: $lonhost=~tr/A-Z/a-z/;
1.595 albertel 2119: my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150 www 2120: $dtoken=~s/\W/\_/g;
1.234 www 2121: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2122: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2123:
1.154 www 2124: unless (($tuname) && ($tudom)) {
2125: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2126: return '';
2127: }
2128:
2129: unless (&allowed('mgr',$tcrsid)) {
2130: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2131: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2132: return '';
2133: }
2134:
1.153 www 2135: my %infohash=('resource.0.intoken' => $token,
2136: 'resource.0.checkintime' => $now,
2137: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2138:
2139: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2140: return '';
2141: }
2142:
2143: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2144: &escape('Checkin - '.$token)) ne 'ok') {
2145: return '';
2146: }
2147:
2148: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2149: }
2150:
2151: # --------------------------------------------- Set Expire Date for Spreadsheet
2152:
2153: sub expirespread {
2154: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2155: my $cid=$env{'request.course.id'};
1.110 www 2156: if ($cid) {
2157: my $now=time;
2158: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2159: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2160: $env{'course.'.$cid.'.num'}.
1.110 www 2161: ':nohist_expirationdates:'.
2162: &escape($key).'='.$now,
1.620 albertel 2163: $env{'course.'.$cid.'.home'})
1.110 www 2164: }
2165: return 'ok';
1.14 www 2166: }
2167:
1.109 www 2168: # ----------------------------------------------------- Devalidate Spreadsheets
2169:
2170: sub devalidate {
1.325 www 2171: my ($symb,$uname,$udom)=@_;
1.620 albertel 2172: my $cid=$env{'request.course.id'};
1.109 www 2173: if ($cid) {
1.391 matthew 2174: # delete the stored spreadsheets for
2175: # - the student level sheet of this user in course's homespace
2176: # - the assessment level sheet for this resource
2177: # for this user in user's homespace
1.553 albertel 2178: # - current conditional state info
1.325 www 2179: my $key=$uname.':'.$udom.':';
1.109 www 2180: my $status=
1.299 matthew 2181: &del('nohist_calculatedsheets',
1.391 matthew 2182: [$key.'studentcalc:'],
1.620 albertel 2183: $env{'course.'.$cid.'.domain'},
2184: $env{'course.'.$cid.'.num'})
1.133 albertel 2185: .' '.
2186: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2187: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2188: unless ($status eq 'ok ok') {
2189: &logthis('Could not devalidate spreadsheet '.
1.325 www 2190: $uname.' at '.$udom.' for '.
1.109 www 2191: $symb.': '.$status);
1.133 albertel 2192: }
1.553 albertel 2193: &delenv('user.state.'.$cid);
1.109 www 2194: }
2195: }
2196:
1.265 albertel 2197: sub get_scalar {
2198: my ($string,$end) = @_;
2199: my $value;
2200: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2201: $value = $1;
2202: } elsif ($$string =~ s/^([^&]*?)&//) {
2203: $value = $1;
2204: }
2205: return &unescape($value);
2206: }
2207:
2208: sub array2str {
2209: my (@array) = @_;
2210: my $result=&arrayref2str(\@array);
2211: $result=~s/^__ARRAY_REF__//;
2212: $result=~s/__END_ARRAY_REF__$//;
2213: return $result;
2214: }
2215:
1.204 albertel 2216: sub arrayref2str {
2217: my ($arrayref) = @_;
1.265 albertel 2218: my $result='__ARRAY_REF__';
1.204 albertel 2219: foreach my $elem (@$arrayref) {
1.265 albertel 2220: if(ref($elem) eq 'ARRAY') {
2221: $result.=&arrayref2str($elem).'&';
2222: } elsif(ref($elem) eq 'HASH') {
2223: $result.=&hashref2str($elem).'&';
2224: } elsif(ref($elem)) {
2225: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2226: } else {
2227: $result.=&escape($elem).'&';
2228: }
2229: }
2230: $result=~s/\&$//;
1.265 albertel 2231: $result .= '__END_ARRAY_REF__';
1.204 albertel 2232: return $result;
2233: }
2234:
1.168 albertel 2235: sub hash2str {
1.204 albertel 2236: my (%hash) = @_;
2237: my $result=&hashref2str(\%hash);
1.265 albertel 2238: $result=~s/^__HASH_REF__//;
2239: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2240: return $result;
2241: }
2242:
2243: sub hashref2str {
2244: my ($hashref)=@_;
1.265 albertel 2245: my $result='__HASH_REF__';
1.495 albertel 2246: foreach (sort(keys(%$hashref))) {
1.204 albertel 2247: if (ref($_) eq 'ARRAY') {
1.265 albertel 2248: $result.=&arrayref2str($_).'=';
1.204 albertel 2249: } elsif (ref($_) eq 'HASH') {
1.265 albertel 2250: $result.=&hashref2str($_).'=';
1.204 albertel 2251: } elsif (ref($_)) {
1.265 albertel 2252: $result.='=';
2253: #print("Got a ref of ".(ref($_))." skipping.");
1.204 albertel 2254: } else {
1.265 albertel 2255: if ($_) {$result.=&escape($_).'=';} else { last; }
1.204 albertel 2256: }
2257:
1.265 albertel 2258: if(ref($hashref->{$_}) eq 'ARRAY') {
2259: $result.=&arrayref2str($hashref->{$_}).'&';
2260: } elsif(ref($hashref->{$_}) eq 'HASH') {
2261: $result.=&hashref2str($hashref->{$_}).'&';
2262: } elsif(ref($hashref->{$_})) {
2263: $result.='&';
2264: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204 albertel 2265: } else {
1.265 albertel 2266: $result.=&escape($hashref->{$_}).'&';
1.204 albertel 2267: }
2268: }
1.168 albertel 2269: $result=~s/\&$//;
1.265 albertel 2270: $result .= '__END_HASH_REF__';
1.168 albertel 2271: return $result;
2272: }
2273:
2274: sub str2hash {
1.265 albertel 2275: my ($string)=@_;
2276: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2277: return %$hash;
2278: }
2279:
2280: sub str2hashref {
1.168 albertel 2281: my ($string) = @_;
1.265 albertel 2282:
2283: my %hash;
2284:
2285: if($string !~ /^__HASH_REF__/) {
2286: if (! ($string eq '' || !defined($string))) {
2287: $hash{'error'}='Not hash reference';
2288: }
2289: return (\%hash, $string);
2290: }
2291:
2292: $string =~ s/^__HASH_REF__//;
2293:
2294: while($string !~ /^__END_HASH_REF__/) {
2295: #key
2296: my $key='';
2297: if($string =~ /^__HASH_REF__/) {
2298: ($key, $string)=&str2hashref($string);
2299: if(defined($key->{'error'})) {
2300: $hash{'error'}='Bad data';
2301: return (\%hash, $string);
2302: }
2303: } elsif($string =~ /^__ARRAY_REF__/) {
2304: ($key, $string)=&str2arrayref($string);
2305: if($key->[0] eq 'Array reference error') {
2306: $hash{'error'}='Bad data';
2307: return (\%hash, $string);
2308: }
2309: } else {
2310: $string =~ s/^(.*?)=//;
1.267 albertel 2311: $key=&unescape($1);
1.265 albertel 2312: }
2313: $string =~ s/^=//;
2314:
2315: #value
2316: my $value='';
2317: if($string =~ /^__HASH_REF__/) {
2318: ($value, $string)=&str2hashref($string);
2319: if(defined($value->{'error'})) {
2320: $hash{'error'}='Bad data';
2321: return (\%hash, $string);
2322: }
2323: } elsif($string =~ /^__ARRAY_REF__/) {
2324: ($value, $string)=&str2arrayref($string);
2325: if($value->[0] eq 'Array reference error') {
2326: $hash{'error'}='Bad data';
2327: return (\%hash, $string);
2328: }
2329: } else {
2330: $value=&get_scalar(\$string,'__END_HASH_REF__');
2331: }
2332: $string =~ s/^&//;
2333:
2334: $hash{$key}=$value;
1.204 albertel 2335: }
1.265 albertel 2336:
2337: $string =~ s/^__END_HASH_REF__//;
2338:
2339: return (\%hash, $string);
1.204 albertel 2340: }
2341:
2342: sub str2array {
1.265 albertel 2343: my ($string)=@_;
2344: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2345: return @$array;
2346: }
2347:
2348: sub str2arrayref {
1.204 albertel 2349: my ($string) = @_;
1.265 albertel 2350: my @array;
2351:
2352: if($string !~ /^__ARRAY_REF__/) {
2353: if (! ($string eq '' || !defined($string))) {
2354: $array[0]='Array reference error';
2355: }
2356: return (\@array, $string);
2357: }
2358:
2359: $string =~ s/^__ARRAY_REF__//;
2360:
2361: while($string !~ /^__END_ARRAY_REF__/) {
2362: my $value='';
2363: if($string =~ /^__HASH_REF__/) {
2364: ($value, $string)=&str2hashref($string);
2365: if(defined($value->{'error'})) {
2366: $array[0] ='Array reference error';
2367: return (\@array, $string);
2368: }
2369: } elsif($string =~ /^__ARRAY_REF__/) {
2370: ($value, $string)=&str2arrayref($string);
2371: if($value->[0] eq 'Array reference error') {
2372: $array[0] ='Array reference error';
2373: return (\@array, $string);
2374: }
2375: } else {
2376: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2377: }
2378: $string =~ s/^&//;
2379:
2380: push(@array, $value);
1.191 harris41 2381: }
1.265 albertel 2382:
2383: $string =~ s/^__END_ARRAY_REF__//;
2384:
2385: return (\@array, $string);
1.168 albertel 2386: }
2387:
1.167 albertel 2388: # -------------------------------------------------------------------Temp Store
2389:
1.168 albertel 2390: sub tmpreset {
2391: my ($symb,$namespace,$domain,$stuname) = @_;
2392: if (!$symb) {
2393: $symb=&symbread();
1.620 albertel 2394: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2395: }
2396: $symb=escape($symb);
2397:
1.620 albertel 2398: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 2399: $namespace=~s/\//\_/g;
2400: $namespace=~s/\W//g;
2401:
1.620 albertel 2402: if (!$domain) { $domain=$env{'user.domain'}; }
2403: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2404: if ($domain eq 'public' && $stuname eq 'public') {
2405: $stuname=$ENV{'REMOTE_ADDR'};
2406: }
1.168 albertel 2407: my $path=$perlvar{'lonDaemons'}.'/tmp';
2408: my %hash;
2409: if (tie(%hash,'GDBM_File',
2410: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2411: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2412: foreach my $key (keys %hash) {
1.180 albertel 2413: if ($key=~ /:$symb/) {
1.168 albertel 2414: delete($hash{$key});
2415: }
2416: }
2417: }
2418: }
2419:
1.167 albertel 2420: sub tmpstore {
1.168 albertel 2421: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2422:
2423: if (!$symb) {
2424: $symb=&symbread();
1.620 albertel 2425: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2426: }
2427: $symb=escape($symb);
2428:
2429: if (!$namespace) {
2430: # I don't think we would ever want to store this for a course.
2431: # it seems this will only be used if we don't have a course.
1.620 albertel 2432: #$namespace=$env{'request.course.id'};
1.168 albertel 2433: #if (!$namespace) {
1.620 albertel 2434: $namespace=$env{'request.state'};
1.168 albertel 2435: #}
2436: }
2437: $namespace=~s/\//\_/g;
2438: $namespace=~s/\W//g;
1.620 albertel 2439: if (!$domain) { $domain=$env{'user.domain'}; }
2440: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2441: if ($domain eq 'public' && $stuname eq 'public') {
2442: $stuname=$ENV{'REMOTE_ADDR'};
2443: }
1.168 albertel 2444: my $now=time;
2445: my %hash;
2446: my $path=$perlvar{'lonDaemons'}.'/tmp';
2447: if (tie(%hash,'GDBM_File',
2448: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2449: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2450: $hash{"version:$symb"}++;
2451: my $version=$hash{"version:$symb"};
2452: my $allkeys='';
2453: foreach my $key (keys(%$storehash)) {
2454: $allkeys.=$key.':';
1.591 albertel 2455: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 2456: }
2457: $hash{"$version:$symb:timestamp"}=$now;
2458: $allkeys.='timestamp';
2459: $hash{"$version:keys:$symb"}=$allkeys;
2460: if (untie(%hash)) {
2461: return 'ok';
2462: } else {
2463: return "error:$!";
2464: }
2465: } else {
2466: return "error:$!";
2467: }
2468: }
1.167 albertel 2469:
1.168 albertel 2470: # -----------------------------------------------------------------Temp Restore
1.167 albertel 2471:
1.168 albertel 2472: sub tmprestore {
2473: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 2474:
1.168 albertel 2475: if (!$symb) {
2476: $symb=&symbread();
1.620 albertel 2477: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2478: }
2479: $symb=escape($symb);
2480:
1.620 albertel 2481: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 2482:
1.620 albertel 2483: if (!$domain) { $domain=$env{'user.domain'}; }
2484: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2485: if ($domain eq 'public' && $stuname eq 'public') {
2486: $stuname=$ENV{'REMOTE_ADDR'};
2487: }
1.168 albertel 2488: my %returnhash;
2489: $namespace=~s/\//\_/g;
2490: $namespace=~s/\W//g;
2491: my %hash;
2492: my $path=$perlvar{'lonDaemons'}.'/tmp';
2493: if (tie(%hash,'GDBM_File',
2494: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2495: &GDBM_READER(),0640)) {
1.168 albertel 2496: my $version=$hash{"version:$symb"};
2497: $returnhash{'version'}=$version;
2498: my $scope;
2499: for ($scope=1;$scope<=$version;$scope++) {
2500: my $vkeys=$hash{"$scope:keys:$symb"};
2501: my @keys=split(/:/,$vkeys);
2502: my $key;
2503: $returnhash{"$scope:keys"}=$vkeys;
2504: foreach $key (@keys) {
1.591 albertel 2505: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2506: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 2507: }
2508: }
1.168 albertel 2509: if (!(untie(%hash))) {
2510: return "error:$!";
2511: }
2512: } else {
2513: return "error:$!";
2514: }
2515: return %returnhash;
1.167 albertel 2516: }
2517:
1.9 www 2518: # ----------------------------------------------------------------------- Store
2519:
2520: sub store {
1.124 www 2521: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2522: my $home='';
2523:
1.168 albertel 2524: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2525:
1.213 www 2526: $symb=&symbclean($symb);
1.122 albertel 2527: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2528:
1.620 albertel 2529: if (!$domain) { $domain=$env{'user.domain'}; }
2530: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2531:
2532: &devalidate($symb,$stuname,$domain);
1.109 www 2533:
2534: $symb=escape($symb);
1.187 www 2535: if (!$namespace) {
1.620 albertel 2536: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2537: return '';
2538: }
2539: }
1.620 albertel 2540: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2541:
2542: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2543: $$storehash{'host'}=$perlvar{'lonHostID'};
2544:
1.12 www 2545: my $namevalue='';
1.191 harris41 2546: foreach (keys %$storehash) {
1.591 albertel 2547: $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 2548: }
1.12 www 2549: $namevalue=~s/\&$//;
1.187 www 2550: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2551: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2552: }
2553:
1.47 www 2554: # -------------------------------------------------------------- Critical Store
2555:
2556: sub cstore {
1.124 www 2557: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2558: my $home='';
2559:
1.168 albertel 2560: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2561:
1.213 www 2562: $symb=&symbclean($symb);
1.122 albertel 2563: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2564:
1.620 albertel 2565: if (!$domain) { $domain=$env{'user.domain'}; }
2566: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2567:
2568: &devalidate($symb,$stuname,$domain);
1.109 www 2569:
2570: $symb=escape($symb);
1.187 www 2571: if (!$namespace) {
1.620 albertel 2572: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2573: return '';
2574: }
2575: }
1.620 albertel 2576: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2577:
2578: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2579: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2580:
1.47 www 2581: my $namevalue='';
1.191 harris41 2582: foreach (keys %$storehash) {
1.591 albertel 2583: $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 2584: }
1.47 www 2585: $namevalue=~s/\&$//;
1.187 www 2586: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2587: return critical
2588: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2589: }
2590:
1.9 www 2591: # --------------------------------------------------------------------- Restore
2592:
2593: sub restore {
1.124 www 2594: my ($symb,$namespace,$domain,$stuname) = @_;
2595: my $home='';
2596:
1.168 albertel 2597: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2598:
1.122 albertel 2599: if (!$symb) {
2600: unless ($symb=escape(&symbread())) { return ''; }
2601: } else {
1.213 www 2602: $symb=&escape(&symbclean($symb));
1.122 albertel 2603: }
1.188 www 2604: if (!$namespace) {
1.620 albertel 2605: unless ($namespace=$env{'request.course.id'}) {
1.188 www 2606: return '';
2607: }
2608: }
1.620 albertel 2609: if (!$domain) { $domain=$env{'user.domain'}; }
2610: if (!$stuname) { $stuname=$env{'user.name'}; }
2611: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 2612: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2613:
1.12 www 2614: my %returnhash=();
1.191 harris41 2615: foreach (split(/\&/,$answer)) {
1.12 www 2616: my ($name,$value)=split(/\=/,$_);
1.591 albertel 2617: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 2618: }
1.75 www 2619: my $version;
2620: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191 harris41 2621: foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75 www 2622: $returnhash{$_}=$returnhash{$version.':'.$_};
1.191 harris41 2623: }
1.75 www 2624: }
1.13 www 2625: return %returnhash;
1.34 www 2626: }
2627:
2628: # ---------------------------------------------------------- Course Description
2629:
2630: sub coursedescription {
1.731 albertel 2631: my ($courseid,$args)=@_;
1.34 www 2632: $courseid=~s/^\///;
1.49 www 2633: $courseid=~s/\_/\//g;
1.34 www 2634: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2635: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2636: my $normalid=$cdomain.'_'.$cnum;
2637: # need to always cache even if we get errors otherwise we keep
2638: # trying and trying and trying to get the course description.
2639: my %envhash=();
2640: my %returnhash=();
1.731 albertel 2641:
2642: my $expiretime=600;
2643: if ($env{'request.course.id'} eq $normalid) {
2644: $expiretime=120;
2645: }
2646:
2647: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2648: if (!$args->{'freshen_cache'}
2649: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2650: foreach my $key (keys(%env)) {
2651: next if ($key !~ /^\Q$prefix\E(.*)/);
2652: my ($setting) = $1;
2653: $returnhash{$setting} = $env{$key};
2654: }
2655: return %returnhash;
2656: }
2657:
2658: # get the data agin
2659: if (!$args->{'one_time'}) {
2660: $envhash{'course.'.$normalid.'.last_cache'}=time;
2661: }
1.34 www 2662: if ($chome ne 'no_host') {
1.302 albertel 2663: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2664: if (!exists($returnhash{'con_lost'})) {
2665: $returnhash{'home'}= $chome;
2666: $returnhash{'domain'} = $cdomain;
2667: $returnhash{'num'} = $cnum;
1.741 raeburn 2668: if (!defined($returnhash{'type'})) {
2669: $returnhash{'type'} = 'Course';
2670: }
1.130 albertel 2671: while (my ($name,$value) = each %returnhash) {
1.53 www 2672: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2673: }
1.270 www 2674: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2675: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 2676: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2677: $envhash{'course.'.$normalid.'.home'}=$chome;
2678: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2679: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2680: }
2681: }
1.731 albertel 2682: if (!$args->{'one_time'}) {
2683: &appenv(%envhash);
2684: }
1.302 albertel 2685: return %returnhash;
1.461 www 2686: }
2687:
2688: # -------------------------------------------------See if a user is privileged
2689:
2690: sub privileged {
2691: my ($username,$domain)=@_;
2692: my $rolesdump=&reply("dump:$domain:$username:roles",
2693: &homeserver($username,$domain));
2694: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2695: my $now=time;
2696: if ($rolesdump ne '') {
2697: foreach (split(/&/,$rolesdump)) {
1.586 albertel 2698: if ($_!~/^rolesdef_/) {
1.461 www 2699: my ($area,$role)=split(/=/,$_);
2700: $area=~s/\_\w\w$//;
2701: my ($trole,$tend,$tstart)=split(/_/,$role);
2702: if (($trole eq 'dc') || ($trole eq 'su')) {
2703: my $active=1;
2704: if ($tend) {
2705: if ($tend<$now) { $active=0; }
2706: }
2707: if ($tstart) {
2708: if ($tstart>$now) { $active=0; }
2709: }
2710: if ($active) { return 1; }
2711: }
2712: }
2713: }
2714: }
2715: return 0;
1.9 www 2716: }
1.1 albertel 2717:
1.103 harris41 2718: # -------------------------------------------------------- Get user privileges
1.11 www 2719:
2720: sub rolesinit {
2721: my ($domain,$username,$authhost)=@_;
2722: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 2723: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 2724: my %allroles=();
1.678 raeburn 2725: my %allgroups=();
1.11 www 2726: my $now=time;
1.743 albertel 2727: my %userroles = ('user.login.time' => $now);
1.678 raeburn 2728: my $group_privs;
1.11 www 2729:
2730: if ($rolesdump ne '') {
1.191 harris41 2731: foreach (split(/&/,$rolesdump)) {
1.586 albertel 2732: if ($_!~/^rolesdef_/) {
1.11 www 2733: my ($area,$role)=split(/=/,$_);
1.587 albertel 2734: $area=~s/\_\w\w$//;
1.678 raeburn 2735: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 2736: if ($role=~/^cr/) {
1.655 albertel 2737: if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
2738: ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
2739: ($tend,$tstart)=split('_',$trest);
2740: } else {
2741: $trole=$role;
2742: }
1.678 raeburn 2743: } elsif ($role =~ m|^gr/|) {
2744: ($trole,$tend,$tstart) = split(/_/,$role);
2745: ($trole,$group_privs) = split(/\//,$trole);
2746: $group_privs = &unescape($group_privs);
1.587 albertel 2747: } else {
2748: ($trole,$tend,$tstart)=split(/_/,$role);
2749: }
1.743 albertel 2750: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
2751: $username);
2752: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 2753: if (($tend!=0) && ($tend<$now)) { $trole=''; }
2754: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 2755: if (($area ne '') && ($trole ne '')) {
1.347 albertel 2756: my $spec=$trole.'.'.$area;
2757: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
2758: if ($trole =~ /^cr\//) {
1.567 raeburn 2759: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 2760: } elsif ($trole eq 'gr') {
2761: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 2762: } else {
1.567 raeburn 2763: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 2764: }
1.12 www 2765: }
1.662 raeburn 2766: }
1.191 harris41 2767: }
1.743 albertel 2768: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
2769: $userroles{'user.adv'} = $adv;
2770: $userroles{'user.author'} = $author;
1.620 albertel 2771: $env{'user.adv'}=$adv;
1.11 www 2772: }
1.743 albertel 2773: return \%userroles;
1.11 www 2774: }
2775:
1.567 raeburn 2776: sub set_arearole {
2777: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
2778: # log the associated role with the area
2779: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 2780: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 2781: }
2782:
2783: sub custom_roleprivs {
2784: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
2785: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
2786: my $homsvr=homeserver($rauthor,$rdomain);
2787: if ($hostname{$homsvr} ne '') {
2788: my ($rdummy,$roledef)=
2789: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
2790: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
2791: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
2792: if (defined($syspriv)) {
2793: $$allroles{'cm./'}.=':'.$syspriv;
2794: $$allroles{$spec.'./'}.=':'.$syspriv;
2795: }
2796: if ($tdomain ne '') {
2797: if (defined($dompriv)) {
2798: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
2799: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
2800: }
2801: if (($trest ne '') && (defined($coursepriv))) {
2802: $$allroles{'cm.'.$area}.=':'.$coursepriv;
2803: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
2804: }
2805: }
2806: }
2807: }
2808: }
2809:
1.678 raeburn 2810: sub group_roleprivs {
2811: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
2812: my $access = 1;
2813: my $now = time;
2814: if (($tend!=0) && ($tend<$now)) { $access = 0; }
2815: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
2816: if ($access) {
2817: my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
2818: $$allgroups{$course}{$group} .=':'.$group_privs;
2819: }
2820: }
1.567 raeburn 2821:
2822: sub standard_roleprivs {
2823: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
2824: if (defined($pr{$trole.':s'})) {
2825: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
2826: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
2827: }
2828: if ($tdomain ne '') {
2829: if (defined($pr{$trole.':d'})) {
2830: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2831: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
2832: }
2833: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
2834: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
2835: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
2836: }
2837: }
2838: }
2839:
2840: sub set_userprivs {
1.678 raeburn 2841: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 2842: my $author=0;
2843: my $adv=0;
1.678 raeburn 2844: my %grouproles = ();
2845: if (keys(%{$allgroups}) > 0) {
2846: foreach my $role (keys %{$allroles}) {
1.681 raeburn 2847: my ($trole,$area,$sec,$extendedarea);
1.771 raeburn 2848: if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678 raeburn 2849: $trole = $1;
2850: $area = $2;
1.681 raeburn 2851: $sec = $3;
2852: $extendedarea = $area.$sec;
2853: if (exists($$allgroups{$area})) {
2854: foreach my $group (keys(%{$$allgroups{$area}})) {
2855: my $spec = $trole.'.'.$extendedarea;
2856: $grouproles{$spec.'.'.$area.'/'.$group} =
2857: $$allgroups{$area}{$group};
1.678 raeburn 2858: }
2859: }
2860: }
2861: }
2862: }
2863: foreach (keys(%grouproles)) {
2864: $$allroles{$_} = $grouproles{$_};
2865: }
1.567 raeburn 2866: foreach (keys %{$allroles}) {
2867: my %thesepriv=();
2868: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
2869: foreach (split(/:/,$$allroles{$_})) {
2870: if ($_ ne '') {
2871: my ($privilege,$restrictions)=split(/&/,$_);
2872: if ($restrictions eq '') {
2873: $thesepriv{$privilege}='F';
2874: } elsif ($thesepriv{$privilege} ne 'F') {
2875: $thesepriv{$privilege}.=$restrictions;
2876: }
2877: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
2878: }
2879: }
2880: my $thesestr='';
2881: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743 albertel 2882: $userroles->{'user.priv.'.$_} = $thesestr;
1.567 raeburn 2883: }
2884: return ($author,$adv);
2885: }
2886:
1.12 www 2887: # --------------------------------------------------------------- get interface
2888:
2889: sub get {
1.131 albertel 2890: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 2891: my $items='';
1.191 harris41 2892: foreach (@$storearr) {
1.12 www 2893: $items.=escape($_).'&';
1.191 harris41 2894: }
1.12 www 2895: $items=~s/\&$//;
1.620 albertel 2896: if (!$udomain) { $udomain=$env{'user.domain'}; }
2897: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 2898: my $uhome=&homeserver($uname,$udomain);
2899:
1.133 albertel 2900: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2901: my @pairs=split(/\&/,$rep);
1.273 albertel 2902: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
2903: return @pairs;
2904: }
1.15 www 2905: my %returnhash=();
1.42 www 2906: my $i=0;
1.191 harris41 2907: foreach (@$storearr) {
1.557 albertel 2908: $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42 www 2909: $i++;
1.191 harris41 2910: }
1.15 www 2911: return %returnhash;
1.27 www 2912: }
2913:
2914: # --------------------------------------------------------------- del interface
2915:
2916: sub del {
1.133 albertel 2917: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 2918: my $items='';
1.191 harris41 2919: foreach (@$storearr) {
1.27 www 2920: $items.=escape($_).'&';
1.191 harris41 2921: }
1.27 www 2922: $items=~s/\&$//;
1.620 albertel 2923: if (!$udomain) { $udomain=$env{'user.domain'}; }
2924: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 2925: my $uhome=&homeserver($uname,$udomain);
2926:
2927: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 2928: }
2929:
2930: # -------------------------------------------------------------- dump interface
2931:
2932: sub dump {
1.755 albertel 2933: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
2934: if (!$udomain) { $udomain=$env{'user.domain'}; }
2935: if (!$uname) { $uname=$env{'user.name'}; }
2936: my $uhome=&homeserver($uname,$udomain);
2937: if ($regexp) {
2938: $regexp=&escape($regexp);
2939: } else {
2940: $regexp='.';
2941: }
2942: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
2943: my @pairs=split(/\&/,$rep);
2944: my %returnhash=();
2945: foreach my $item (@pairs) {
2946: my ($key,$value)=split(/=/,$item,2);
2947: $key = &unescape($key);
2948: next if ($key =~ /^error: 2 /);
2949: $returnhash{$key}=&thaw_unescape($value);
2950: }
2951: return %returnhash;
1.407 www 2952: }
2953:
1.717 albertel 2954: # --------------------------------------------------------- dumpstore interface
2955:
2956: sub dumpstore {
2957: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
2958: return &dump($namespace,$udomain,$uname,$regexp,$range);
2959: }
2960:
1.407 www 2961: # -------------------------------------------------------------- keys interface
2962:
2963: sub getkeys {
2964: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 2965: if (!$udomain) { $udomain=$env{'user.domain'}; }
2966: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 2967: my $uhome=&homeserver($uname,$udomain);
2968: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
2969: my @keyarray=();
2970: foreach (split(/\&/,$rep)) {
2971: push (@keyarray,&unescape($_));
2972: }
2973: return @keyarray;
1.318 matthew 2974: }
2975:
1.319 matthew 2976: # --------------------------------------------------------------- currentdump
2977: sub currentdump {
1.328 matthew 2978: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 2979: $courseid = $env{'request.course.id'} if (! defined($courseid));
2980: $sdom = $env{'user.domain'} if (! defined($sdom));
2981: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 2982: my $uhome = &homeserver($sname,$sdom);
2983: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 2984: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 2985: #
1.318 matthew 2986: my %returnhash=();
1.319 matthew 2987: #
2988: if ($rep eq "unknown_cmd") {
2989: # an old lond will not know currentdump
2990: # Do a dump and make it look like a currentdump
1.326 matthew 2991: my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319 matthew 2992: return if ($tmp[0] =~ /^(error:|no_such_host)/);
2993: my %hash = @tmp;
2994: @tmp=();
1.424 matthew 2995: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 2996: } else {
2997: my @pairs=split(/\&/,$rep);
2998: foreach (@pairs) {
2999: my ($key,$value)=split(/=/,$_);
3000: my ($symb,$param) = split(/:/,$key);
3001: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3002: &thaw_unescape($value);
1.319 matthew 3003: }
1.191 harris41 3004: }
1.12 www 3005: return %returnhash;
1.424 matthew 3006: }
3007:
3008: sub convert_dump_to_currentdump{
3009: my %hash = %{shift()};
3010: my %returnhash;
3011: # Code ripped from lond, essentially. The only difference
3012: # here is the unescaping done by lonnet::dump(). Conceivably
3013: # we might run in to problems with parameter names =~ /^v\./
3014: while (my ($key,$value) = each(%hash)) {
3015: my ($v,$symb,$param) = split(/:/,$key);
3016: next if ($v eq 'version' || $symb eq 'keys');
3017: next if (exists($returnhash{$symb}) &&
3018: exists($returnhash{$symb}->{$param}) &&
3019: $returnhash{$symb}->{'v.'.$param} > $v);
3020: $returnhash{$symb}->{$param}=$value;
3021: $returnhash{$symb}->{'v.'.$param}=$v;
3022: }
3023: #
3024: # Remove all of the keys in the hashes which keep track of
3025: # the version of the parameter.
3026: while (my ($symb,$param_hash) = each(%returnhash)) {
3027: # use a foreach because we are going to delete from the hash.
3028: foreach my $key (keys(%$param_hash)) {
3029: delete($param_hash->{$key}) if ($key =~ /^v\./);
3030: }
3031: }
3032: return \%returnhash;
1.12 www 3033: }
3034:
1.627 albertel 3035: # ------------------------------------------------------ critical inc interface
3036:
3037: sub cinc {
3038: return &inc(@_,'critical');
3039: }
3040:
1.449 matthew 3041: # --------------------------------------------------------------- inc interface
3042:
3043: sub inc {
1.627 albertel 3044: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3045: if (!$udomain) { $udomain=$env{'user.domain'}; }
3046: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3047: my $uhome=&homeserver($uname,$udomain);
3048: my $items='';
3049: if (! ref($store)) {
3050: # got a single value, so use that instead
3051: $items = &escape($store).'=&';
3052: } elsif (ref($store) eq 'SCALAR') {
3053: $items = &escape($$store).'=&';
3054: } elsif (ref($store) eq 'ARRAY') {
3055: $items = join('=&',map {&escape($_);} @{$store});
3056: } elsif (ref($store) eq 'HASH') {
3057: while (my($key,$value) = each(%{$store})) {
3058: $items.= &escape($key).'='.&escape($value).'&';
3059: }
3060: }
3061: $items=~s/\&$//;
1.627 albertel 3062: if ($critical) {
3063: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3064: } else {
3065: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3066: }
1.449 matthew 3067: }
3068:
1.12 www 3069: # --------------------------------------------------------------- put interface
3070:
3071: sub put {
1.134 albertel 3072: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3073: if (!$udomain) { $udomain=$env{'user.domain'}; }
3074: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3075: my $uhome=&homeserver($uname,$udomain);
1.12 www 3076: my $items='';
1.191 harris41 3077: foreach (keys %$storehash) {
1.557 albertel 3078: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 3079: }
1.12 www 3080: $items=~s/\&$//;
1.134 albertel 3081: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3082: }
3083:
1.631 albertel 3084: # ------------------------------------------------------------ newput interface
3085:
3086: sub newput {
3087: my ($namespace,$storehash,$udomain,$uname)=@_;
3088: if (!$udomain) { $udomain=$env{'user.domain'}; }
3089: if (!$uname) { $uname=$env{'user.name'}; }
3090: my $uhome=&homeserver($uname,$udomain);
3091: my $items='';
3092: foreach my $key (keys(%$storehash)) {
3093: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3094: }
3095: $items=~s/\&$//;
3096: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3097: }
3098:
3099: # --------------------------------------------------------- putstore interface
3100:
1.524 raeburn 3101: sub putstore {
1.715 albertel 3102: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3103: if (!$udomain) { $udomain=$env{'user.domain'}; }
3104: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3105: my $uhome=&homeserver($uname,$udomain);
3106: my $items='';
1.715 albertel 3107: foreach my $key (keys(%$storehash)) {
3108: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3109: }
1.715 albertel 3110: $items=~s/\&$//;
1.716 albertel 3111: my $esc_symb=&escape($symb);
3112: my $esc_v=&escape($version);
1.715 albertel 3113: my $reply =
1.716 albertel 3114: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3115: $uhome);
3116: if ($reply eq 'unknown_cmd') {
1.716 albertel 3117: # gfall back to way things use to be done
1.715 albertel 3118: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3119: $uname);
1.524 raeburn 3120: }
1.715 albertel 3121: return $reply;
3122: }
3123:
3124: sub old_putstore {
1.716 albertel 3125: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3126: if (!$udomain) { $udomain=$env{'user.domain'}; }
3127: if (!$uname) { $uname=$env{'user.name'}; }
3128: my $uhome=&homeserver($uname,$udomain);
3129: my %newstorehash;
3130: foreach (keys %$storehash) {
3131: my $key = $version.':'.&escape($symb).':'.$_;
3132: $newstorehash{$key} = $storehash->{$_};
3133: }
3134: my $items='';
3135: my %allitems = ();
3136: foreach (keys %newstorehash) {
3137: if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
3138: my $key = $1.':keys:'.$2;
3139: $allitems{$key} .= $3.':';
3140: }
3141: $items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
3142: }
3143: foreach (keys %allitems) {
3144: $allitems{$_} =~ s/\:$//;
3145: $items.= $_.'='.$allitems{$_}.'&';
3146: }
3147: $items=~s/\&$//;
3148: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3149: }
3150:
1.47 www 3151: # ------------------------------------------------------ critical put interface
3152:
3153: sub cput {
1.134 albertel 3154: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3155: if (!$udomain) { $udomain=$env{'user.domain'}; }
3156: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3157: my $uhome=&homeserver($uname,$udomain);
1.47 www 3158: my $items='';
1.191 harris41 3159: foreach (keys %$storehash) {
1.715 albertel 3160: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191 harris41 3161: }
1.47 www 3162: $items=~s/\&$//;
1.134 albertel 3163: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3164: }
3165:
3166: # -------------------------------------------------------------- eget interface
3167:
3168: sub eget {
1.133 albertel 3169: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3170: my $items='';
1.191 harris41 3171: foreach (@$storearr) {
1.12 www 3172: $items.=escape($_).'&';
1.191 harris41 3173: }
1.12 www 3174: $items=~s/\&$//;
1.620 albertel 3175: if (!$udomain) { $udomain=$env{'user.domain'}; }
3176: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3177: my $uhome=&homeserver($uname,$udomain);
3178: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3179: my @pairs=split(/\&/,$rep);
3180: my %returnhash=();
1.42 www 3181: my $i=0;
1.191 harris41 3182: foreach (@$storearr) {
1.557 albertel 3183: $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42 www 3184: $i++;
1.191 harris41 3185: }
1.12 www 3186: return %returnhash;
3187: }
3188:
1.667 albertel 3189: # ------------------------------------------------------------ tmpput interface
3190: sub tmpput {
3191: my ($storehash,$server)=@_;
3192: my $items='';
3193: foreach (keys(%$storehash)) {
3194: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
3195: }
3196: $items=~s/\&$//;
3197: return &reply("tmpput:$items",$server);
3198: }
3199:
3200: # ------------------------------------------------------------ tmpget interface
3201: sub tmpget {
1.688 albertel 3202: my ($token,$server)=@_;
3203: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3204: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3205: my %returnhash;
3206: foreach my $item (split(/\&/,$rep)) {
3207: my ($key,$value)=split(/=/,$item);
3208: $returnhash{&unescape($key)}=&thaw_unescape($value);
3209: }
3210: return %returnhash;
3211: }
3212:
1.688 albertel 3213: # ------------------------------------------------------------ tmpget interface
3214: sub tmpdel {
3215: my ($token,$server)=@_;
3216: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3217: return &reply("tmpdel:$token",$server);
3218: }
3219:
1.765 albertel 3220: # -------------------------------------------------- portfolio access checking
3221:
3222: sub portfolio_access {
1.766 albertel 3223: my ($requrl) = @_;
1.765 albertel 3224: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3225: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
3226: if ($result eq 'ok') {
1.766 albertel 3227: return 'F';
1.765 albertel 3228: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3229: return 'A';
1.765 albertel 3230: }
1.766 albertel 3231: return '';
1.765 albertel 3232: }
3233:
3234: sub get_portfolio_access {
1.767 albertel 3235: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3236:
3237: if (!ref($access_hash)) {
3238: my $current_perms = &get_portfile_permissions($udom,$unum);
3239: my %access_controls = &get_access_controls($current_perms,$group,
3240: $file_name);
3241: $access_hash = $access_controls{$file_name};
3242: }
3243:
1.765 albertel 3244: my ($public,$guest,@domains,@users,@courses,@groups);
3245: my $now = time;
3246: if (ref($access_hash) eq 'HASH') {
3247: foreach my $key (keys(%{$access_hash})) {
3248: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3249: if ($start > $now) {
3250: next;
3251: }
3252: if ($end && $end<$now) {
3253: next;
3254: }
3255: if ($scope eq 'public') {
3256: $public = $key;
3257: last;
3258: } elsif ($scope eq 'guest') {
3259: $guest = $key;
3260: } elsif ($scope eq 'domains') {
3261: push(@domains,$key);
3262: } elsif ($scope eq 'users') {
3263: push(@users,$key);
3264: } elsif ($scope eq 'course') {
3265: push(@courses,$key);
3266: } elsif ($scope eq 'group') {
3267: push(@groups,$key);
3268: }
3269: }
3270: if ($public) {
3271: return 'ok';
3272: }
3273: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3274: if ($guest) {
3275: return $guest;
3276: }
3277: } else {
3278: if (@domains > 0) {
3279: foreach my $domkey (@domains) {
3280: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3281: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3282: return 'ok';
3283: }
3284: }
3285: }
3286: }
3287: if (@users > 0) {
3288: foreach my $userkey (@users) {
3289: if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
3290: return 'ok';
3291: }
3292: }
3293: }
3294: my %roleshash;
3295: my @courses_and_groups = @courses;
3296: push(@courses_and_groups,@groups);
3297: if (@courses_and_groups > 0) {
3298: my (%allgroups,%allroles);
3299: my ($start,$end,$role,$sec,$group);
3300: foreach my $envkey (%env) {
3301: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
3302: my $cid = $2.'_'.$3;
3303: if ($1 eq 'gr') {
3304: $group = $4;
3305: $allgroups{$cid}{$group} = $env{$envkey};
3306: } else {
3307: if ($4 eq '') {
3308: $sec = 'none';
3309: } else {
3310: $sec = $4;
3311: }
3312: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3313: }
3314: } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
3315: my $cid = $2.'_'.$3;
3316: if ($4 eq '') {
3317: $sec = 'none';
3318: } else {
3319: $sec = $4;
3320: }
3321: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3322: }
3323: }
3324: if (keys(%allroles) == 0) {
3325: return;
3326: }
3327: foreach my $key (@courses_and_groups) {
3328: my %content = %{$$access_hash{$key}};
3329: my $cnum = $content{'number'};
3330: my $cdom = $content{'domain'};
3331: my $cid = $cdom.'_'.$cnum;
3332: if (!exists($allroles{$cid})) {
3333: next;
3334: }
3335: foreach my $role_id (keys(%{$content{'roles'}})) {
3336: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3337: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3338: my @status = @{$content{'roles'}{$role_id}{'access'}};
3339: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3340: foreach my $role (keys(%{$allroles{$cid}})) {
3341: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3342: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3343: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3344: if (grep/^all$/,@sections) {
3345: return 'ok';
3346: } else {
3347: if (grep/^$sec$/,@sections) {
3348: return 'ok';
3349: }
3350: }
3351: }
3352: }
3353: if (keys(%{$allgroups{$cid}}) == 0) {
3354: if (grep/^none$/,@groups) {
3355: return 'ok';
3356: }
3357: } else {
3358: if (grep/^all$/,@groups) {
3359: return 'ok';
3360: }
3361: foreach my $group (keys(%{$allgroups{$cid}})) {
3362: if (grep/^$group$/,@groups) {
3363: return 'ok';
3364: }
3365: }
3366: }
3367: }
3368: }
3369: }
3370: }
3371: }
3372: if ($guest) {
3373: return $guest;
3374: }
3375: }
3376: }
3377: return;
3378: }
3379:
3380: sub course_group_datechecker {
3381: my ($dates,$now,$status) = @_;
3382: my ($start,$end) = split(/\./,$dates);
3383: if (!$start && !$end) {
3384: return 'ok';
3385: }
3386: if (grep/^active$/,@{$status}) {
3387: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3388: return 'ok';
3389: }
3390: }
3391: if (grep/^previous$/,@{$status}) {
3392: if ($end > $now ) {
3393: return 'ok';
3394: }
3395: }
3396: if (grep/^future$/,@{$status}) {
3397: if ($start > $now) {
3398: return 'ok';
3399: }
3400: }
3401: return;
3402: }
3403:
3404: sub parse_portfolio_url {
3405: my ($url) = @_;
3406:
3407: my ($type,$udom,$unum,$group,$file_name);
3408:
3409: if ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
3410: $type = 1;
3411: $udom = $1;
3412: $unum = $2;
3413: $file_name = $3;
3414: } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
3415: $type = 2;
3416: $udom = $1;
3417: $unum = $2;
3418: $group = $3;
3419: $file_name = $3.'/'.$4;
3420: }
3421: if (wantarray) {
3422: return ($type,$udom,$unum,$file_name,$group);
3423: }
3424: return $type;
3425: }
3426:
3427: sub is_portfolio_url {
3428: my ($url) = @_;
3429: return scalar(&parse_portfolio_url($url));
3430: }
3431:
1.341 www 3432: # ---------------------------------------------- Custom access rule evaluation
3433:
3434: sub customaccess {
3435: my ($priv,$uri)=@_;
1.620 albertel 3436: my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343 www 3437: $urealm=~s/^\W//;
3438: my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341 www 3439: my $access=0;
3440: foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342 www 3441: my ($effect,$realm,$role)=split(/\:/,$_);
1.343 www 3442: if ($role) {
3443: if ($role ne $urole) { next; }
3444: }
3445: foreach (split(/\s*\,\s*/,$realm)) {
3446: my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
3447: if ($tdom) {
3448: if ($tdom ne $udom) { next; }
3449: }
3450: if ($tcrs) {
3451: if ($tcrs ne $ucrs) { next; }
3452: }
3453: if ($tsec) {
3454: if ($tsec ne $usec) { next; }
3455: }
3456: $access=($effect eq 'allow');
3457: last;
1.342 www 3458: }
1.402 bowersj2 3459: if ($realm eq '' && $role eq '') {
3460: $access=($effect eq 'allow');
3461: }
1.341 www 3462: }
3463: return $access;
3464: }
3465:
1.103 harris41 3466: # ------------------------------------------------- Check for a user privilege
1.12 www 3467:
3468: sub allowed {
1.579 albertel 3469: my ($priv,$uri,$symb)=@_;
1.705 albertel 3470: my $ver_orguri=$uri;
1.439 www 3471: $uri=&deversion($uri);
1.152 www 3472: my $orguri=$uri;
1.52 www 3473: $uri=&declutter($uri);
1.545 banghart 3474:
1.620 albertel 3475: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 3476: # Free bre access to adm and meta resources
1.775 albertel 3477: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 3478: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3479: && ($priv eq 'bre')) {
1.14 www 3480: return 'F';
1.159 www 3481: }
3482:
1.545 banghart 3483: # Free bre access to user's own portfolio contents
1.714 raeburn 3484: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 3485: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 3486: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545 banghart 3487: return 'F';
3488: }
3489:
1.762 raeburn 3490: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 3491: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3492: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3493: if (exists($env{'request.course.id'})) {
3494: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3495: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3496: if (($domain eq $cdom) && ($name eq $cnum)) {
3497: my $courseprivid=$env{'request.course.id'};
3498: $courseprivid=~s/\_/\//;
3499: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3500: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3501: return $1;
1.762 raeburn 3502: } else {
3503: if ($env{'request.course.sec'}) {
3504: $courseprivid.='/'.$env{'request.course.sec'};
3505: }
3506: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3507: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3508: return $2;
3509: }
1.714 raeburn 3510: }
3511: }
3512: }
3513: }
3514:
1.159 www 3515: # Free bre to public access
3516:
3517: if ($priv eq 'bre') {
1.238 www 3518: my $copyright=&metadata($uri,'copyright');
1.620 albertel 3519: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 3520: return 'F';
3521: }
1.238 www 3522: if ($copyright eq 'priv') {
3523: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3524: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 3525: return '';
3526: }
3527: }
3528: if ($copyright eq 'domain') {
3529: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3530: unless (($env{'user.domain'} eq $1) ||
3531: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 3532: return '';
3533: }
1.262 matthew 3534: }
1.620 albertel 3535: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 3536: # Library role, so allow browsing of resources in this domain.
3537: return 'F';
1.238 www 3538: }
1.341 www 3539: if ($copyright eq 'custom') {
3540: unless (&customaccess($priv,$uri)) { return ''; }
3541: }
1.14 www 3542: }
1.264 matthew 3543: # Domain coordinator is trying to create a course
1.620 albertel 3544: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 3545: # uri is the requested domain in this case.
3546: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 3547: # a role of dc for the domain in question.
1.620 albertel 3548: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 3549: }
1.29 www 3550:
1.52 www 3551: my $thisallowed='';
3552: my $statecond=0;
3553: my $courseprivid='';
3554:
3555: # Course
3556:
1.620 albertel 3557: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3558: $thisallowed.=$1;
3559: }
1.29 www 3560:
1.52 www 3561: # Domain
3562:
1.620 albertel 3563: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 3564: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3565: $thisallowed.=$1;
3566: }
1.52 www 3567:
3568: # Course: uri itself is a course
1.66 www 3569: my $courseuri=$uri;
3570: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 3571: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 3572:
1.620 albertel 3573: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 3574: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3575: $thisallowed.=$1;
3576: }
1.29 www 3577:
1.665 albertel 3578: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 3579: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 3580: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 3581: $thisallowed='';
1.671 raeburn 3582: my ($match)=&is_on_map($uri);
3583: if ($match) {
3584: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3585: =~/\Q$priv\E\&([^\:]*)/) {
3586: $thisallowed.=$1;
3587: }
3588: } else {
1.705 albertel 3589: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 3590: if ($refuri) {
3591: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 3592: $thisallowed='F';
1.671 raeburn 3593: } else {
3594: $refuri=&declutter($refuri);
3595: my ($match) = &is_on_map($refuri);
3596: if ($match) {
3597: $thisallowed='F';
3598: }
1.669 raeburn 3599: }
1.671 raeburn 3600: }
3601: }
1.314 www 3602: }
1.492 albertel 3603:
1.766 albertel 3604: if ($priv eq 'bre'
3605: && $thisallowed ne 'F'
3606: && $thisallowed ne '2'
3607: && &is_portfolio_url($uri)) {
3608: $thisallowed = &portfolio_access($uri);
3609: }
3610:
1.52 www 3611: # Full access at system, domain or course-wide level? Exit.
1.29 www 3612:
3613: if ($thisallowed=~/F/) {
3614: return 'F';
3615: }
3616:
1.52 www 3617: # If this is generating or modifying users, exit with special codes
1.29 www 3618:
1.643 www 3619: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3620: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 3621: my ($audom,$auname)=split('/',$uri);
1.643 www 3622: # no author name given, so this just checks on the general right to make a co-author in this domain
3623: unless ($auname) { return $thisallowed; }
3624: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 3625: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3626: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3627: ($audom ne $env{'request.role.domain'}))) { return ''; }
3628: }
1.52 www 3629: return $thisallowed;
3630: }
3631: #
1.103 harris41 3632: # Gathered so far: system, domain and course wide privileges
1.52 www 3633: #
3634: # Course: See if uri or referer is an individual resource that is part of
3635: # the course
3636:
1.620 albertel 3637: if ($env{'request.course.id'}) {
1.232 www 3638:
1.620 albertel 3639: $courseprivid=$env{'request.course.id'};
3640: if ($env{'request.course.sec'}) {
3641: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 3642: }
3643: $courseprivid=~s/\_/\//;
3644: my $checkreferer=1;
1.232 www 3645: my ($match,$cond)=&is_on_map($uri);
3646: if ($match) {
3647: $statecond=$cond;
1.620 albertel 3648: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 3649: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3650: $thisallowed.=$1;
3651: $checkreferer=0;
3652: }
1.29 www 3653: }
1.83 www 3654:
1.148 www 3655: if ($checkreferer) {
1.620 albertel 3656: my $refuri=$env{'httpref.'.$orguri};
1.148 www 3657: unless ($refuri) {
1.620 albertel 3658: foreach (keys %env) {
1.148 www 3659: if ($_=~/^httpref\..*\*/) {
3660: my $pattern=$_;
1.156 www 3661: $pattern=~s/^httpref\.\/res\///;
1.148 www 3662: $pattern=~s/\*/\[\^\/\]\+/g;
3663: $pattern=~s/\//\\\//g;
1.152 www 3664: if ($orguri=~/$pattern/) {
1.620 albertel 3665: $refuri=$env{$_};
1.148 www 3666: }
3667: }
1.191 harris41 3668: }
1.148 www 3669: }
1.232 www 3670:
1.148 www 3671: if ($refuri) {
1.152 www 3672: $refuri=&declutter($refuri);
1.232 www 3673: my ($match,$cond)=&is_on_map($refuri);
3674: if ($match) {
3675: my $refstatecond=$cond;
1.620 albertel 3676: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 3677: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3678: $thisallowed.=$1;
1.53 www 3679: $uri=$refuri;
3680: $statecond=$refstatecond;
1.52 www 3681: }
3682: }
1.148 www 3683: }
1.29 www 3684: }
1.52 www 3685: }
1.29 www 3686:
1.52 www 3687: #
1.103 harris41 3688: # Gathered now: all privileges that could apply, and condition number
1.52 www 3689: #
3690: #
3691: # Full or no access?
3692: #
1.29 www 3693:
1.52 www 3694: if ($thisallowed=~/F/) {
3695: return 'F';
3696: }
1.29 www 3697:
1.52 www 3698: unless ($thisallowed) {
3699: return '';
3700: }
1.29 www 3701:
1.52 www 3702: # Restrictions exist, deal with them
3703: #
3704: # C:according to course preferences
3705: # R:according to resource settings
3706: # L:unless locked
3707: # X:according to user session state
3708: #
3709:
3710: # Possibly locked functionality, check all courses
1.54 www 3711: # Locks might take effect only after 10 minutes cache expiration for other
3712: # courses, and 2 minutes for current course
1.52 www 3713:
3714: my $envkey;
3715: if ($thisallowed=~/L/) {
1.620 albertel 3716: foreach $envkey (keys %env) {
1.54 www 3717: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
3718: my $courseid=$2;
3719: my $roleid=$1.'.'.$2;
1.92 www 3720: $courseid=~s/^\///;
1.54 www 3721: my $expiretime=600;
1.620 albertel 3722: if ($env{'request.role'} eq $roleid) {
1.54 www 3723: $expiretime=120;
3724: }
3725: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
3726: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 3727: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 3728: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 3729: }
1.620 albertel 3730: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
3731: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
3732: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
3733: &log($env{'user.domain'},$env{'user.name'},
3734: $env{'user.home'},
1.57 www 3735: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 3736: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 3737: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 3738: return '';
3739: }
3740: }
1.620 albertel 3741: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
3742: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
3743: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
3744: &log($env{'user.domain'},$env{'user.name'},
3745: $env{'user.home'},
1.57 www 3746: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 3747: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 3748: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 3749: return '';
3750: }
3751: }
3752: }
1.29 www 3753: }
1.52 www 3754: }
3755:
3756: #
3757: # Rest of the restrictions depend on selected course
3758: #
3759:
1.620 albertel 3760: unless ($env{'request.course.id'}) {
1.766 albertel 3761: if ($thisallowed eq 'A') {
3762: return 'A';
3763: } else {
3764: return '1';
3765: }
1.52 www 3766: }
1.29 www 3767:
1.52 www 3768: #
3769: # Now user is definitely in a course
3770: #
1.53 www 3771:
3772:
3773: # Course preferences
3774:
3775: if ($thisallowed=~/C/) {
1.620 albertel 3776: my $rolecode=(split(/\./,$env{'request.role'}))[0];
3777: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
3778: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 3779: =~/\Q$rolecode\E/) {
1.689 albertel 3780: if ($priv ne 'pch') {
3781: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3782: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
3783: $env{'request.course.id'});
3784: }
1.237 www 3785: return '';
3786: }
3787:
1.620 albertel 3788: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 3789: =~/\Q$unamedom\E/) {
1.689 albertel 3790: if ($priv ne 'pch') {
3791: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
3792: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
3793: $env{'request.course.id'});
3794: }
1.54 www 3795: return '';
3796: }
1.53 www 3797: }
3798:
3799: # Resource preferences
3800:
3801: if ($thisallowed=~/R/) {
1.620 albertel 3802: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 3803: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 3804: if ($priv ne 'pch') {
3805: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
3806: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
3807: }
3808: return '';
1.54 www 3809: }
1.53 www 3810: }
1.30 www 3811:
1.246 www 3812: # Restricted by state or randomout?
1.30 www 3813:
1.52 www 3814: if ($thisallowed=~/X/) {
1.620 albertel 3815: if ($env{'acc.randomout'}) {
1.579 albertel 3816: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 3817: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 3818: return '';
3819: }
1.247 www 3820: }
3821: if (&condval($statecond)) {
1.52 www 3822: return '2';
3823: } else {
3824: return '';
3825: }
3826: }
1.30 www 3827:
1.766 albertel 3828: if ($thisallowed eq 'A') {
3829: return 'A';
3830: }
1.52 www 3831: return 'F';
1.232 www 3832: }
3833:
1.710 albertel 3834: sub split_uri_for_cond {
3835: my $uri=&deversion(&declutter(shift));
3836: my @uriparts=split(/\//,$uri);
3837: my $filename=pop(@uriparts);
3838: my $pathname=join('/',@uriparts);
3839: return ($pathname,$filename);
3840: }
1.232 www 3841: # --------------------------------------------------- Is a resource on the map?
3842:
3843: sub is_on_map {
1.710 albertel 3844: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 3845: #Trying to find the conditional for the file
1.620 albertel 3846: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 3847: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 3848: if ($match) {
1.289 bowersj2 3849: return (1,$1);
3850: } else {
1.434 www 3851: return (0,0);
1.289 bowersj2 3852: }
1.12 www 3853: }
3854:
1.427 www 3855: # --------------------------------------------------------- Get symb from alias
3856:
3857: sub get_symb_from_alias {
3858: my $symb=shift;
3859: my ($map,$resid,$url)=&decode_symb($symb);
3860: # Already is a symb
3861: if ($url) { return $symb; }
3862: # Must be an alias
3863: my $aliassymb='';
3864: my %bighash;
1.620 albertel 3865: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 3866: &GDBM_READER(),0640)) {
3867: my $rid=$bighash{'mapalias_'.$symb};
3868: if ($rid) {
3869: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 3870: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
3871: $resid,$bighash{'src_'.$rid});
1.427 www 3872: }
3873: untie %bighash;
3874: }
3875: return $aliassymb;
3876: }
3877:
1.12 www 3878: # ----------------------------------------------------------------- Define Role
3879:
3880: sub definerole {
3881: if (allowed('mcr','/')) {
3882: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392 www 3883: foreach (split(':',$sysrole)) {
1.21 www 3884: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3885: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
3886: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
3887: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 3888: return "refused:s:$crole&$cqual";
3889: }
3890: }
1.191 harris41 3891: }
1.392 www 3892: foreach (split(':',$domrole)) {
1.21 www 3893: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3894: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
3895: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
3896: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 3897: return "refused:d:$crole&$cqual";
3898: }
3899: }
1.191 harris41 3900: }
1.392 www 3901: foreach (split(':',$courole)) {
1.21 www 3902: my ($crole,$cqual)=split(/\&/,$_);
1.479 albertel 3903: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
3904: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
3905: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 3906: return "refused:c:$crole&$cqual";
3907: }
3908: }
1.191 harris41 3909: }
1.620 albertel 3910: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
3911: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 3912: "rolesdef_$rolename=".
3913: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 3914: return reply($command,$env{'user.home'});
1.12 www 3915: } else {
3916: return 'refused';
3917: }
1.105 harris41 3918: }
3919:
3920: # ---------------- Make a metadata query against the network of library servers
3921:
3922: sub metadata_query {
1.244 matthew 3923: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 3924: my %rhash;
1.244 matthew 3925: my @server_list = (defined($server_array) ? @$server_array
3926: : keys(%libserv) );
3927: for my $server (@server_list) {
1.118 harris41 3928: unless ($custom or $customshow) {
3929: my $reply=&reply("querysend:".&escape($query),$server);
3930: $rhash{$server}=$reply;
3931: }
3932: else {
3933: my $reply=&reply("querysend:".&escape($query).':'.
3934: &escape($custom).':'.&escape($customshow),
3935: $server);
3936: $rhash{$server}=$reply;
3937: }
1.112 harris41 3938: }
1.118 harris41 3939: return \%rhash;
1.240 www 3940: }
3941:
3942: # ----------------------------------------- Send log queries and wait for reply
3943:
3944: sub log_query {
3945: my ($uname,$udom,$query,%filters)=@_;
3946: my $uhome=&homeserver($uname,$udom);
3947: if ($uhome eq 'no_host') { return 'error: no_host'; }
3948: my $uhost=$hostname{$uhome};
1.241 www 3949: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240 www 3950: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
3951: $uhome);
1.479 albertel 3952: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 3953: return get_query_reply($queryid);
3954: }
3955:
1.508 raeburn 3956: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 3957:
3958: sub fetch_enrollment_query {
1.511 raeburn 3959: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 3960: my $homeserver;
1.547 raeburn 3961: my $maxtries = 1;
1.508 raeburn 3962: if ($context eq 'automated') {
3963: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 3964: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 3965: } else {
3966: $homeserver = &homeserver($cnum,$dom);
3967: }
1.506 raeburn 3968: my $host=$hostname{$homeserver};
3969: my $cmd = '';
3970: foreach (keys %{$affiliatesref}) {
1.508 raeburn 3971: $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506 raeburn 3972: }
3973: $cmd =~ s/%%$//;
3974: $cmd = &escape($cmd);
3975: my $query = 'fetchenrollment';
1.620 albertel 3976: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 3977: unless ($queryid=~/^\Q$host\E\_/) {
3978: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
3979: return 'error: '.$queryid;
3980: }
1.506 raeburn 3981: my $reply = &get_query_reply($queryid);
1.547 raeburn 3982: my $tries = 1;
3983: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
3984: $reply = &get_query_reply($queryid);
3985: $tries ++;
3986: }
1.526 raeburn 3987: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 3988: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 3989: } else {
1.515 raeburn 3990: my @responses = split/:/,$reply;
3991: if ($homeserver eq $perlvar{'lonHostID'}) {
3992: foreach (@responses) {
3993: my ($key,$value) = split/=/,$_;
3994: $$replyref{$key} = $value;
3995: }
3996: } else {
1.506 raeburn 3997: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
3998: foreach (@responses) {
3999: my ($key,$value) = split/=/,$_;
4000: $$replyref{$key} = $value;
4001: if ($value > 0) {
4002: foreach (@{$$affiliatesref{$key}}) {
4003: my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
4004: my $destname = $pathname.'/'.$filename;
4005: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4006: if ($xml_classlist =~ /^error/) {
4007: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4008: } else {
1.506 raeburn 4009: if ( open(FILE,">$destname") ) {
4010: print FILE &unescape($xml_classlist);
4011: close(FILE);
1.526 raeburn 4012: } else {
4013: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4014: }
4015: }
4016: }
4017: }
4018: }
4019: }
4020: return 'ok';
4021: }
4022: return 'error';
4023: }
4024:
1.242 www 4025: sub get_query_reply {
4026: my $queryid=shift;
1.240 www 4027: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4028: my $reply='';
4029: for (1..100) {
4030: sleep 2;
4031: if (-e $replyfile.'.end') {
1.448 albertel 4032: if (open(my $fh,$replyfile)) {
1.240 www 4033: $reply.=<$fh>;
1.448 albertel 4034: close($fh);
1.240 www 4035: } else { return 'error: reply_file_error'; }
1.242 www 4036: return &unescape($reply);
4037: }
1.240 www 4038: }
1.242 www 4039: return 'timeout:'.$queryid;
1.240 www 4040: }
4041:
4042: sub courselog_query {
1.241 www 4043: #
4044: # possible filters:
4045: # url: url or symb
4046: # username
4047: # domain
4048: # action: view, submit, grade
4049: # start: timestamp
4050: # end: timestamp
4051: #
1.240 www 4052: my (%filters)=@_;
1.620 albertel 4053: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4054: if ($filters{'url'}) {
4055: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4056: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4057: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4058: }
1.620 albertel 4059: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4060: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4061: return &log_query($cname,$cdom,'courselog',%filters);
4062: }
4063:
4064: sub userlog_query {
4065: my ($uname,$udom,%filters)=@_;
4066: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4067: }
4068:
1.506 raeburn 4069: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4070:
4071: sub auto_run {
1.508 raeburn 4072: my ($cnum,$cdom) = @_;
4073: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4074: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 4075: return $response;
4076: }
1.776 albertel 4077:
1.506 raeburn 4078: sub auto_get_sections {
1.508 raeburn 4079: my ($cnum,$cdom,$inst_coursecode) = @_;
4080: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4081: my @secs = ();
1.511 raeburn 4082: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4083: unless ($response eq 'refused') {
4084: @secs = split/:/,$response;
4085: }
4086: return @secs;
4087: }
1.776 albertel 4088:
1.506 raeburn 4089: sub auto_new_course {
1.508 raeburn 4090: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4091: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4092: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4093: return $response;
4094: }
1.776 albertel 4095:
1.506 raeburn 4096: sub auto_validate_courseID {
1.508 raeburn 4097: my ($cnum,$cdom,$inst_course_id) = @_;
4098: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4099: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4100: return $response;
4101: }
1.776 albertel 4102:
1.506 raeburn 4103: sub auto_create_password {
1.508 raeburn 4104: my ($cnum,$cdom,$authparam) = @_;
4105: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4106: my $create_passwd = 0;
4107: my $authchk = '';
1.511 raeburn 4108: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 4109: if ($response eq 'refused') {
4110: $authchk = 'refused';
4111: } else {
4112: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4113: }
4114: return ($authparam,$create_passwd,$authchk);
4115: }
4116:
1.706 raeburn 4117: sub auto_photo_permission {
4118: my ($cnum,$cdom,$students) = @_;
4119: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4120: my ($outcome,$perm_reqd,$conditions) =
4121: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4122: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4123: return (undef,undef);
4124: }
1.706 raeburn 4125: return ($outcome,$perm_reqd,$conditions);
4126: }
4127:
4128: sub auto_checkphotos {
4129: my ($uname,$udom,$pid) = @_;
4130: my $homeserver = &homeserver($uname,$udom);
4131: my ($result,$resulttype);
4132: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4133: &escape($uname).':'.&escape($pid),
4134: $homeserver));
1.709 albertel 4135: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4136: return (undef,undef);
4137: }
1.706 raeburn 4138: if ($outcome) {
4139: ($result,$resulttype) = split(/:/,$outcome);
4140: }
4141: return ($result,$resulttype);
4142: }
4143:
4144: sub auto_photochoice {
4145: my ($cnum,$cdom) = @_;
4146: my $homeserver = &homeserver($cnum,$cdom);
4147: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4148: &escape($cdom),
4149: $homeserver)));
1.709 albertel 4150: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4151: return (undef,undef);
4152: }
1.706 raeburn 4153: return ($update,$comment);
4154: }
4155:
4156: sub auto_photoupdate {
4157: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4158: my $homeserver = &homeserver($cnum,$dom);
4159: my $host=$hostname{$homeserver};
4160: my $cmd = '';
4161: my $maxtries = 1;
4162: foreach (keys %{$affiliatesref}) {
4163: $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
4164: }
4165: $cmd =~ s/%%$//;
4166: $cmd = &escape($cmd);
4167: my $query = 'institutionalphotos';
4168: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4169: unless ($queryid=~/^\Q$host\E\_/) {
4170: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4171: return 'error: '.$queryid;
4172: }
4173: my $reply = &get_query_reply($queryid);
4174: my $tries = 1;
4175: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4176: $reply = &get_query_reply($queryid);
4177: $tries ++;
4178: }
4179: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4180: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4181: } else {
4182: my @responses = split(/:/,$reply);
4183: my $outcome = shift(@responses);
4184: foreach my $item (@responses) {
4185: my ($key,$value) = split(/=/,$item);
4186: $$photo{$key} = $value;
4187: }
4188: return $outcome;
4189: }
4190: return 'error';
4191: }
4192:
1.521 raeburn 4193: sub auto_instcode_format {
4194: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
4195: my $courses = '';
1.772 raeburn 4196: my @homeservers;
1.521 raeburn 4197: if ($caller eq 'global') {
1.584 raeburn 4198: foreach my $tryserver (keys %libserv) {
4199: if ($hostdom{$tryserver} eq $codedom) {
1.772 raeburn 4200: if (!grep/^\Q$tryserver\E$/,@homeservers) {
4201: push(@homeservers,$tryserver);
4202: }
1.584 raeburn 4203: }
4204: }
1.521 raeburn 4205: } else {
1.772 raeburn 4206: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4207: }
4208: foreach (keys %{$instcodes}) {
4209: $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
4210: }
4211: chop($courses);
1.772 raeburn 4212: my $ok_response = 0;
4213: my $response;
4214: while (@homeservers > 0 && $ok_response == 0) {
4215: my $server = shift(@homeservers);
4216: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4217: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4218: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
4219: split/:/,$response;
4220: %{$codes} = (%{$codes},&str2hash($codes_str));
4221: push(@{$codetitles},&str2array($codetitles_str));
4222: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4223: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4224: $ok_response = 1;
4225: }
4226: }
4227: if ($ok_response) {
1.521 raeburn 4228: return 'ok';
1.772 raeburn 4229: } else {
4230: return $response;
1.521 raeburn 4231: }
4232: }
4233:
1.777 albertel 4234: sub auto_validate_class_sec {
1.773 raeburn 4235: my ($cdom,$cnum,$owner,$inst_class) = @_;
4236: my $homeserver = &homeserver($cnum,$cdom);
4237: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774 banghart 4238: &escape($owner).':'.$cdom,$homeserver);
1.773 raeburn 4239: return $response;
4240: }
4241:
1.679 raeburn 4242: # ------------------------------------------------------- Course Group routines
4243:
4244: sub get_coursegroups {
1.683 raeburn 4245: my ($cdom,$cnum,$group) = @_;
4246: return(&dump('coursegroups',$cdom,$cnum,$group));
1.679 raeburn 4247: }
4248:
4249: sub modify_coursegroup {
4250: my ($cdom,$cnum,$groupsettings) = @_;
4251: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4252: }
4253:
4254: sub modify_group_roles {
4255: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4256: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4257: my $role = 'gr/'.&escape($userprivs);
4258: my ($uname,$udom) = split(/:/,$user);
4259: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 4260: if ($result eq 'ok') {
4261: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4262: }
1.679 raeburn 4263: return $result;
4264: }
4265:
4266: sub modify_coursegroup_membership {
4267: my ($cdom,$cnum,$membership) = @_;
4268: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4269: return $result;
4270: }
4271:
1.682 raeburn 4272: sub get_active_groups {
4273: my ($udom,$uname,$cdom,$cnum) = @_;
4274: my $now = time;
4275: my %groups = ();
4276: foreach my $key (keys(%env)) {
4277: if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
4278: my ($start,$end) = split(/\./,$env{$key});
4279: if (($end!=0) && ($end<$now)) { next; }
4280: if (($start!=0) && ($start>$now)) { next; }
4281: if ($1 eq $cdom && $2 eq $cnum) {
4282: $groups{$3} = $env{$key} ;
4283: }
4284: }
4285: }
4286: return %groups;
4287: }
4288:
1.683 raeburn 4289: sub get_group_membership {
4290: my ($cdom,$cnum,$group) = @_;
4291: return(&dump('groupmembership',$cdom,$cnum,$group));
4292: }
4293:
4294: sub get_users_groups {
4295: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 4296: my @usersgroups;
1.683 raeburn 4297: my $cachetime=1800;
4298: $courseid=~s/\_/\//g;
4299: $courseid=~s/^(\w)/\/$1/;
4300:
4301: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 4302: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4303: if (defined($cached)) {
1.734 albertel 4304: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 4305: } else {
4306: $grouplist = '';
4307: my %roleshash = &dump('roles',$udom,$uname,$courseid);
4308: my ($tmp) = keys(%roleshash);
4309: if ($tmp=~/^error:/) {
4310: &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
4311: } else {
4312: my $access_end = $env{'course.'.$courseid.
4313: '.default_enrollment_end_date'};
4314: my $now = time;
1.734 albertel 4315: foreach my $key (keys(%roleshash)) {
1.733 raeburn 4316: if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
4317: my $group = $1;
4318: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4319: my $start = $2;
4320: my $end = $1;
4321: if ($start == -1) { next; } # deleted from group
4322: if (($start!=0) && ($start>$now)) { next; }
4323: if (($end!=0) && ($end<$now)) {
4324: if ($access_end && $access_end < $now) {
4325: if ($access_end - $end < 86400) {
4326: push(@usersgroups,$group);
4327: }
4328: }
4329: next;
4330: }
4331: push(@usersgroups,$group);
4332: }
1.683 raeburn 4333: }
4334: }
1.733 raeburn 4335: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4336: $grouplist = join(':',@usersgroups);
4337: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 4338: }
4339: }
1.733 raeburn 4340: return @usersgroups;
1.683 raeburn 4341: }
4342:
4343: sub devalidate_getgroups_cache {
4344: my ($udom,$uname,$cdom,$cnum)=@_;
4345: my $courseid = $cdom.'_'.$cnum;
4346: $courseid=~s/\_/\//g;
4347: $courseid=~s/^(\w)/\/$1/;
4348: my $hashid="$udom:$uname:$courseid";
4349: &devalidate_cache_new('getgroups',$hashid);
4350: }
4351:
1.12 www 4352: # ------------------------------------------------------------------ Plain Text
4353:
4354: sub plaintext {
1.742 raeburn 4355: my ($short,$type,$cid) = @_;
1.758 albertel 4356: if ($short =~ /^cr/) {
4357: return (split('/',$short))[-1];
4358: }
1.742 raeburn 4359: if (!defined($cid)) {
4360: $cid = $env{'request.course.id'};
4361: }
4362: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4363: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4364: '.plaintext'});
4365: }
4366: my %rolenames = (
4367: Course => 'std',
4368: Group => 'alt1',
4369: );
4370: if (defined($type) &&
4371: defined($rolenames{$type}) &&
4372: defined($prp{$short}{$rolenames{$type}})) {
4373: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4374: } else {
4375: return &Apache::lonlocal::mt($prp{$short}{'std'});
4376: }
1.12 www 4377: }
4378:
4379: # ----------------------------------------------------------------- Assign Role
4380:
4381: sub assignrole {
1.357 www 4382: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 4383: my $mrole;
4384: if ($role =~ /^cr\//) {
1.393 www 4385: my $cwosec=$url;
4386: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
4387: unless (&allowed('ccr',$cwosec)) {
1.104 www 4388: &logthis('Refused custom assignrole: '.
4389: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4390: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4391: return 'refused';
4392: }
1.21 www 4393: $mrole='cr';
1.678 raeburn 4394: } elsif ($role =~ /^gr\//) {
4395: my $cwogrp=$url;
4396: $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
4397: unless (&allowed('mdg',$cwogrp)) {
4398: &logthis('Refused group assignrole: '.
4399: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4400: $env{'user.name'}.' at '.$env{'user.domain'});
4401: return 'refused';
4402: }
4403: $mrole='gr';
1.21 www 4404: } else {
1.82 www 4405: my $cwosec=$url;
1.83 www 4406: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373 www 4407: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 4408: &logthis('Refused assignrole: '.
4409: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4410: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4411: return 'refused';
4412: }
1.21 www 4413: $mrole=$role;
4414: }
1.620 albertel 4415: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4416: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 4417: if ($end) { $command.='_'.$end; }
1.21 www 4418: if ($start) {
4419: if ($end) {
1.81 www 4420: $command.='_'.$start;
1.21 www 4421: } else {
1.81 www 4422: $command.='_0_'.$start;
1.21 www 4423: }
4424: }
1.739 raeburn 4425: my $origstart = $start;
4426: my $origend = $end;
1.357 www 4427: # actually delete
4428: if ($deleteflag) {
1.373 www 4429: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 4430: # modify command to delete the role
1.620 albertel 4431: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 4432: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 4433: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 4434: # set start and finish to negative values for userrolelog
4435: $start=-1;
4436: $end=-1;
4437: }
4438: }
4439: # send command
1.349 www 4440: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 4441: # log new user role if status is ok
1.349 www 4442: if ($answer eq 'ok') {
1.663 raeburn 4443: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 4444: # for course roles, perform group memberships changes triggered by role change.
4445: unless ($role =~ /^gr/) {
4446: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4447: $origstart);
4448: }
1.349 www 4449: }
4450: return $answer;
1.169 harris41 4451: }
4452:
4453: # -------------------------------------------------- Modify user authentication
1.197 www 4454: # Overrides without validation
4455:
1.169 harris41 4456: sub modifyuserauth {
4457: my ($udom,$uname,$umode,$upass)=@_;
4458: my $uhome=&homeserver($uname,$udom);
1.197 www 4459: unless (&allowed('mau',$udom)) { return 'refused'; }
4460: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 4461: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4462: ' in domain '.$env{'request.role.domain'});
1.169 harris41 4463: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4464: &escape($upass),$uhome);
1.620 albertel 4465: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 4466: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4467: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4468: &log($udom,,$uname,$uhome,
1.620 albertel 4469: 'Authentication changed by '.$env{'user.domain'}.', '.
4470: $env{'user.name'}.', '.$umode.
1.197 www 4471: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 4472: unless ($reply eq 'ok') {
1.197 www 4473: &logthis('Authentication mode error: '.$reply);
1.169 harris41 4474: return 'error: '.$reply;
4475: }
1.170 harris41 4476: return 'ok';
1.80 www 4477: }
4478:
1.81 www 4479: # --------------------------------------------------------------- Modify a user
1.80 www 4480:
1.81 www 4481: sub modifyuser {
1.206 matthew 4482: my ($udom, $uname, $uid,
4483: $umode, $upass, $first,
4484: $middle, $last, $gene,
1.387 www 4485: $forceid, $desiredhome, $email)=@_;
1.198 www 4486: $udom=~s/\W//g;
4487: $uname=~s/\W//g;
1.81 www 4488: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4489: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 4490: $last.', '.$gene.'(forceid: '.$forceid.')'.
4491: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4492: ' desiredhome not specified').
1.620 albertel 4493: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4494: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 4495: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 4496: # ----------------------------------------------------------------- Create User
1.406 albertel 4497: if (($uhome eq 'no_host') &&
4498: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 4499: my $unhome='';
1.209 matthew 4500: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) {
4501: $unhome = $desiredhome;
1.620 albertel 4502: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4503: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 4504: } else { # load balancing routine for determining $unhome
1.80 www 4505: my $tryserver;
1.81 www 4506: my $loadm=10000000;
1.80 www 4507: foreach $tryserver (keys %libserv) {
4508: if ($hostdom{$tryserver} eq $udom) {
4509: my $answer=reply('load',$tryserver);
4510: if (($answer=~/\d+/) && ($answer<$loadm)) {
4511: $loadm=$answer;
4512: $unhome=$tryserver;
4513: }
4514: }
4515: }
4516: }
4517: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 4518: return 'error: unable to find a home server for '.$uname.
4519: ' in domain '.$udom;
1.80 www 4520: }
4521: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4522: &escape($upass),$unhome);
4523: unless ($reply eq 'ok') {
4524: return 'error: '.$reply;
4525: }
1.230 stredwic 4526: $uhome=&homeserver($uname,$udom,'true');
1.80 www 4527: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 4528: return 'error: unable verify users home machine.';
1.80 www 4529: }
1.209 matthew 4530: } # End of creation of new user
1.80 www 4531: # ---------------------------------------------------------------------- Add ID
4532: if ($uid) {
4533: $uid=~tr/A-Z/a-z/;
4534: my %uidhash=&idrget($udom,$uname);
1.196 www 4535: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4536: && (!$forceid)) {
1.80 www 4537: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 4538: return 'error: user id "'.$uid.'" does not match '.
4539: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 4540: }
4541: } else {
4542: &idput($udom,($uname => $uid));
4543: }
4544: }
4545: # -------------------------------------------------------------- Add names, etc
1.313 matthew 4546: my @tmp=&get('environment',
1.134 albertel 4547: ['firstname','middlename','lastname','generation'],
4548: $udom,$uname);
1.313 matthew 4549: my %names;
4550: if ($tmp[0] =~ m/^error:.*/) {
4551: %names=();
4552: } else {
4553: %names = @tmp;
4554: }
1.388 www 4555: #
4556: # Make sure to not trash student environment if instructor does not bother
4557: # to supply name and email information
4558: #
4559: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 4560: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 4561: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 4562: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 4563: if ($email) {
4564: $email=~s/[^\w\@\.\-\,]//gs;
4565: if ($email=~/\@/) { $names{'notification'} = $email;
4566: $names{'critnotification'} = $email;
4567: $names{'permanentemail'} = $email; }
4568: }
1.134 albertel 4569: my $reply = &put('environment', \%names, $udom,$uname);
4570: if ($reply ne 'ok') { return 'error: '.$reply; }
1.680 www 4571: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 4572: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4573: $umode.', '.$first.', '.$middle.', '.
4574: $last.', '.$gene.' by '.
1.620 albertel 4575: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 4576: return 'ok';
1.80 www 4577: }
4578:
1.81 www 4579: # -------------------------------------------------------------- Modify student
1.80 www 4580:
1.81 www 4581: sub modifystudent {
4582: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 4583: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 4584: if (!$cid) {
1.620 albertel 4585: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 4586: return 'not_in_class';
4587: }
1.80 www 4588: }
4589: # --------------------------------------------------------------- Make the user
1.81 www 4590: my $reply=&modifyuser
1.209 matthew 4591: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 4592: $desiredhome,$email);
1.80 www 4593: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 4594: # This will cause &modify_student_enrollment to get the uid from the
4595: # students environment
4596: $uid = undef if (!$forceid);
1.455 albertel 4597: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 4598: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 4599: return $reply;
4600: }
4601:
4602: sub modify_student_enrollment {
1.515 raeburn 4603: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 4604: my ($cdom,$cnum,$chome);
4605: if (!$cid) {
1.620 albertel 4606: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 4607: return 'not_in_class';
4608: }
1.620 albertel 4609: $cdom=$env{'course.'.$cid.'.domain'};
4610: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 4611: } else {
4612: ($cdom,$cnum)=split(/_/,$cid);
4613: }
1.620 albertel 4614: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 4615: if (!$chome) {
1.457 raeburn 4616: $chome=&homeserver($cnum,$cdom);
1.297 matthew 4617: }
1.455 albertel 4618: if (!$chome) { return 'unknown_course'; }
1.297 matthew 4619: # Make sure the user exists
1.81 www 4620: my $uhome=&homeserver($uname,$udom);
4621: if (($uhome eq '') || ($uhome eq 'no_host')) {
4622: return 'error: no such user';
4623: }
1.297 matthew 4624: # Get student data if we were not given enough information
4625: if (!defined($first) || $first eq '' ||
4626: !defined($last) || $last eq '' ||
4627: !defined($uid) || $uid eq '' ||
4628: !defined($middle) || $middle eq '' ||
4629: !defined($gene) || $gene eq '') {
1.294 matthew 4630: # They did not supply us with enough data to enroll the student, so
4631: # we need to pick up more information.
1.297 matthew 4632: my %tmp = &get('environment',
1.294 matthew 4633: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 4634: ,$udom,$uname);
4635:
1.455 albertel 4636: #foreach (keys(%tmp)) {
4637: # &logthis("key $_ = ".$tmp{$_});
4638: #}
1.294 matthew 4639: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
4640: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
4641: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 4642: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 4643: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
4644: }
1.556 albertel 4645: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 4646: my $reply=cput('classlist',
4647: {"$uname:$udom" =>
1.515 raeburn 4648: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 4649: $cdom,$cnum);
1.81 www 4650: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
4651: return 'error: '.$reply;
1.652 albertel 4652: } else {
4653: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 4654: }
1.297 matthew 4655: # Add student role to user
1.83 www 4656: my $uurl='/'.$cid;
1.81 www 4657: $uurl=~s/\_/\//g;
4658: if ($usec) {
4659: $uurl.='/'.$usec;
4660: }
4661: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 4662: }
4663:
1.556 albertel 4664: sub format_name {
4665: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
4666: my $name;
4667: if ($first ne 'lastname') {
4668: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
4669: } else {
4670: if ($lastname=~/\S/) {
4671: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
4672: $name=~s/\s+,/,/;
4673: } else {
4674: $name.= $firstname.' '.$middlename.' '.$generation;
4675: }
4676: }
4677: $name=~s/^\s+//;
4678: $name=~s/\s+$//;
4679: $name=~s/\s+/ /g;
4680: return $name;
4681: }
4682:
1.84 www 4683: # ------------------------------------------------- Write to course preferences
4684:
4685: sub writecoursepref {
4686: my ($courseid,%prefs)=@_;
4687: $courseid=~s/^\///;
4688: $courseid=~s/\_/\//g;
4689: my ($cdomain,$cnum)=split(/\//,$courseid);
4690: my $chome=homeserver($cnum,$cdomain);
4691: if (($chome eq '') || ($chome eq 'no_host')) {
4692: return 'error: no such course';
4693: }
4694: my $cstring='';
1.191 harris41 4695: foreach (keys %prefs) {
1.84 www 4696: $cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191 harris41 4697: }
1.84 www 4698: $cstring=~s/\&$//;
4699: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
4700: }
4701:
4702: # ---------------------------------------------------------- Make/modify course
4703:
4704: sub createcourse {
1.741 raeburn 4705: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
4706: $course_owner,$crstype)=@_;
1.84 www 4707: $url=&declutter($url);
4708: my $cid='';
1.264 matthew 4709: unless (&allowed('ccc',$udom)) {
1.84 www 4710: return 'refused';
4711: }
4712: # ------------------------------------------------------------------- Create ID
1.674 www 4713: my $uname=int(1+rand(9)).
4714: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
4715: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 4716: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
4717: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 4718: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 4719: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4720: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
4721: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 4722: $uhome=&homeserver($uname,$udom,'true');
1.84 www 4723: unless (($uhome eq '') || ($uhome eq 'no_host')) {
4724: return 'error: unable to generate unique course-ID';
4725: }
4726: }
1.264 matthew 4727: # ------------------------------------------------ Check supplied server name
1.620 albertel 4728: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264 matthew 4729: if (! exists($libserv{$course_server})) {
4730: return 'error:bad server name '.$course_server;
4731: }
1.84 www 4732: # ------------------------------------------------------------- Make the course
4733: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 4734: $course_server);
1.84 www 4735: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 4736: $uhome=&homeserver($uname,$udom,'true');
1.84 www 4737: if (($uhome eq '') || ($uhome eq 'no_host')) {
4738: return 'error: no such course';
4739: }
1.271 www 4740: # ----------------------------------------------------------------- Course made
1.516 raeburn 4741: # log existence
4742: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741 raeburn 4743: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
4744: &escape($crstype),$uhome);
1.358 www 4745: &flushcourselogs();
4746: # set toplevel url
1.271 www 4747: my $topurl=$url;
4748: unless ($nonstandard) {
4749: # ------------------------------------------ For standard courses, make top url
4750: my $mapurl=&clutter($url);
1.278 www 4751: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 4752: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 4753: <map>
4754: <resource id="1" type="start"></resource>
4755: <resource id="2" src="$mapurl"></resource>
4756: <resource id="3" type="finish"></resource>
4757: <link index="1" from="1" to="2"></link>
4758: <link index="2" from="2" to="3"></link>
4759: </map>
4760: ENDINITMAP
4761: $topurl=&declutter(
1.638 albertel 4762: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 4763: );
4764: }
4765: # ----------------------------------------------------------- Write preferences
1.84 www 4766: &writecoursepref($udom.'_'.$uname,
4767: ('description' => $description,
1.271 www 4768: 'url' => $topurl));
1.84 www 4769: return '/'.$udom.'/'.$uname;
4770: }
4771:
1.21 www 4772: # ---------------------------------------------------------- Assign Custom Role
4773:
4774: sub assigncustomrole {
1.357 www 4775: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 4776: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 4777: $end,$start,$deleteflag);
1.21 www 4778: }
4779:
4780: # ----------------------------------------------------------------- Revoke Role
4781:
4782: sub revokerole {
1.357 www 4783: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 4784: my $now=time;
1.357 www 4785: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 4786: }
4787:
4788: # ---------------------------------------------------------- Revoke Custom Role
4789:
4790: sub revokecustomrole {
1.357 www 4791: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 4792: my $now=time;
1.357 www 4793: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
4794: $deleteflag);
1.17 www 4795: }
4796:
1.533 banghart 4797: # ------------------------------------------------------------ Disk usage
1.535 albertel 4798: sub diskusage {
1.533 banghart 4799: my ($udom,$uname,$directoryRoot)=@_;
4800: $directoryRoot =~ s/\/$//;
1.535 albertel 4801: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 4802: return $listing;
1.512 banghart 4803: }
4804:
1.566 banghart 4805: sub is_locked {
4806: my ($file_name, $domain, $user) = @_;
4807: my @check;
4808: my $is_locked;
4809: push @check, $file_name;
1.613 albertel 4810: my %locked = &get('file_permissions',\@check,
1.620 albertel 4811: $env{'user.domain'},$env{'user.name'});
1.615 albertel 4812: my ($tmp)=keys(%locked);
4813: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 4814:
1.566 banghart 4815: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 4816: $is_locked = 'false';
4817: foreach my $entry (@{$locked{$file_name}}) {
4818: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 4819: $is_locked = 'true';
4820: last;
1.745 raeburn 4821: }
4822: }
1.566 banghart 4823: } else {
4824: $is_locked = 'false';
4825: }
4826: }
4827:
1.759 albertel 4828: sub declutter_portfile {
4829: my ($file) = @_;
4830: &logthis("got $file");
4831: $file =~ s-^(/portfolio/|portfolio/)-/-;
4832: &logthis("ret $file");
4833: return $file;
4834: }
4835:
1.559 banghart 4836: # ------------------------------------------------------------- Mark as Read Only
4837:
4838: sub mark_as_readonly {
4839: my ($domain,$user,$files,$what) = @_;
1.613 albertel 4840: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 4841: my ($tmp)=keys(%current_permissions);
4842: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 4843: foreach my $file (@{$files}) {
1.759 albertel 4844: $file = &declutter_portfile($file);
1.561 banghart 4845: push(@{$current_permissions{$file}},$what);
1.559 banghart 4846: }
1.613 albertel 4847: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 4848: return;
4849: }
4850:
1.572 banghart 4851: # ------------------------------------------------------------Save Selected Files
4852:
4853: sub save_selected_files {
4854: my ($user, $path, @files) = @_;
4855: my $filename = $user."savedfiles";
1.573 banghart 4856: my @other_files = &files_not_in_path($user, $path);
1.574 banghart 4857: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 4858: foreach my $file (@files) {
1.620 albertel 4859: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 4860: }
4861: foreach my $file (@other_files) {
1.574 banghart 4862: print (OUT $file."\n");
1.572 banghart 4863: }
1.574 banghart 4864: close (OUT);
1.572 banghart 4865: return 'ok';
4866: }
4867:
1.574 banghart 4868: sub clear_selected_files {
4869: my ($user) = @_;
4870: my $filename = $user."savedfiles";
4871: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
4872: print (OUT undef);
4873: close (OUT);
4874: return ("ok");
4875: }
4876:
1.572 banghart 4877: sub files_in_path {
4878: my ($user, $path) = @_;
4879: my $filename = $user."savedfiles";
4880: my %return_files;
1.574 banghart 4881: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 4882: while (my $line_in = <IN>) {
1.574 banghart 4883: chomp ($line_in);
4884: my @paths_and_file = split (m!/!, $line_in);
4885: my $file_part = pop (@paths_and_file);
4886: my $path_part = join ('/', @paths_and_file);
1.573 banghart 4887: $path_part.='/';
4888: my $path_and_file = $path_part.$file_part;
4889: if ($path_part eq $path) {
4890: $return_files{$file_part}= 'selected';
4891: }
4892: }
1.574 banghart 4893: close (IN);
4894: return (\%return_files);
1.572 banghart 4895: }
4896:
4897: # called in portfolio select mode, to show files selected NOT in current directory
4898: sub files_not_in_path {
4899: my ($user, $path) = @_;
4900: my $filename = $user."savedfiles";
4901: my @return_files;
4902: my $path_part;
1.574 banghart 4903: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572 banghart 4904: while (<IN>) {
4905: #ok, I know it's clunky, but I want it to work
4906: my @paths_and_file = split m!/!, $_;
1.574 banghart 4907: my $file_part = pop (@paths_and_file);
4908: chomp ($file_part);
4909: my $path_part = join ('/', @paths_and_file);
1.572 banghart 4910: $path_part .= '/';
4911: my $path_and_file = $path_part.$file_part;
4912: if ($path_part ne $path) {
1.574 banghart 4913: push (@return_files, ($path_and_file));
1.572 banghart 4914: }
4915: }
1.574 banghart 4916: close (OUT);
4917: return (@return_files);
1.572 banghart 4918: }
4919:
1.745 raeburn 4920: #----------------------------------------------Get portfolio file permissions
1.629 banghart 4921:
1.745 raeburn 4922: sub get_portfile_permissions {
4923: my ($domain,$user) = @_;
1.613 albertel 4924: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 4925: my ($tmp)=keys(%current_permissions);
4926: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 4927: return \%current_permissions;
4928: }
4929:
4930: #---------------------------------------------Get portfolio file access controls
4931:
1.749 raeburn 4932: sub get_access_controls {
1.745 raeburn 4933: my ($current_permissions,$group,$file) = @_;
1.769 albertel 4934: my %access;
4935: my $real_file = $file;
4936: $file =~ s/\.meta$//;
1.745 raeburn 4937: if (defined($file)) {
1.749 raeburn 4938: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
4939: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 4940: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 4941: }
4942: }
1.745 raeburn 4943: } else {
1.749 raeburn 4944: foreach my $key (keys(%{$current_permissions})) {
4945: if ($key =~ /\0accesscontrol$/) {
4946: if (defined($group)) {
4947: if ($key !~ m-^\Q$group\E/-) {
4948: next;
4949: }
4950: }
4951: my ($fullpath) = split(/\0/,$key);
4952: if (ref($$current_permissions{$key}) eq 'HASH') {
4953: foreach my $control (keys(%{$$current_permissions{$key}})) {
4954: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
4955: }
4956: }
4957: }
4958: }
4959: }
4960: return %access;
4961: }
4962:
4963: sub modify_access_controls {
4964: my ($file_name,$changes,$domain,$user)=@_;
4965: my ($outcome,$deloutcome);
4966: my %store_permissions;
4967: my %new_values;
4968: my %new_control;
4969: my %translation;
4970: my @deletions = ();
4971: my $now = time;
4972: if (exists($$changes{'activate'})) {
4973: if (ref($$changes{'activate'}) eq 'HASH') {
4974: my @newitems = sort(keys(%{$$changes{'activate'}}));
4975: my $numnew = scalar(@newitems);
4976: for (my $i=0; $i<$numnew; $i++) {
4977: my $newkey = $newitems[$i];
4978: my $newid = &Apache::loncommon::get_cgi_id();
4979: $newkey =~ s/^(\d+)/$newid/;
4980: $translation{$1} = $newid;
4981: $new_values{$file_name."\0".$newkey} =
4982: $$changes{'activate'}{$newitems[$i]};
4983: $new_control{$newkey} = $now;
4984: }
4985: }
4986: }
4987: my %todelete;
4988: my %changed_items;
4989: foreach my $action ('delete','update') {
4990: if (exists($$changes{$action})) {
4991: if (ref($$changes{$action}) eq 'HASH') {
4992: foreach my $key (keys(%{$$changes{$action}})) {
4993: my ($itemnum) = ($key =~ /^([^:]+):/);
4994: if ($action eq 'delete') {
4995: $todelete{$itemnum} = 1;
4996: } else {
4997: $changed_items{$itemnum} = $key;
4998: }
4999: }
1.745 raeburn 5000: }
5001: }
1.749 raeburn 5002: }
5003: # get lock on access controls for file.
5004: my $lockhash = {
5005: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5006: ':'.$env{'user.domain'},
5007: };
5008: my $tries = 0;
5009: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5010:
5011: while (($gotlock ne 'ok') && $tries <3) {
5012: $tries ++;
5013: sleep 1;
5014: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5015: }
5016: if ($gotlock eq 'ok') {
5017: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5018: my ($tmp)=keys(%curr_permissions);
5019: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5020: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5021: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5022: if (ref($curr_controls) eq 'HASH') {
5023: foreach my $control_item (keys(%{$curr_controls})) {
5024: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5025: if (defined($todelete{$itemnum})) {
5026: push(@deletions,$file_name."\0".$control_item);
5027: } else {
5028: if (defined($changed_items{$itemnum})) {
5029: $new_control{$changed_items{$itemnum}} = $now;
5030: push(@deletions,$file_name."\0".$control_item);
5031: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5032: } else {
5033: $new_control{$control_item} = $$curr_controls{$control_item};
5034: }
5035: }
1.745 raeburn 5036: }
5037: }
5038: }
1.749 raeburn 5039: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5040: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5041: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5042: # remove lock
5043: my @del_lock = ($file_name."\0".'locked_access_records');
5044: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
5045: } else {
5046: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5047: }
1.749 raeburn 5048: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5049: }
5050:
5051: #------------------------------------------------------Get Marked as Read Only
5052:
5053: sub get_marked_as_readonly {
5054: my ($domain,$user,$what,$group) = @_;
5055: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5056: my @readonly_files;
1.629 banghart 5057: my $cmp1=$what;
5058: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5059: while (my ($file_name,$value) = each(%{$current_permissions})) {
5060: if (defined($group)) {
5061: if ($file_name !~ m-^\Q$group\E/-) {
5062: next;
5063: }
5064: }
1.561 banghart 5065: if (ref($value) eq "ARRAY"){
5066: foreach my $stored_what (@{$value}) {
1.629 banghart 5067: my $cmp2=$stored_what;
1.759 albertel 5068: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 5069: $cmp2=join('',@{$stored_what});
1.745 raeburn 5070: }
1.629 banghart 5071: if ($cmp1 eq $cmp2) {
1.561 banghart 5072: push(@readonly_files, $file_name);
1.745 raeburn 5073: last;
1.563 banghart 5074: } elsif (!defined($what)) {
5075: push(@readonly_files, $file_name);
1.745 raeburn 5076: last;
1.561 banghart 5077: }
5078: }
1.745 raeburn 5079: }
1.561 banghart 5080: }
5081: return @readonly_files;
5082: }
1.577 banghart 5083: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 5084:
1.577 banghart 5085: sub get_marked_as_readonly_hash {
1.745 raeburn 5086: my ($current_permissions,$group,$what) = @_;
1.577 banghart 5087: my %readonly_files;
1.745 raeburn 5088: while (my ($file_name,$value) = each(%{$current_permissions})) {
5089: if (defined($group)) {
5090: if ($file_name !~ m-^\Q$group\E/-) {
5091: next;
5092: }
5093: }
1.577 banghart 5094: if (ref($value) eq "ARRAY"){
5095: foreach my $stored_what (@{$value}) {
1.745 raeburn 5096: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 5097: foreach my $lock_descriptor(@{$stored_what}) {
5098: if ($lock_descriptor eq 'graded') {
5099: $readonly_files{$file_name} = 'graded';
5100: } elsif ($lock_descriptor eq 'handback') {
5101: $readonly_files{$file_name} = 'handback';
5102: } else {
5103: if (!exists($readonly_files{$file_name})) {
5104: $readonly_files{$file_name} = 'locked';
5105: }
5106: }
1.745 raeburn 5107: }
1.750 banghart 5108: }
1.577 banghart 5109: }
5110: }
5111: }
5112: return %readonly_files;
5113: }
1.559 banghart 5114: # ------------------------------------------------------------ Unmark as Read Only
5115:
5116: sub unmark_as_readonly {
1.629 banghart 5117: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5118: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 5119: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 5120: $file_name = &declutter_portfile($file_name);
1.634 albertel 5121: my $symb_crs = $what;
5122: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 5123: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 5124: my ($tmp)=keys(%current_permissions);
5125: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5126: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 5127: foreach my $file (@readonly_files) {
1.759 albertel 5128: my $clean_file = &declutter_portfile($file);
5129: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 5130: my $current_locks = $current_permissions{$file};
1.563 banghart 5131: my @new_locks;
5132: my @del_keys;
5133: if (ref($current_locks) eq "ARRAY"){
5134: foreach my $locker (@{$current_locks}) {
1.632 albertel 5135: my $compare=$locker;
1.749 raeburn 5136: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 5137: $compare=join('',@{$locker});
1.746 raeburn 5138: if ($compare ne $symb_crs) {
5139: push(@new_locks, $locker);
5140: }
1.563 banghart 5141: }
5142: }
1.650 albertel 5143: if (scalar(@new_locks) > 0) {
1.563 banghart 5144: $current_permissions{$file} = \@new_locks;
5145: } else {
5146: push(@del_keys, $file);
1.613 albertel 5147: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 5148: delete($current_permissions{$file});
1.563 banghart 5149: }
5150: }
1.561 banghart 5151: }
1.613 albertel 5152: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5153: return;
5154: }
1.512 banghart 5155:
1.17 www 5156: # ------------------------------------------------------------ Directory lister
5157:
5158: sub dirlist {
1.253 stredwic 5159: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5160:
1.18 www 5161: $uri=~s/^\///;
5162: $uri=~s/\/$//;
1.253 stredwic 5163: my ($udom, $uname);
5164: (undef,$udom,$uname)=split(/\//,$uri);
5165: if(defined($userdomain)) {
5166: $udom = $userdomain;
5167: }
5168: if(defined($username)) {
5169: $uname = $username;
5170: }
5171:
5172: my $dirRoot = $perlvar{'lonDocRoot'};
5173: if(defined($alternateDirectoryRoot)) {
5174: $dirRoot = $alternateDirectoryRoot;
5175: $dirRoot =~ s/\/$//;
1.751 banghart 5176: }
1.253 stredwic 5177:
5178: if($udom) {
5179: if($uname) {
1.605 matthew 5180: my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253 stredwic 5181: homeserver($uname,$udom));
1.605 matthew 5182: my @listing_results;
5183: if ($listing eq 'unknown_cmd') {
5184: $listing=reply('ls:'.$dirRoot.'/'.$uri,
5185: homeserver($uname,$udom));
5186: @listing_results = split(/:/,$listing);
5187: } else {
5188: @listing_results = map { &unescape($_); } split(/:/,$listing);
5189: }
5190: return @listing_results;
1.253 stredwic 5191: } elsif(!defined($alternateDirectoryRoot)) {
5192: my $tryserver;
5193: my %allusers=();
5194: foreach $tryserver (keys %libserv) {
5195: if($hostdom{$tryserver} eq $udom) {
1.605 matthew 5196: my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253 stredwic 5197: $udom, $tryserver);
1.605 matthew 5198: my @listing_results;
5199: if ($listing eq 'unknown_cmd') {
5200: $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5201: $udom, $tryserver);
5202: @listing_results = split(/:/,$listing);
5203: } else {
5204: @listing_results =
5205: map { &unescape($_); } split(/:/,$listing);
5206: }
5207: if ($listing_results[0] ne 'no_such_dir' &&
5208: $listing_results[0] ne 'empty' &&
5209: $listing_results[0] ne 'con_lost') {
5210: foreach (@listing_results) {
1.253 stredwic 5211: my ($entry,@stat)=split(/&/,$_);
5212: $allusers{$entry}=1;
5213: }
5214: }
1.191 harris41 5215: }
1.253 stredwic 5216: }
5217: my $alluserstr='';
5218: foreach (sort keys %allusers) {
5219: $alluserstr.=$_.'&user:';
5220: }
5221: $alluserstr=~s/:$//;
5222: return split(/:/,$alluserstr);
5223: } else {
5224: my @emptyResults = ();
5225: push(@emptyResults, 'missing user name');
5226: return split(':',@emptyResults);
5227: }
5228: } elsif(!defined($alternateDirectoryRoot)) {
5229: my $tryserver;
5230: my %alldom=();
5231: foreach $tryserver (keys %libserv) {
5232: $alldom{$hostdom{$tryserver}}=1;
5233: }
5234: my $alldomstr='';
5235: foreach (sort keys %alldom) {
1.397 albertel 5236: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253 stredwic 5237: }
5238: $alldomstr=~s/:$//;
5239: return split(/:/,$alldomstr);
5240: } else {
5241: my @emptyResults = ();
5242: push(@emptyResults, 'missing domain');
5243: return split(':',@emptyResults);
1.275 stredwic 5244: }
5245: }
5246:
5247: # --------------------------------------------- GetFileTimestamp
5248: # This function utilizes dirlist and returns the date stamp for
5249: # when it was last modified. It will also return an error of -1
5250: # if an error occurs
5251:
1.410 matthew 5252: ##
5253: ## FIXME: This subroutine assumes its caller knows something about the
5254: ## directory structure of the home server for the student ($root).
5255: ## Not a good assumption to make. Since this is for looking up files
5256: ## in user directories, the full path should be constructed by lond, not
5257: ## whatever machine we request data from.
5258: ##
1.275 stredwic 5259: sub GetFileTimestamp {
5260: my ($studentDomain,$studentName,$filename,$root)=@_;
5261: $studentDomain=~s/\W//g;
5262: $studentName=~s/\W//g;
5263: my $subdir=$studentName.'__';
5264: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5265: my $proname="$studentDomain/$subdir/$studentName";
5266: $proname .= '/'.$filename;
1.375 matthew 5267: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5268: $studentName, $root);
1.275 stredwic 5269: my @stats = split('&', $fileStat);
5270: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 5271: # @stats contains first the filename, then the stat output
5272: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 5273: } else {
5274: return -1;
1.253 stredwic 5275: }
1.26 www 5276: }
5277:
1.712 albertel 5278: sub stat_file {
5279: my ($uri) = @_;
1.787 albertel 5280: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 5281:
1.712 albertel 5282: my ($udom,$uname,$file,$dir);
5283: if ($uri =~ m-^/(uploaded|editupload)/-) {
5284: ($udom,$uname,$file) =
5285: ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
5286: $file = 'userfiles/'.$file;
1.740 www 5287: $dir = &propath($udom,$uname);
1.712 albertel 5288: }
5289: if ($uri =~ m-^/res/-) {
5290: ($udom,$uname) =
5291: ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
5292: $file = $uri;
5293: }
5294:
5295: if (!$udom || !$uname || !$file) {
5296: # unable to handle the uri
5297: return ();
5298: }
5299:
5300: my ($result) = &dirlist($file,$udom,$uname,$dir);
5301: my @stats = split('&', $result);
1.721 banghart 5302:
1.712 albertel 5303: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5304: shift(@stats); #filename is first
5305: return @stats;
5306: }
5307: return ();
5308: }
5309:
1.26 www 5310: # -------------------------------------------------------- Value of a Condition
5311:
1.713 albertel 5312: # gets the value of a specific preevaluated condition
5313: # stored in the string $env{user.state.<cid>}
5314: # or looks up a condition reference in the bighash and if if hasn't
5315: # already been evaluated recurses into docondval to get the value of
5316: # the condition, then memoizing it to
5317: # $env{user.state.<cid>.<condition>}
1.40 www 5318: sub directcondval {
5319: my $number=shift;
1.620 albertel 5320: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 5321: &Apache::lonuserstate::evalstate();
5322: }
1.713 albertel 5323: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5324: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5325: } elsif ($number =~ /^_/) {
5326: my $sub_condition;
5327: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5328: &GDBM_READER(),0640)) {
5329: $sub_condition=$bighash{'conditions'.$number};
5330: untie(%bighash);
5331: }
5332: my $value = &docondval($sub_condition);
5333: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5334: return $value;
5335: }
1.620 albertel 5336: if ($env{'user.state.'.$env{'request.course.id'}}) {
5337: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 5338: } else {
5339: return 2;
5340: }
5341: }
5342:
1.713 albertel 5343: # get the collection of conditions for this resource
1.26 www 5344: sub condval {
5345: my $condidx=shift;
1.54 www 5346: my $allpathcond='';
1.713 albertel 5347: foreach my $cond (split(/\|/,$condidx)) {
5348: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5349: $allpathcond.=
5350: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5351: }
1.191 harris41 5352: }
1.54 www 5353: $allpathcond=~s/\|$//;
1.713 albertel 5354: return &docondval($allpathcond);
5355: }
5356:
5357: #evaluates an expression of conditions
5358: sub docondval {
5359: my ($allpathcond) = @_;
5360: my $result=0;
5361: if ($env{'request.course.id'}
5362: && defined($allpathcond)) {
5363: my $operand='|';
5364: my @stack;
5365: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5366: if ($chunk eq '(') {
5367: push @stack,($operand,$result);
5368: } elsif ($chunk eq ')') {
5369: my $before=pop @stack;
5370: if (pop @stack eq '&') {
5371: $result=$result>$before?$before:$result;
5372: } else {
5373: $result=$result>$before?$result:$before;
5374: }
5375: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5376: $operand=$chunk;
5377: } else {
5378: my $new=directcondval($chunk);
5379: if ($operand eq '&') {
5380: $result=$result>$new?$new:$result;
5381: } else {
5382: $result=$result>$new?$result:$new;
5383: }
5384: }
5385: }
1.26 www 5386: }
5387: return $result;
1.421 albertel 5388: }
5389:
5390: # ---------------------------------------------------- Devalidate courseresdata
5391:
5392: sub devalidatecourseresdata {
5393: my ($coursenum,$coursedomain)=@_;
5394: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5395: &devalidate_cache_new('courseres',$hashid);
1.28 www 5396: }
5397:
1.763 www 5398:
1.200 www 5399: # --------------------------------------------------- Course Resourcedata Query
5400:
1.624 albertel 5401: sub get_courseresdata {
5402: my ($coursenum,$coursedomain)=@_;
1.200 www 5403: my $coursehom=&homeserver($coursenum,$coursedomain);
5404: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5405: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 5406: my %dumpreply;
1.417 albertel 5407: unless (defined($cached)) {
1.624 albertel 5408: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 5409: $result=\%dumpreply;
1.251 albertel 5410: my ($tmp) = keys(%dumpreply);
5411: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 5412: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 5413: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5414: return $tmp;
1.416 albertel 5415: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 5416: $result=undef;
1.599 albertel 5417: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 5418: }
5419: }
1.624 albertel 5420: return $result;
5421: }
5422:
1.633 albertel 5423: sub devalidateuserresdata {
5424: my ($uname,$udom)=@_;
5425: my $hashid="$udom:$uname";
5426: &devalidate_cache_new('userres',$hashid);
5427: }
5428:
1.624 albertel 5429: sub get_userresdata {
5430: my ($uname,$udom)=@_;
5431: #most student don\'t have any data set, check if there is some data
5432: if (&EXT_cache_status($udom,$uname)) { return undef; }
5433:
5434: my $hashid="$udom:$uname";
5435: my ($result,$cached)=&is_cached_new('userres',$hashid);
5436: if (!defined($cached)) {
5437: my %resourcedata=&dump('resourcedata',$udom,$uname);
5438: $result=\%resourcedata;
5439: &do_cache_new('userres',$hashid,$result,600);
5440: }
5441: my ($tmp)=keys(%$result);
5442: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5443: return $result;
5444: }
5445: #error 2 occurs when the .db doesn't exist
5446: if ($tmp!~/error: 2 /) {
1.672 albertel 5447: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 5448: " Trying to get resource data for ".
5449: $uname." at ".$udom.": ".
5450: $tmp."</font>");
5451: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 5452: #&EXT_cache_set($udom,$uname);
5453: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 5454: undef($tmp); # not really an error so don't send it back
1.624 albertel 5455: }
5456: return $tmp;
5457: }
5458:
5459: sub resdata {
5460: my ($name,$domain,$type,@which)=@_;
5461: my $result;
5462: if ($type eq 'course') {
5463: $result=&get_courseresdata($name,$domain);
5464: } elsif ($type eq 'user') {
5465: $result=&get_userresdata($name,$domain);
5466: }
5467: if (!ref($result)) { return $result; }
1.251 albertel 5468: foreach my $item (@which) {
1.417 albertel 5469: if (defined($result->{$item})) {
5470: return $result->{$item};
1.251 albertel 5471: }
1.250 albertel 5472: }
1.291 albertel 5473: return undef;
1.200 www 5474: }
5475:
1.379 matthew 5476: #
5477: # EXT resource caching routines
5478: #
5479:
5480: sub clear_EXT_cache_status {
1.383 albertel 5481: &delenv('cache.EXT.');
1.379 matthew 5482: }
5483:
5484: sub EXT_cache_status {
5485: my ($target_domain,$target_user) = @_;
1.383 albertel 5486: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 5487: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 5488: # We know already the user has no data
5489: return 1;
5490: } else {
5491: return 0;
5492: }
5493: }
5494:
5495: sub EXT_cache_set {
5496: my ($target_domain,$target_user) = @_;
1.383 albertel 5497: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 5498: #&appenv($cachename => time);
1.379 matthew 5499: }
5500:
1.28 www 5501: # --------------------------------------------------------- Value of a Variable
1.58 www 5502: sub EXT {
1.715 albertel 5503:
1.395 albertel 5504: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 5505: unless ($varname) { return ''; }
1.218 albertel 5506: #get real user name/domain, courseid and symb
5507: my $courseid;
1.359 albertel 5508: my $publicuser;
1.427 www 5509: if ($symbparm) {
5510: $symbparm=&get_symb_from_alias($symbparm);
5511: }
1.218 albertel 5512: if (!($uname && $udom)) {
1.360 albertel 5513: (my $cursymb,$courseid,$udom,$uname,$publicuser)=
1.378 matthew 5514: &Apache::lonxml::whichuser($symbparm);
1.218 albertel 5515: if (!$symbparm) { $symbparm=$cursymb; }
5516: } else {
1.620 albertel 5517: $courseid=$env{'request.course.id'};
1.218 albertel 5518: }
1.48 www 5519: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
5520: my $rest;
1.320 albertel 5521: if (defined($therest[0])) {
1.48 www 5522: $rest=join('.',@therest);
5523: } else {
5524: $rest='';
5525: }
1.320 albertel 5526:
1.57 www 5527: my $qualifierrest=$qualifier;
5528: if ($rest) { $qualifierrest.='.'.$rest; }
5529: my $spacequalifierrest=$space;
5530: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 5531: if ($realm eq 'user') {
1.48 www 5532: # --------------------------------------------------------------- user.resource
5533: if ($space eq 'resource') {
1.651 albertel 5534: if ( (defined($Apache::lonhomework::parsing_a_problem)
5535: || defined($Apache::lonhomework::parsing_a_task))
5536: &&
1.744 albertel 5537: ($symbparm eq &symbread()) ) {
5538: # if we are in the middle of processing the resource the
5539: # get the value we are planning on committing
5540: if (defined($Apache::lonhomework::results{$qualifierrest})) {
5541: return $Apache::lonhomework::results{$qualifierrest};
5542: } else {
5543: return $Apache::lonhomework::history{$qualifierrest};
5544: }
1.335 albertel 5545: } else {
1.359 albertel 5546: my %restored;
1.620 albertel 5547: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 5548: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
5549: } else {
5550: %restored=&restore($symbparm,$courseid,$udom,$uname);
5551: }
1.335 albertel 5552: return $restored{$qualifierrest};
5553: }
1.48 www 5554: # ----------------------------------------------------------------- user.access
5555: } elsif ($space eq 'access') {
1.218 albertel 5556: # FIXME - not supporting calls for a specific user
1.48 www 5557: return &allowed($qualifier,$rest);
5558: # ------------------------------------------ user.preferences, user.environment
5559: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 5560: if (($uname eq $env{'user.name'}) &&
5561: ($udom eq $env{'user.domain'})) {
5562: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 5563: } else {
1.359 albertel 5564: my %returnhash;
5565: if (!$publicuser) {
5566: %returnhash=&userenvironment($udom,$uname,
5567: $qualifierrest);
5568: }
1.218 albertel 5569: return $returnhash{$qualifierrest};
5570: }
1.48 www 5571: # ----------------------------------------------------------------- user.course
5572: } elsif ($space eq 'course') {
1.218 albertel 5573: # FIXME - not supporting calls for a specific user
1.620 albertel 5574: return $env{join('.',('request.course',$qualifier))};
1.48 www 5575: # ------------------------------------------------------------------- user.role
5576: } elsif ($space eq 'role') {
1.218 albertel 5577: # FIXME - not supporting calls for a specific user
1.620 albertel 5578: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 5579: if ($qualifier eq 'value') {
5580: return $role;
5581: } elsif ($qualifier eq 'extent') {
5582: return $where;
5583: }
5584: # ----------------------------------------------------------------- user.domain
5585: } elsif ($space eq 'domain') {
1.218 albertel 5586: return $udom;
1.48 www 5587: # ------------------------------------------------------------------- user.name
5588: } elsif ($space eq 'name') {
1.218 albertel 5589: return $uname;
1.48 www 5590: # ---------------------------------------------------- Any other user namespace
1.29 www 5591: } else {
1.359 albertel 5592: my %reply;
5593: if (!$publicuser) {
5594: %reply=&get($space,[$qualifierrest],$udom,$uname);
5595: }
5596: return $reply{$qualifierrest};
1.48 www 5597: }
1.236 www 5598: } elsif ($realm eq 'query') {
5599: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 5600: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
5601: [$spacequalifierrest]);
1.620 albertel 5602: return $env{'form.'.$spacequalifierrest};
1.236 www 5603: } elsif ($realm eq 'request') {
1.48 www 5604: # ------------------------------------------------------------- request.browser
5605: if ($space eq 'browser') {
1.430 www 5606: if ($qualifier eq 'textremote') {
1.676 albertel 5607: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 5608: return 1;
5609: } else {
5610: return 0;
5611: }
5612: } else {
1.620 albertel 5613: return $env{'browser.'.$qualifier};
1.430 www 5614: }
1.57 www 5615: # ------------------------------------------------------------ request.filename
5616: } else {
1.620 albertel 5617: return $env{'request.'.$spacequalifierrest};
1.29 www 5618: }
1.28 www 5619: } elsif ($realm eq 'course') {
1.48 www 5620: # ---------------------------------------------------------- course.description
1.620 albertel 5621: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 5622: } elsif ($realm eq 'resource') {
1.165 www 5623:
1.620 albertel 5624: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 5625: if (!$symbparm) { $symbparm=&symbread(); }
5626: }
1.693 albertel 5627:
5628: if ($space eq 'title') {
5629: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
5630: return &gettitle($symbparm);
5631: }
5632:
5633: if ($space eq 'map') {
5634: my ($map) = &decode_symb($symbparm);
5635: return &symbread($map);
5636: }
5637:
5638: my ($section, $group, @groups);
1.593 albertel 5639: my ($courselevelm,$courselevel);
1.539 albertel 5640: if ($symbparm && defined($courseid) &&
1.620 albertel 5641: $courseid eq $env{'request.course.id'}) {
1.165 www 5642:
1.218 albertel 5643: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 5644:
1.60 www 5645: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 5646: my $symbp=$symbparm;
1.735 albertel 5647: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 5648:
5649: my $symbparm=$symbp.'.'.$spacequalifierrest;
5650: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
5651:
1.620 albertel 5652: if (($env{'user.name'} eq $uname) &&
5653: ($env{'user.domain'} eq $udom)) {
5654: $section=$env{'request.course.sec'};
1.733 raeburn 5655: @groups = split(/:/,$env{'request.course.groups'});
5656: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 5657: } else {
1.539 albertel 5658: if (! defined($usection)) {
1.551 albertel 5659: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 5660: } else {
5661: $section = $usection;
5662: }
1.733 raeburn 5663: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 5664: }
5665:
5666: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
5667: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
5668: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
5669:
1.593 albertel 5670: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 5671: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 5672: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 5673:
1.60 www 5674: # ----------------------------------------------------------- first, check user
1.624 albertel 5675:
5676: my $userreply=&resdata($uname,$udom,'user',
5677: ($courselevelr,$courselevelm,
5678: $courselevel));
5679: if (defined($userreply)) { return $userreply; }
1.95 www 5680:
1.594 albertel 5681: # ------------------------------------------------ second, check some of course
1.684 raeburn 5682: my $coursereply;
1.691 raeburn 5683: if (@groups > 0) {
5684: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
5685: $mapparm,$spacequalifierrest);
1.684 raeburn 5686: if (defined($coursereply)) { return $coursereply; }
5687: }
1.96 www 5688:
1.684 raeburn 5689: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624 albertel 5690: $env{'course.'.$courseid.'.domain'},
5691: 'course',
5692: ($seclevelr,$seclevelm,$seclevel,
5693: $courselevelr));
1.287 albertel 5694: if (defined($coursereply)) { return $coursereply; }
1.200 www 5695:
1.60 www 5696: # ------------------------------------------------------ third, check map parms
1.218 albertel 5697: my %parmhash=();
5698: my $thisparm='';
5699: if (tie(%parmhash,'GDBM_File',
1.620 albertel 5700: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 5701: &GDBM_READER(),0640)) {
1.218 albertel 5702: $thisparm=$parmhash{$symbparm};
5703: untie(%parmhash);
5704: }
5705: if ($thisparm) { return $thisparm; }
5706: }
1.594 albertel 5707: # ------------------------------------------ fourth, look in resource metadata
1.71 www 5708:
1.218 albertel 5709: $spacequalifierrest=~s/\./\_/;
1.282 albertel 5710: my $filename;
5711: if (!$symbparm) { $symbparm=&symbread(); }
5712: if ($symbparm) {
1.409 www 5713: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 5714: } else {
1.620 albertel 5715: $filename=$env{'request.filename'};
1.282 albertel 5716: }
5717: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 5718: if (defined($metadata)) { return $metadata; }
1.282 albertel 5719: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 5720: if (defined($metadata)) { return $metadata; }
1.142 www 5721:
1.594 albertel 5722: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 5723: if ($symbparm && defined($courseid) &&
1.620 albertel 5724: $courseid eq $env{'request.course.id'}) {
1.624 albertel 5725: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
5726: $env{'course.'.$courseid.'.domain'},
5727: 'course',
5728: ($courselevelm,$courselevel));
1.593 albertel 5729: if (defined($coursereply)) { return $coursereply; }
5730: }
1.145 www 5731: # ------------------------------------------------------------------ Cascade up
1.218 albertel 5732: unless ($space eq '0') {
1.336 albertel 5733: my @parts=split(/_/,$space);
5734: my $id=pop(@parts);
5735: my $part=join('_',@parts);
5736: if ($part eq '') { $part='0'; }
5737: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 5738: $symbparm,$udom,$uname,$section,1);
1.337 albertel 5739: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 5740: }
1.395 albertel 5741: if ($recurse) { return undef; }
5742: my $pack_def=&packages_tab_default($filename,$varname);
5743: if (defined($pack_def)) { return $pack_def; }
1.71 www 5744:
1.48 www 5745: # ---------------------------------------------------- Any other user namespace
5746: } elsif ($realm eq 'environment') {
5747: # ----------------------------------------------------------------- environment
1.620 albertel 5748: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
5749: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 5750: } else {
1.770 albertel 5751: if ($uname eq 'anonymous' && $udom eq '') {
5752: return '';
5753: }
1.219 albertel 5754: my %returnhash=&userenvironment($udom,$uname,
5755: $spacequalifierrest);
5756: return $returnhash{$spacequalifierrest};
5757: }
1.28 www 5758: } elsif ($realm eq 'system') {
1.48 www 5759: # ----------------------------------------------------------------- system.time
5760: if ($space eq 'time') {
5761: return time;
5762: }
1.696 albertel 5763: } elsif ($realm eq 'server') {
5764: # ----------------------------------------------------------------- system.time
5765: if ($space eq 'name') {
5766: return $ENV{'SERVER_NAME'};
5767: }
1.28 www 5768: }
1.48 www 5769: return '';
1.61 www 5770: }
5771:
1.691 raeburn 5772: sub check_group_parms {
5773: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
5774: my @groupitems = ();
5775: my $resultitem;
5776: my @levels = ($symbparm,$mapparm,$what);
5777: foreach my $group (@{$groups}) {
5778: foreach my $level (@levels) {
5779: my $item = $courseid.'.['.$group.'].'.$level;
5780: push(@groupitems,$item);
5781: }
5782: }
5783: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
5784: $env{'course.'.$courseid.'.domain'},
5785: 'course',@groupitems);
5786: return $coursereply;
5787: }
5788:
5789: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 5790: my ($courseid,@groups) = @_;
5791: @groups = sort(@groups);
1.691 raeburn 5792: return @groups;
5793: }
5794:
1.395 albertel 5795: sub packages_tab_default {
5796: my ($uri,$varname)=@_;
5797: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 5798:
5799: my (@extension,@specifics,$do_default);
5800: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 5801: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 5802: if ($pack_type eq 'default') {
5803: $do_default=1;
5804: } elsif ($pack_type eq 'extension') {
5805: push(@extension,[$package,$pack_type,$pack_part]);
5806: } else {
5807: push(@specifics,[$package,$pack_type,$pack_part]);
5808: }
5809: }
5810: # first look for a package that matches the requested part id
5811: foreach my $package (@specifics) {
5812: my (undef,$pack_type,$pack_part)=@{$package};
5813: next if ($pack_part ne $part);
5814: if (defined($packagetab{"$pack_type&$name&default"})) {
5815: return $packagetab{"$pack_type&$name&default"};
5816: }
5817: }
5818: # look for any possible matching non extension_ package
5819: foreach my $package (@specifics) {
5820: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 5821: if (defined($packagetab{"$pack_type&$name&default"})) {
5822: return $packagetab{"$pack_type&$name&default"};
5823: }
1.585 albertel 5824: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 5825: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
5826: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 5827: }
5828: }
1.738 albertel 5829: # look for any posible extension_ match
5830: foreach my $package (@extension) {
5831: my ($package,$pack_type)=@{$package};
5832: if (defined($packagetab{"$pack_type&$name&default"})) {
5833: return $packagetab{"$pack_type&$name&default"};
5834: }
5835: if (defined($packagetab{$package."&$name&default"})) {
5836: return $packagetab{$package."&$name&default"};
5837: }
5838: }
5839: # look for a global default setting
5840: if ($do_default && defined($packagetab{"default&$name&default"})) {
5841: return $packagetab{"default&$name&default"};
5842: }
1.395 albertel 5843: return undef;
5844: }
5845:
1.334 albertel 5846: sub add_prefix_and_part {
5847: my ($prefix,$part)=@_;
5848: my $keyroot;
5849: if (defined($prefix) && $prefix !~ /^__/) {
5850: # prefix that has a part already
5851: $keyroot=$prefix;
5852: } elsif (defined($prefix)) {
5853: # prefix that is missing a part
5854: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
5855: } else {
5856: # no prefix at all
5857: if (defined($part)) { $keyroot='_'.$part; }
5858: }
5859: return $keyroot;
5860: }
5861:
1.71 www 5862: # ---------------------------------------------------------------- Get metadata
5863:
1.599 albertel 5864: my %metaentry;
1.71 www 5865: sub metadata {
1.176 www 5866: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 5867: $uri=&declutter($uri);
1.288 albertel 5868: # if it is a non metadata possible uri return quickly
1.529 albertel 5869: if (($uri eq '') ||
5870: (($uri =~ m|^/*adm/|) &&
1.698 albertel 5871: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 5872: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489 albertel 5873: ($uri =~ m|home/[^/]+/public_html/|)) {
1.468 albertel 5874: return undef;
1.288 albertel 5875: }
1.73 www 5876: my $filename=$uri;
5877: $uri=~s/\.meta$//;
1.172 www 5878: #
5879: # Is the metadata already cached?
1.177 www 5880: # Look at timestamp of caching
1.172 www 5881: # Everything is cached by the main uri, libraries are never directly cached
5882: #
1.428 albertel 5883: if (!defined($liburi)) {
1.599 albertel 5884: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 5885: if (defined($cached)) { return $result->{':'.$what}; }
5886: }
5887: {
1.172 www 5888: #
5889: # Is this a recursive call for a library?
5890: #
1.599 albertel 5891: # if (! exists($metacache{$uri})) {
5892: # $metacache{$uri}={};
5893: # }
1.171 www 5894: if ($liburi) {
5895: $liburi=&declutter($liburi);
5896: $filename=$liburi;
1.401 bowersj2 5897: } else {
1.599 albertel 5898: &devalidate_cache_new('meta',$uri);
5899: undef(%metaentry);
1.401 bowersj2 5900: }
1.140 www 5901: my %metathesekeys=();
1.73 www 5902: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 5903: my $metastring;
1.768 albertel 5904: if ($uri !~ m -^(editupload)/-) {
1.543 albertel 5905: my $file=&filelocation('',&clutter($filename));
1.599 albertel 5906: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 5907: $metastring=&getfile($file);
1.489 albertel 5908: }
1.208 albertel 5909: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 5910: my $token;
1.140 www 5911: undef %metathesekeys;
1.71 www 5912: while ($token=$parser->get_token) {
1.339 albertel 5913: if ($token->[0] eq 'S') {
5914: if (defined($token->[2]->{'package'})) {
1.172 www 5915: #
5916: # This is a package - get package info
5917: #
1.339 albertel 5918: my $package=$token->[2]->{'package'};
5919: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
5920: if (defined($token->[2]->{'id'})) {
5921: $keyroot.='_'.$token->[2]->{'id'};
5922: }
1.599 albertel 5923: if ($metaentry{':packages'}) {
5924: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 5925: } else {
1.599 albertel 5926: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 5927: }
1.736 albertel 5928: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 5929: my $part=$keyroot;
5930: $part=~s/^\_//;
1.736 albertel 5931: if ($pack_entry=~/^\Q$package\E\&/ ||
5932: $pack_entry=~/^\Q$package\E_0\&/) {
5933: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 5934: # ignore package.tab specified default values
5935: # here &package_tab_default() will fetch those
5936: if ($subp eq 'default') { next; }
1.736 albertel 5937: my $value=$packagetab{$pack_entry};
1.432 albertel 5938: my $unikey;
5939: if ($pack =~ /_0$/) {
5940: $unikey='parameter_0_'.$name;
5941: $part=0;
5942: } else {
5943: $unikey='parameter'.$keyroot.'_'.$name;
5944: }
1.339 albertel 5945: if ($subp eq 'display') {
5946: $value.=' [Part: '.$part.']';
5947: }
1.599 albertel 5948: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 5949: $metathesekeys{$unikey}=1;
1.599 albertel 5950: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
5951: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 5952: }
1.599 albertel 5953: if (defined($metaentry{':'.$unikey.'.default'})) {
5954: $metaentry{':'.$unikey}=
5955: $metaentry{':'.$unikey.'.default'};
1.356 albertel 5956: }
1.339 albertel 5957: }
5958: }
5959: } else {
1.172 www 5960: #
5961: # This is not a package - some other kind of start tag
1.339 albertel 5962: #
5963: my $entry=$token->[1];
5964: my $unikey;
5965: if ($entry eq 'import') {
5966: $unikey='';
5967: } else {
5968: $unikey=$entry;
5969: }
5970: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
5971:
5972: if (defined($token->[2]->{'id'})) {
5973: $unikey.='_'.$token->[2]->{'id'};
5974: }
1.175 www 5975:
1.339 albertel 5976: if ($entry eq 'import') {
1.175 www 5977: #
5978: # Importing a library here
1.339 albertel 5979: #
5980: if ($depthcount<20) {
5981: my $location=$parser->get_text('/import');
5982: my $dir=$filename;
5983: $dir=~s|[^/]*$||;
5984: $location=&filelocation($dir,$location);
1.736 albertel 5985: my $metadata =
5986: &metadata($uri,'keys', $location,$unikey,
5987: $depthcount+1);
5988: foreach my $meta (split(',',$metadata)) {
5989: $metaentry{':'.$meta}=$metaentry{':'.$meta};
5990: $metathesekeys{$meta}=1;
1.339 albertel 5991: }
5992: }
5993: } else {
5994:
5995: if (defined($token->[2]->{'name'})) {
5996: $unikey.='_'.$token->[2]->{'name'};
5997: }
5998: $metathesekeys{$unikey}=1;
1.736 albertel 5999: foreach my $param (@{$token->[3]}) {
6000: $metaentry{':'.$unikey.'.'.$param} =
6001: $token->[2]->{$param};
1.339 albertel 6002: }
6003: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6004: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6005: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6006: # only ws inside the tag, and not in default, so use default
6007: # as value
1.599 albertel 6008: $metaentry{':'.$unikey}=$default;
1.339 albertel 6009: } else {
1.321 albertel 6010: # either something interesting inside the tag or default
6011: # uninteresting
1.599 albertel 6012: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6013: }
1.172 www 6014: # end of not-a-package not-a-library import
1.339 albertel 6015: }
1.172 www 6016: # end of not-a-package start tag
1.339 albertel 6017: }
1.172 www 6018: # the next is the end of "start tag"
1.339 albertel 6019: }
6020: }
1.483 albertel 6021: my ($extension) = ($uri =~ /\.(\w+)$/);
1.737 albertel 6022: foreach my $key (keys(%packagetab)) {
1.483 albertel 6023: #no specific packages #how's our extension
6024: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6025: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6026: \%metathesekeys);
6027: }
1.599 albertel 6028: if (!exists($metaentry{':packages'})) {
1.737 albertel 6029: foreach my $key (keys(%packagetab)) {
1.483 albertel 6030: #no specific packages well let's get default then
6031: if ($key!~/^default&/) { next; }
1.488 albertel 6032: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 6033: \%metathesekeys);
6034: }
6035: }
1.338 www 6036: # are there custom rights to evaluate
1.599 albertel 6037: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 6038:
1.338 www 6039: #
6040: # Importing a rights file here
1.339 albertel 6041: #
6042: unless ($depthcount) {
1.599 albertel 6043: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 6044: my $dir=$filename;
6045: $dir=~s|[^/]*$||;
6046: $location=&filelocation($dir,$location);
1.736 albertel 6047: my $rights_metadata =
6048: &metadata($uri,'keys',$location,'_rights',
6049: $depthcount+1);
6050: foreach my $rights (split(',',$rights_metadata)) {
6051: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6052: $metathesekeys{$rights}=1;
1.339 albertel 6053: }
6054: }
6055: }
1.737 albertel 6056: # uniqifiy package listing
6057: my %seen;
6058: my @uniq_packages =
6059: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6060: $metaentry{':packages'} = join(',',@uniq_packages);
6061:
6062: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 6063: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6064: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699 albertel 6065: &do_cache_new('meta',$uri,\%metaentry,60*60);
1.177 www 6066: # this is the end of "was not already recently cached
1.71 www 6067: }
1.599 albertel 6068: return $metaentry{':'.$what};
1.261 albertel 6069: }
6070:
1.488 albertel 6071: sub metadata_create_package_def {
1.483 albertel 6072: my ($uri,$key,$package,$metathesekeys)=@_;
6073: my ($pack,$name,$subp)=split(/\&/,$key);
6074: if ($subp eq 'default') { next; }
6075:
1.599 albertel 6076: if (defined($metaentry{':packages'})) {
6077: $metaentry{':packages'}.=','.$package;
1.483 albertel 6078: } else {
1.599 albertel 6079: $metaentry{':packages'}=$package;
1.483 albertel 6080: }
6081: my $value=$packagetab{$key};
6082: my $unikey;
6083: $unikey='parameter_0_'.$name;
1.599 albertel 6084: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 6085: $$metathesekeys{$unikey}=1;
1.599 albertel 6086: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6087: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 6088: }
1.599 albertel 6089: if (defined($metaentry{':'.$unikey.'.default'})) {
6090: $metaentry{':'.$unikey}=
6091: $metaentry{':'.$unikey.'.default'};
1.483 albertel 6092: }
6093: }
6094:
1.261 albertel 6095: sub metadata_generate_part0 {
6096: my ($metadata,$metacache,$uri) = @_;
6097: my %allnames;
1.737 albertel 6098: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 6099: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 6100: my $part=$$metacache{':'.$metakey.'.part'};
6101: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 6102: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 6103: $allnames{$name}=$part;
6104: }
6105: }
6106: }
6107: foreach my $name (keys(%allnames)) {
6108: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 6109: my $key=":parameter_0_$name";
1.261 albertel 6110: $$metacache{"$key.part"}='0';
6111: $$metacache{"$key.name"}=$name;
1.428 albertel 6112: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 6113: $allnames{$name}.'_'.$name.
6114: '.type'};
1.428 albertel 6115: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 6116: '.display'};
1.644 www 6117: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 6118: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 6119: $$metacache{"$key.display"}=$olddis;
6120: }
1.71 www 6121: }
6122:
1.764 albertel 6123: # ------------------------------------------------------ Devalidate title cache
6124:
6125: sub devalidate_title_cache {
6126: my ($url)=@_;
6127: if (!$env{'request.course.id'}) { return; }
6128: my $symb=&symbread($url);
6129: if (!$symb) { return; }
6130: my $key=$env{'request.course.id'}."\0".$symb;
6131: &devalidate_cache_new('title',$key);
6132: }
6133:
1.301 www 6134: # ------------------------------------------------- Get the title of a resource
6135:
6136: sub gettitle {
6137: my $urlsymb=shift;
6138: my $symb=&symbread($urlsymb);
1.534 albertel 6139: if ($symb) {
1.620 albertel 6140: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 6141: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 6142: if (defined($cached)) {
6143: return $result;
6144: }
1.534 albertel 6145: my ($map,$resid,$url)=&decode_symb($symb);
6146: my $title='';
6147: my %bighash;
1.620 albertel 6148: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534 albertel 6149: &GDBM_READER(),0640)) {
6150: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6151: $title=$bighash{'title_'.$mapid.'.'.$resid};
6152: untie %bighash;
6153: }
6154: $title=~s/\&colon\;/\:/gs;
6155: if ($title) {
1.599 albertel 6156: return &do_cache_new('title',$key,$title,600);
1.534 albertel 6157: }
6158: $urlsymb=$url;
6159: }
6160: my $title=&metadata($urlsymb,'title');
6161: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6162: return $title;
1.301 www 6163: }
1.613 albertel 6164:
1.614 albertel 6165: sub get_slot {
6166: my ($which,$cnum,$cdom)=@_;
6167: if (!$cnum || !$cdom) {
6168: (undef,my $courseid)=&Apache::lonxml::whichuser();
1.620 albertel 6169: $cdom=$env{'course.'.$courseid.'.domain'};
6170: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 6171: }
1.703 albertel 6172: my $key=join("\0",'slots',$cdom,$cnum,$which);
6173: my %slotinfo;
6174: if (exists($remembered{$key})) {
6175: $slotinfo{$which} = $remembered{$key};
6176: } else {
6177: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6178: &Apache::lonhomework::showhash(%slotinfo);
6179: my ($tmp)=keys(%slotinfo);
6180: if ($tmp=~/^error:/) { return (); }
6181: $remembered{$key} = $slotinfo{$which};
6182: }
1.616 albertel 6183: if (ref($slotinfo{$which}) eq 'HASH') {
6184: return %{$slotinfo{$which}};
6185: }
6186: return $slotinfo{$which};
1.614 albertel 6187: }
1.31 www 6188: # ------------------------------------------------- Update symbolic store links
6189:
6190: sub symblist {
6191: my ($mapname,%newhash)=@_;
1.438 www 6192: $mapname=&deversion(&declutter($mapname));
1.31 www 6193: my %hash;
1.620 albertel 6194: if (($env{'request.course.fn'}) && (%newhash)) {
6195: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6196: &GDBM_WRCREAT(),0640)) {
1.711 albertel 6197: foreach my $url (keys %newhash) {
6198: next if ($url eq 'last_known'
6199: && $env{'form.no_update_last_known'});
6200: $hash{declutter($url)}=&encode_symb($mapname,
6201: $newhash{$url}->[1],
6202: $newhash{$url}->[0]);
1.191 harris41 6203: }
1.31 www 6204: if (untie(%hash)) {
6205: return 'ok';
6206: }
6207: }
6208: }
6209: return 'error';
1.212 www 6210: }
6211:
6212: # --------------------------------------------------------------- Verify a symb
6213:
6214: sub symbverify {
1.510 www 6215: my ($symb,$thisurl)=@_;
6216: my $thisfn=$thisurl;
1.439 www 6217: $thisfn=&declutter($thisfn);
1.215 www 6218: # direct jump to resource in page or to a sequence - will construct own symbs
6219: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6220: # check URL part
1.409 www 6221: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 6222:
1.431 www 6223: unless ($url eq $thisfn) { return 0; }
1.213 www 6224:
1.216 www 6225: $symb=&symbclean($symb);
1.510 www 6226: $thisurl=&deversion($thisurl);
1.439 www 6227: $thisfn=&deversion($thisfn);
1.213 www 6228:
6229: my %bighash;
6230: my $okay=0;
1.431 www 6231:
1.620 albertel 6232: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6233: &GDBM_READER(),0640)) {
1.510 www 6234: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 6235: unless ($ids) {
1.510 www 6236: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 6237: }
6238: if ($ids) {
6239: # ------------------------------------------------------------------- Has ID(s)
6240: foreach (split(/\,/,$ids)) {
1.644 www 6241: my ($mapid,$resid)=split(/\./,$_);
1.216 www 6242: if (
6243: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6244: eq $symb) {
1.620 albertel 6245: if (($env{'request.role.adv'}) ||
6246: $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582 albertel 6247: $okay=1;
6248: }
6249: }
1.216 www 6250: }
6251: }
1.213 www 6252: untie(%bighash);
6253: }
6254: return $okay;
1.31 www 6255: }
6256:
1.210 www 6257: # --------------------------------------------------------------- Clean-up symb
6258:
6259: sub symbclean {
6260: my $symb=shift;
1.568 albertel 6261: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 6262: # remove version from map
6263: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 6264:
1.210 www 6265: # remove version from URL
6266: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 6267:
1.507 www 6268: # remove wrapper
6269:
1.510 www 6270: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 6271: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 6272: return $symb;
1.409 www 6273: }
6274:
6275: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 6276:
6277: sub encode_symb {
6278: my ($map,$resid,$url)=@_;
6279: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6280: }
1.409 www 6281:
6282: sub decode_symb {
1.568 albertel 6283: my $symb=shift;
6284: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6285: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 6286: return (&fixversion($map),$resid,&fixversion($url));
6287: }
6288:
6289: sub fixversion {
6290: my $fn=shift;
1.609 banghart 6291: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 6292: my %bighash;
6293: my $uri=&clutter($fn);
1.620 albertel 6294: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 6295: # is this cached?
1.599 albertel 6296: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 6297: if (defined($cached)) { return $result; }
6298: # unfortunately not cached, or expired
1.620 albertel 6299: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 6300: &GDBM_READER(),0640)) {
6301: if ($bighash{'version_'.$uri}) {
6302: my $version=$bighash{'version_'.$uri};
1.444 www 6303: unless (($version eq 'mostrecent') ||
6304: ($version==&getversion($uri))) {
1.440 www 6305: $uri=~s/\.(\w+)$/\.$version\.$1/;
6306: }
6307: }
6308: untie %bighash;
1.413 www 6309: }
1.599 albertel 6310: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 6311: }
6312:
6313: sub deversion {
6314: my $url=shift;
6315: $url=~s/\.\d+\.(\w+)$/\.$1/;
6316: return $url;
1.210 www 6317: }
6318:
1.31 www 6319: # ------------------------------------------------------ Return symb list entry
6320:
6321: sub symbread {
1.249 www 6322: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 6323: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 6324: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 6325: # no filename provided? try from environment
1.44 www 6326: unless ($thisfn) {
1.620 albertel 6327: if ($env{'request.symb'}) {
6328: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 6329: }
1.620 albertel 6330: $thisfn=$env{'request.filename'};
1.44 www 6331: }
1.569 albertel 6332: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 6333: # is that filename actually a symb? Verify, clean, and return
6334: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 6335: if (&symbverify($thisfn,$1)) {
1.620 albertel 6336: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 6337: }
1.242 www 6338: }
1.44 www 6339: $thisfn=declutter($thisfn);
1.31 www 6340: my %hash;
1.37 www 6341: my %bighash;
6342: my $syval='';
1.620 albertel 6343: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 6344: my $targetfn = $thisfn;
1.609 banghart 6345: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 6346: $targetfn = 'adm/wrapper/'.$thisfn;
6347: }
1.687 albertel 6348: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6349: $targetfn=$1;
6350: }
1.620 albertel 6351: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6352: &GDBM_READER(),0640)) {
1.481 raeburn 6353: $syval=$hash{$targetfn};
1.37 www 6354: untie(%hash);
6355: }
6356: # ---------------------------------------------------------- There was an entry
6357: if ($syval) {
1.601 albertel 6358: #unless ($syval=~/\_\d+$/) {
1.620 albertel 6359: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 6360: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 6361: #return $env{$cache_str}='';
1.601 albertel 6362: #}
6363: #$syval.=$1;
6364: #}
1.37 www 6365: } else {
6366: # ------------------------------------------------------- Was not in symb table
1.620 albertel 6367: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6368: &GDBM_READER(),0640)) {
1.37 www 6369: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 6370: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 6371: unless ($ids) {
6372: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 6373: }
6374: unless ($ids) {
6375: # alias?
6376: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 6377: }
1.37 www 6378: if ($ids) {
6379: # ------------------------------------------------------------------- Has ID(s)
6380: my @possibilities=split(/\,/,$ids);
1.39 www 6381: if ($#possibilities==0) {
6382: # ----------------------------------------------- There is only one possibility
1.37 www 6383: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 6384: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6385: $resid,$thisfn);
1.249 www 6386: } elsif (!$donotrecurse) {
1.39 www 6387: # ------------------------------------------ There is more than one possibility
6388: my $realpossible=0;
1.191 harris41 6389: foreach (@possibilities) {
1.39 www 6390: my $file=$bighash{'src_'.$_};
6391: if (&allowed('bre',$file)) {
6392: my ($mapid,$resid)=split(/\./,$_);
6393: if ($bighash{'map_type_'.$mapid} ne 'page') {
6394: $realpossible++;
1.626 albertel 6395: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6396: $resid,$thisfn);
1.39 www 6397: }
6398: }
1.191 harris41 6399: }
1.39 www 6400: if ($realpossible!=1) { $syval=''; }
1.249 www 6401: } else {
6402: $syval='';
1.37 www 6403: }
6404: }
6405: untie(%bighash)
1.481 raeburn 6406: }
1.31 www 6407: }
1.62 www 6408: if ($syval) {
1.620 albertel 6409: return $env{$cache_str}=$syval;
1.62 www 6410: }
1.31 www 6411: }
1.44 www 6412: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 6413: return $env{$cache_str}='';
1.31 www 6414: }
6415:
6416: # ---------------------------------------------------------- Return random seed
6417:
1.32 www 6418: sub numval {
6419: my $txt=shift;
6420: $txt=~tr/A-J/0-9/;
6421: $txt=~tr/a-j/0-9/;
6422: $txt=~tr/K-T/0-9/;
6423: $txt=~tr/k-t/0-9/;
6424: $txt=~tr/U-Z/0-5/;
6425: $txt=~tr/u-z/0-5/;
6426: $txt=~s/\D//g;
1.564 albertel 6427: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 6428: return int($txt);
1.368 albertel 6429: }
6430:
1.484 albertel 6431: sub numval2 {
6432: my $txt=shift;
6433: $txt=~tr/A-J/0-9/;
6434: $txt=~tr/a-j/0-9/;
6435: $txt=~tr/K-T/0-9/;
6436: $txt=~tr/k-t/0-9/;
6437: $txt=~tr/U-Z/0-5/;
6438: $txt=~tr/u-z/0-5/;
6439: $txt=~s/\D//g;
6440: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6441: my $total;
6442: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 6443: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 6444: return int($total);
6445: }
6446:
1.575 albertel 6447: sub numval3 {
6448: use integer;
6449: my $txt=shift;
6450: $txt=~tr/A-J/0-9/;
6451: $txt=~tr/a-j/0-9/;
6452: $txt=~tr/K-T/0-9/;
6453: $txt=~tr/k-t/0-9/;
6454: $txt=~tr/U-Z/0-5/;
6455: $txt=~tr/u-z/0-5/;
6456: $txt=~s/\D//g;
6457: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6458: my $total;
6459: foreach my $val (@txts) { $total+=$val; }
6460: if ($_64bit) { $total=(($total<<32)>>32); }
6461: return $total;
6462: }
6463:
1.675 albertel 6464: sub digest {
6465: my ($data)=@_;
6466: my $digest=&Digest::MD5::md5($data);
6467: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6468: my ($e,$f);
6469: {
6470: use integer;
6471: $e=($a+$b);
6472: $f=($c+$d);
6473: if ($_64bit) {
6474: $e=(($e<<32)>>32);
6475: $f=(($f<<32)>>32);
6476: }
6477: }
6478: if (wantarray) {
6479: return ($e,$f);
6480: } else {
6481: my $g;
6482: {
6483: use integer;
6484: $g=($e+$f);
6485: if ($_64bit) {
6486: $g=(($g<<32)>>32);
6487: }
6488: }
6489: return $g;
6490: }
6491: }
6492:
1.368 albertel 6493: sub latest_rnd_algorithm_id {
1.675 albertel 6494: return '64bit5';
1.366 albertel 6495: }
1.32 www 6496:
1.503 albertel 6497: sub get_rand_alg {
6498: my ($courseid)=@_;
6499: if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
6500: if ($courseid) {
1.620 albertel 6501: return $env{"course.$courseid.rndseed"};
1.503 albertel 6502: }
6503: return &latest_rnd_algorithm_id();
6504: }
6505:
1.562 albertel 6506: sub validCODE {
6507: my ($CODE)=@_;
6508: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6509: return 0;
6510: }
6511:
1.491 albertel 6512: sub getCODE {
1.620 albertel 6513: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 6514: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
6515: defined($Apache::lonhomework::parsing_a_task) ) &&
6516: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 6517: return $Apache::lonhomework::history{'resource.CODE'};
6518: }
6519: return undef;
6520: }
6521:
1.31 www 6522: sub rndseed {
1.155 albertel 6523: my ($symb,$courseid,$domain,$username)=@_;
1.366 albertel 6524:
6525: my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
1.155 albertel 6526: if (!$symb) {
1.366 albertel 6527: unless ($symb=$wsymb) { return time; }
6528: }
6529: if (!$courseid) { $courseid=$wcourseid; }
6530: if (!$domain) { $domain=$wdomain; }
6531: if (!$username) { $username=$wusername }
1.503 albertel 6532: my $which=&get_rand_alg();
1.491 albertel 6533: if (defined(&getCODE())) {
1.675 albertel 6534: if ($which eq '64bit5') {
6535: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
6536: } elsif ($which eq '64bit4') {
1.575 albertel 6537: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
6538: } else {
6539: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
6540: }
1.675 albertel 6541: } elsif ($which eq '64bit5') {
6542: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 6543: } elsif ($which eq '64bit4') {
6544: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 6545: } elsif ($which eq '64bit3') {
6546: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 6547: } elsif ($which eq '64bit2') {
6548: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 6549: } elsif ($which eq '64bit') {
6550: return &rndseed_64bit($symb,$courseid,$domain,$username);
6551: }
6552: return &rndseed_32bit($symb,$courseid,$domain,$username);
6553: }
6554:
6555: sub rndseed_32bit {
6556: my ($symb,$courseid,$domain,$username)=@_;
6557: {
6558: use integer;
6559: my $symbchck=unpack("%32C*",$symb) << 27;
6560: my $symbseed=numval($symb) << 22;
6561: my $namechck=unpack("%32C*",$username) << 17;
6562: my $nameseed=numval($username) << 12;
6563: my $domainseed=unpack("%32C*",$domain) << 7;
6564: my $courseseed=unpack("%32C*",$courseid);
6565: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
6566: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6567: #&Apache::lonxml::debug("rndseed :$num:$symb");
1.564 albertel 6568: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 6569: return $num;
6570: }
6571: }
6572:
6573: sub rndseed_64bit {
6574: my ($symb,$courseid,$domain,$username)=@_;
6575: {
6576: use integer;
6577: my $symbchck=unpack("%32S*",$symb) << 21;
6578: my $symbseed=numval($symb) << 10;
6579: my $namechck=unpack("%32S*",$username);
6580:
6581: my $nameseed=numval($username) << 21;
6582: my $domainseed=unpack("%32S*",$domain) << 10;
6583: my $courseseed=unpack("%32S*",$courseid);
6584:
6585: my $num1=$symbchck+$symbseed+$namechck;
6586: my $num2=$nameseed+$domainseed+$courseseed;
6587: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6588: #&Apache::lonxml::debug("rndseed :$num:$symb");
1.564 albertel 6589: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6590: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 6591: return "$num1,$num2";
1.155 albertel 6592: }
1.366 albertel 6593: }
6594:
1.443 albertel 6595: sub rndseed_64bit2 {
6596: my ($symb,$courseid,$domain,$username)=@_;
6597: {
6598: use integer;
6599: # strings need to be an even # of cahracters long, it it is odd the
6600: # last characters gets thrown away
6601: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6602: my $symbseed=numval($symb) << 10;
6603: my $namechck=unpack("%32S*",$username.' ');
6604:
6605: my $nameseed=numval($username) << 21;
1.501 albertel 6606: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6607: my $courseseed=unpack("%32S*",$courseid.' ');
6608:
6609: my $num1=$symbchck+$symbseed+$namechck;
6610: my $num2=$nameseed+$domainseed+$courseseed;
6611: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6612: #&Apache::lonxml::debug("rndseed :$num:$symb");
6613: return "$num1,$num2";
6614: }
6615: }
6616:
6617: sub rndseed_64bit3 {
6618: my ($symb,$courseid,$domain,$username)=@_;
6619: {
6620: use integer;
6621: # strings need to be an even # of cahracters long, it it is odd the
6622: # last characters gets thrown away
6623: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6624: my $symbseed=numval2($symb) << 10;
6625: my $namechck=unpack("%32S*",$username.' ');
6626:
6627: my $nameseed=numval2($username) << 21;
1.443 albertel 6628: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6629: my $courseseed=unpack("%32S*",$courseid.' ');
6630:
6631: my $num1=$symbchck+$symbseed+$namechck;
6632: my $num2=$nameseed+$domainseed+$courseseed;
6633: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
1.564 albertel 6634: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
6635: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6636:
1.503 albertel 6637: return "$num1:$num2";
1.443 albertel 6638: }
6639: }
6640:
1.575 albertel 6641: sub rndseed_64bit4 {
6642: my ($symb,$courseid,$domain,$username)=@_;
6643: {
6644: use integer;
6645: # strings need to be an even # of cahracters long, it it is odd the
6646: # last characters gets thrown away
6647: my $symbchck=unpack("%32S*",$symb.' ') << 21;
6648: my $symbseed=numval3($symb) << 10;
6649: my $namechck=unpack("%32S*",$username.' ');
6650:
6651: my $nameseed=numval3($username) << 21;
6652: my $domainseed=unpack("%32S*",$domain.' ') << 10;
6653: my $courseseed=unpack("%32S*",$courseid.' ');
6654:
6655: my $num1=$symbchck+$symbseed+$namechck;
6656: my $num2=$nameseed+$domainseed+$courseseed;
6657: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
6658: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
6659: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
6660:
6661: return "$num1:$num2";
6662: }
6663: }
6664:
1.675 albertel 6665: sub rndseed_64bit5 {
6666: my ($symb,$courseid,$domain,$username)=@_;
6667: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
6668: return "$num1:$num2";
6669: }
6670:
1.366 albertel 6671: sub rndseed_CODE_64bit {
6672: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 6673: {
1.366 albertel 6674: use integer;
1.443 albertel 6675: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 6676: my $symbseed=numval2($symb);
1.491 albertel 6677: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6678: my $CODEseed=numval(&getCODE());
1.443 albertel 6679: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 6680: my $num1=$symbseed+$CODEchck;
6681: my $num2=$CODEseed+$courseseed+$symbchck;
6682: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
1.366 albertel 6683: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
1.564 albertel 6684: if ($_64bit) { $num1=(($num1<<32)>>32); }
6685: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 6686: return "$num1:$num2";
1.366 albertel 6687: }
6688: }
6689:
1.575 albertel 6690: sub rndseed_CODE_64bit4 {
6691: my ($symb,$courseid,$domain,$username)=@_;
6692: {
6693: use integer;
6694: my $symbchck=unpack("%32S*",$symb.' ') << 16;
6695: my $symbseed=numval3($symb);
6696: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
6697: my $CODEseed=numval3(&getCODE());
6698: my $courseseed=unpack("%32S*",$courseid.' ');
6699: my $num1=$symbseed+$CODEchck;
6700: my $num2=$CODEseed+$courseseed+$symbchck;
6701: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
6702: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
6703: if ($_64bit) { $num1=(($num1<<32)>>32); }
6704: if ($_64bit) { $num2=(($num2<<32)>>32); }
6705: return "$num1:$num2";
6706: }
6707: }
6708:
1.675 albertel 6709: sub rndseed_CODE_64bit5 {
6710: my ($symb,$courseid,$domain,$username)=@_;
6711: my $code = &getCODE();
6712: my ($num1,$num2)=&digest("$symb,$courseid,$code");
6713: return "$num1:$num2";
6714: }
6715:
1.366 albertel 6716: sub setup_random_from_rndseed {
6717: my ($rndseed)=@_;
1.503 albertel 6718: if ($rndseed =~/([,:])/) {
6719: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 6720: &Math::Random::random_set_seed(abs($num1),abs($num2));
6721: } else {
6722: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 6723: }
1.36 albertel 6724: }
6725:
1.474 albertel 6726: sub latest_receipt_algorithm_id {
6727: return 'receipt2';
6728: }
6729:
1.480 www 6730: sub recunique {
6731: my $fucourseid=shift;
6732: my $unique;
1.620 albertel 6733: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
6734: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 6735: } else {
6736: $unique=$perlvar{'lonReceipt'};
6737: }
6738: return unpack("%32C*",$unique);
6739: }
6740:
6741: sub recprefix {
6742: my $fucourseid=shift;
6743: my $prefix;
1.620 albertel 6744: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
6745: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 6746: } else {
6747: $prefix=$perlvar{'lonHostID'};
6748: }
6749: return unpack("%32C*",$prefix);
6750: }
6751:
1.76 www 6752: sub ireceipt {
1.474 albertel 6753: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76 www 6754: my $cuname=unpack("%32C*",$funame);
6755: my $cudom=unpack("%32C*",$fudom);
6756: my $cucourseid=unpack("%32C*",$fucourseid);
6757: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 6758: my $cunique=&recunique($fucourseid);
1.474 albertel 6759: my $cpart=unpack("%32S*",$part);
1.480 www 6760: my $return =&recprefix($fucourseid).'-';
1.620 albertel 6761: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
6762: $env{'request.state'} eq 'construct') {
1.474 albertel 6763: &Apache::lonxml::debug("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname).
6764: " and ".($cpart%$cudom));
6765:
6766: $return.= ($cunique%$cuname+
6767: $cunique%$cudom+
6768: $cusymb%$cuname+
6769: $cusymb%$cudom+
6770: $cucourseid%$cuname+
6771: $cucourseid%$cudom+
6772: $cpart%$cuname+
6773: $cpart%$cudom);
6774: } else {
6775: $return.= ($cunique%$cuname+
6776: $cunique%$cudom+
6777: $cusymb%$cuname+
6778: $cusymb%$cudom+
6779: $cucourseid%$cuname+
6780: $cucourseid%$cudom);
6781: }
6782: return $return;
1.76 www 6783: }
6784:
6785: sub receipt {
1.474 albertel 6786: my ($part)=@_;
6787: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
6788: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 6789: }
1.260 ng 6790:
1.36 albertel 6791: # ------------------------------------------------------------ Serves up a file
1.472 albertel 6792: # returns either the contents of the file or
6793: # -1 if the file doesn't exist
1.481 raeburn 6794: #
6795: # if the target is a file that was uploaded via DOCS,
6796: # a check will be made to see if a current copy exists on the local server,
6797: # if it does this will be served, otherwise a copy will be retrieved from
6798: # the home server for the course and stored in /home/httpd/html/userfiles on
6799: # the local server.
1.472 albertel 6800:
1.36 albertel 6801: sub getfile {
1.538 albertel 6802: my ($file) = @_;
1.609 banghart 6803: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 6804: &repcopy($file);
6805: return &readfile($file);
6806: }
6807:
6808: sub repcopy_userfile {
6809: my ($file)=@_;
1.609 banghart 6810: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 6811: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 6812: my ($cdom,$cnum,$filename) =
6813: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
6814: my ($info,$rtncode);
6815: my $uri="/uploaded/$cdom/$cnum/$filename";
6816: if (-e "$file") {
6817: my @fileinfo = stat($file);
6818: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 6819: if ($lwpresp ne 'ok') {
6820: if ($rtncode eq '404') {
1.538 albertel 6821: unlink($file);
1.482 albertel 6822: }
1.517 albertel 6823: #my $ua=new LWP::UserAgent;
1.538 albertel 6824: #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517 albertel 6825: #my $response=$ua->request($request);
6826: #if ($response->is_success()) {
6827: # return $response->content;
6828: # } else {
6829: # return -1;
6830: # }
1.482 albertel 6831: return -1;
6832: }
6833: if ($info < $fileinfo[9]) {
1.607 raeburn 6834: return 'ok';
1.482 albertel 6835: }
6836: $info = '';
1.538 albertel 6837: $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 6838: if ($lwpresp ne 'ok') {
6839: return -1;
6840: }
6841: } else {
1.538 albertel 6842: my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 6843: if ($lwpresp ne 'ok') {
1.517 albertel 6844: my $ua=new LWP::UserAgent;
1.538 albertel 6845: my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517 albertel 6846: my $response=$ua->request($request);
6847: if ($response->is_success()) {
1.538 albertel 6848: $info=$response->content;
1.517 albertel 6849: } else {
6850: return -1;
6851: }
1.482 albertel 6852: }
6853: my @parts = ($cdom,$cnum);
6854: if ($filename =~ m|^(.+)/[^/]+$|) {
6855: push @parts, split(/\//,$1);
1.518 albertel 6856: }
1.538 albertel 6857: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482 albertel 6858: foreach my $part (@parts) {
6859: $path .= '/'.$part;
6860: if (!-e $path) {
6861: mkdir($path,0770);
6862: }
6863: }
6864: }
1.538 albertel 6865: open(FILE,">$file");
1.482 albertel 6866: print FILE $info;
6867: close(FILE);
1.607 raeburn 6868: return 'ok';
1.481 raeburn 6869: }
6870:
1.517 albertel 6871: sub tokenwrapper {
6872: my $uri=shift;
1.552 albertel 6873: $uri=~s|^http\://([^/]+)||;
6874: $uri=~s|^/||;
1.620 albertel 6875: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 6876: my $token=$1;
1.552 albertel 6877: my (undef,$udom,$uname,$file)=split('/',$uri,4);
6878: if ($udom && $uname && $file) {
6879: $file=~s|(\?\.*)*$||;
1.620 albertel 6880: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552 albertel 6881: return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517 albertel 6882: (($uri=~/\?/)?'&':'?').'token='.$token.
6883: '&tokenissued='.$perlvar{'lonHostID'};
6884: } else {
6885: return '/adm/notfound.html';
6886: }
6887: }
6888:
1.481 raeburn 6889: sub getuploaded {
6890: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
6891: $uri=~s/^\///;
6892: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
6893: my $ua=new LWP::UserAgent;
6894: my $request=new HTTP::Request($reqtype,$uri);
6895: my $response=$ua->request($request);
6896: $$rtncode = $response->code;
1.482 albertel 6897: if (! $response->is_success()) {
6898: return 'failed';
6899: }
6900: if ($reqtype eq 'HEAD') {
1.486 www 6901: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 6902: } elsif ($reqtype eq 'GET') {
6903: $$info = $response->content;
1.472 albertel 6904: }
1.482 albertel 6905: return 'ok';
1.36 albertel 6906: }
6907:
1.481 raeburn 6908: sub readfile {
6909: my $file = shift;
6910: if ( (! -e $file ) || ($file eq '') ) { return -1; };
6911: my $fh;
6912: open($fh,"<$file");
6913: my $a='';
6914: while (<$fh>) { $a .=$_; }
6915: return $a;
6916: }
6917:
1.36 albertel 6918: sub filelocation {
1.590 banghart 6919: my ($dir,$file) = @_;
6920: my $location;
6921: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 6922:
6923: if ($file =~ m-^/adm/-) {
6924: $file=~s-^/adm/wrapper/-/-;
6925: $file=~s-^/adm/coursedocs/showdoc/-/-;
6926: }
1.590 banghart 6927: if ($file=~m:^/~:) { # is a contruction space reference
6928: $location = $file;
6929: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649 albertel 6930: } elsif ($file=~m:^/home/[^/]*/public_html/:) {
6931: # is a correct contruction space reference
6932: $location = $file;
1.609 banghart 6933: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 6934: my ($udom,$uname,$filename)=
1.609 banghart 6935: ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590 banghart 6936: my $home=&homeserver($uname,$udom);
6937: my $is_me=0;
6938: my @ids=¤t_machine_ids();
6939: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
6940: if ($is_me) {
1.740 www 6941: $location=&propath($udom,$uname).
1.590 banghart 6942: '/userfiles/'.$filename;
6943: } else {
6944: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
6945: $udom.'/'.$uname.'/'.$filename;
6946: }
6947: } else {
6948: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
6949: $file=~s:^/res/:/:;
6950: if ( !( $file =~ m:^/:) ) {
6951: $location = $dir. '/'.$file;
6952: } else {
6953: $location = '/home/httpd/html/res'.$file;
6954: }
1.59 albertel 6955: }
1.590 banghart 6956: $location=~s://+:/:g; # remove duplicate /
6957: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
6958: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
6959: return $location;
1.46 www 6960: }
1.36 albertel 6961:
1.46 www 6962: sub hreflocation {
6963: my ($dir,$file)=@_;
1.460 albertel 6964: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 6965: $file=filelocation($dir,$file);
1.700 albertel 6966: } elsif ($file=~m-^/adm/-) {
6967: $file=~s-^/adm/wrapper/-/-;
6968: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 6969: }
6970: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
6971: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
6972: } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462 albertel 6973: $file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666 albertel 6974: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
6975: $file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
6976: -/uploaded/$1/$2/-x;
1.46 www 6977: }
1.462 albertel 6978: return $file;
1.465 albertel 6979: }
6980:
6981: sub current_machine_domains {
6982: my $hostname=$hostname{$perlvar{'lonHostID'}};
6983: my @domains;
6984: while( my($id, $name) = each(%hostname)) {
1.467 matthew 6985: # &logthis("-$id-$name-$hostname-");
1.465 albertel 6986: if ($hostname eq $name) {
6987: push(@domains,$hostdom{$id});
6988: }
6989: }
6990: return @domains;
6991: }
6992:
6993: sub current_machine_ids {
6994: my $hostname=$hostname{$perlvar{'lonHostID'}};
6995: my @ids;
6996: while( my($id, $name) = each(%hostname)) {
1.467 matthew 6997: # &logthis("-$id-$name-$hostname-");
1.465 albertel 6998: if ($hostname eq $name) {
6999: push(@ids,$id);
7000: }
7001: }
7002: return @ids;
1.31 www 7003: }
7004:
7005: # ------------------------------------------------------------- Declutters URLs
7006:
7007: sub declutter {
7008: my $thisfn=shift;
1.569 albertel 7009: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 7010: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 7011: $thisfn=~s/^\///;
1.697 albertel 7012: $thisfn=~s|^adm/wrapper/||;
7013: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 7014: $thisfn=~s/^res\///;
1.235 www 7015: $thisfn=~s/\?.+$//;
1.268 www 7016: return $thisfn;
7017: }
7018:
7019: # ------------------------------------------------------------- Clutter up URLs
7020:
7021: sub clutter {
7022: my $thisfn='/'.&declutter(shift);
1.609 banghart 7023: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 7024: $thisfn='/res'.$thisfn;
7025: }
1.694 albertel 7026: if ($thisfn !~m|/adm|) {
1.695 albertel 7027: if ($thisfn =~ m|/ext/|) {
1.694 albertel 7028: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 7029: } else {
7030: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7031: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 7032: if ($embstyle eq 'ssi'
7033: || ($embstyle eq 'hdn')
7034: || ($embstyle eq 'rat')
7035: || ($embstyle eq 'prv')
7036: || ($embstyle eq 'ign')) {
7037: #do nothing with these
7038: } elsif (($embstyle eq 'img')
1.695 albertel 7039: || ($embstyle eq 'emb')
7040: || ($embstyle eq 'wrp')) {
7041: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 7042: } elsif ($embstyle eq 'unk'
7043: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 7044: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 7045: } else {
1.718 www 7046: # &logthis("Got a blank emb style");
1.695 albertel 7047: }
1.694 albertel 7048: }
7049: }
1.31 www 7050: return $thisfn;
1.12 www 7051: }
7052:
1.787 albertel 7053: sub clutter_with_no_wrapper {
7054: my $uri = &clutter(shift);
7055: if ($uri =~ m-^/adm/-) {
7056: $uri =~ s-^/adm/wrapper/-/-;
7057: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7058: }
7059: return $uri;
7060: }
7061:
1.557 albertel 7062: sub freeze_escape {
7063: my ($value)=@_;
7064: if (ref($value)) {
7065: $value=&nfreeze($value);
7066: return '__FROZEN__'.&escape($value);
7067: }
7068: return &escape($value);
7069: }
7070:
1.11 www 7071:
1.557 albertel 7072: sub thaw_unescape {
7073: my ($value)=@_;
7074: if ($value =~ /^__FROZEN__/) {
7075: substr($value,0,10,undef);
7076: $value=&unescape($value);
7077: return &thaw($value);
7078: }
7079: return &unescape($value);
7080: }
7081:
1.436 albertel 7082: sub correct_line_ends {
7083: my ($result)=@_;
7084: $$result =~s/\r\n/\n/mg;
7085: $$result =~s/\r/\n/mg;
1.415 albertel 7086: }
1.1 albertel 7087: # ================================================================ Main Program
7088:
1.184 www 7089: sub goodbye {
1.204 albertel 7090: &logthis("Starting Shut down");
1.443 albertel 7091: #not converted to using infrastruture and probably shouldn't be
1.599 albertel 7092: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443 albertel 7093: #converted
1.599 albertel 7094: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
7095: &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
7096: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
7097: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425 albertel 7098: #1.1 only
1.599 albertel 7099: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
7100: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
7101: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
7102: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
7103: &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
7104: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7105: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 7106: &flushcourselogs();
7107: &logthis("Shutting down");
7108: }
7109:
1.179 www 7110: BEGIN {
1.228 harris41 7111: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195 www 7112: unless ($readit) {
1.217 harris41 7113: {
1.781 raeburn 7114: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7115: %perlvar = (%perlvar,%{$configvars});
1.227 harris41 7116: }
1.1 albertel 7117:
1.327 albertel 7118: # ------------------------------------------------------------ Read domain file
7119: {
7120: %domaindescription = ();
7121: %domain_auth_def = ();
7122: %domain_auth_arg_def = ();
1.448 albertel 7123: my $fh;
7124: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327 albertel 7125: while (<$fh>) {
1.390 matthew 7126: next if (/^(\#|\s*$)/);
7127: # next if /^\#/;
1.327 albertel 7128: chomp;
1.403 www 7129: my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685 raeburn 7130: $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403 www 7131: $domain_auth_def{$domain}=$def_auth;
1.327 albertel 7132: $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403 www 7133: $domaindescription{$domain}=$domain_description;
7134: $domain_lang_def{$domain}=$def_lang;
7135: $domain_city{$domain}=$city;
7136: $domain_longi{$domain}=$longi;
7137: $domain_lati{$domain}=$lati;
1.685 raeburn 7138: $domain_primary{$domain}=$primary;
1.403 www 7139:
1.448 albertel 7140: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327 albertel 7141: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448 albertel 7142: }
1.327 albertel 7143: }
1.448 albertel 7144: close ($fh);
1.327 albertel 7145: }
7146:
7147:
1.1 albertel 7148: # ------------------------------------------------------------- Read hosts file
7149: {
1.448 albertel 7150: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1 albertel 7151:
7152: while (my $configline=<$config>) {
1.303 matthew 7153: next if ($configline =~ /^(\#|\s*$)/);
1.154 www 7154: chomp($configline);
1.595 albertel 7155: my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597 albertel 7156: $name=~s/\s//g;
1.595 albertel 7157: if ($id && $domain && $role && $name) {
1.252 albertel 7158: $hostname{$id}=$name;
7159: $hostdom{$id}=$domain;
7160: if ($role eq 'library') { $libserv{$id}=$name; }
1.245 www 7161: }
1.1 albertel 7162: }
1.448 albertel 7163: close($config);
1.619 albertel 7164: # FIXME: dev server don't want this, production servers _do_ want this
1.654 albertel 7165: #&get_iphost();
1.1 albertel 7166: }
7167:
1.598 albertel 7168: sub get_iphost {
7169: if (%iphost) { return %iphost; }
1.653 albertel 7170: my %name_to_ip;
1.598 albertel 7171: foreach my $id (keys(%hostname)) {
7172: my $name=$hostname{$id};
1.653 albertel 7173: my $ip;
7174: if (!exists($name_to_ip{$name})) {
7175: $ip = gethostbyname($name);
7176: if (!$ip || length($ip) ne 4) {
7177: &logthis("Skipping host $id name $name no IP found\n");
7178: next;
7179: }
7180: $ip=inet_ntoa($ip);
7181: $name_to_ip{$name} = $ip;
7182: } else {
7183: $ip = $name_to_ip{$name};
1.598 albertel 7184: }
7185: push(@{$iphost{$ip}},$id);
7186: }
7187: return %iphost;
7188: }
7189:
1.1 albertel 7190: # ------------------------------------------------------ Read spare server file
7191: {
1.448 albertel 7192: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 7193:
7194: while (my $configline=<$config>) {
7195: chomp($configline);
1.284 matthew 7196: if ($configline) {
1.784 albertel 7197: my ($host,$type) = split(':',$configline,2);
1.785 albertel 7198: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 7199: push(@{ $spareid{$type} }, $host);
1.1 albertel 7200: }
7201: }
1.448 albertel 7202: close($config);
1.1 albertel 7203: }
1.11 www 7204: # ------------------------------------------------------------ Read permissions
7205: {
1.448 albertel 7206: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 7207:
7208: while (my $configline=<$config>) {
1.448 albertel 7209: chomp($configline);
7210: if ($configline) {
7211: my ($role,$perm)=split(/ /,$configline);
7212: if ($perm ne '') { $pr{$role}=$perm; }
7213: }
1.11 www 7214: }
1.448 albertel 7215: close($config);
1.11 www 7216: }
7217:
7218: # -------------------------------------------- Read plain texts for permissions
7219: {
1.448 albertel 7220: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 7221:
7222: while (my $configline=<$config>) {
1.448 albertel 7223: chomp($configline);
7224: if ($configline) {
1.742 raeburn 7225: my ($short,@plain)=split(/:/,$configline);
7226: %{$prp{$short}} = ();
7227: if (@plain > 0) {
7228: $prp{$short}{'std'} = $plain[0];
7229: for (my $i=1; $i<@plain; $i++) {
7230: $prp{$short}{'alt'.$i} = $plain[$i];
7231: }
7232: }
1.448 albertel 7233: }
1.135 www 7234: }
1.448 albertel 7235: close($config);
1.135 www 7236: }
7237:
7238: # ---------------------------------------------------------- Read package table
7239: {
1.448 albertel 7240: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 7241:
7242: while (my $configline=<$config>) {
1.483 albertel 7243: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 7244: chomp($configline);
7245: my ($short,$plain)=split(/:/,$configline);
7246: my ($pack,$name)=split(/\&/,$short);
7247: if ($plain ne '') {
7248: $packagetab{$pack.'&'.$name.'&name'}=$name;
7249: $packagetab{$short}=$plain;
7250: }
1.11 www 7251: }
1.448 albertel 7252: close($config);
1.329 matthew 7253: }
7254:
7255: # ------------- set up temporary directory
7256: {
7257: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
7258:
1.11 www 7259: }
7260:
1.599 albertel 7261: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.185 www 7262:
1.281 www 7263: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 7264: $dumpcount=0;
1.22 www 7265:
1.163 harris41 7266: &logtouch();
1.672 albertel 7267: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 7268: $readit=1;
1.564 albertel 7269: {
7270: use integer;
7271: my $test=(2**32)+1;
1.568 albertel 7272: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 7273: &logthis(" Detected 64bit platform ($_64bit)");
7274: }
1.195 www 7275: }
1.1 albertel 7276: }
1.179 www 7277:
1.1 albertel 7278: 1;
1.191 harris41 7279: __END__
7280:
1.243 albertel 7281: =pod
7282:
1.191 harris41 7283: =head1 NAME
7284:
1.243 albertel 7285: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 7286:
7287: =head1 SYNOPSIS
7288:
1.243 albertel 7289: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 7290:
7291: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
7292:
1.243 albertel 7293: Common parameters:
7294:
7295: =over 4
7296:
7297: =item *
7298:
7299: $uname : an internal username (if $cname expecting a course Id specifically)
7300:
7301: =item *
7302:
7303: $udom : a domain (if $cdom expecting a course's domain specifically)
7304:
7305: =item *
7306:
7307: $symb : a resource instance identifier
7308:
7309: =item *
7310:
7311: $namespace : the name of a .db file that contains the data needed or
7312: being set.
7313:
7314: =back
7315:
1.394 bowersj2 7316: =head1 OVERVIEW
1.191 harris41 7317:
1.394 bowersj2 7318: lonnet provides subroutines which interact with the
7319: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
7320: about classes, users, and resources.
1.243 albertel 7321:
7322: For many of these objects you can also use this to store data about
7323: them or modify them in various ways.
1.191 harris41 7324:
1.394 bowersj2 7325: =head2 Symbs
1.191 harris41 7326:
1.394 bowersj2 7327: To identify a specific instance of a resource, LON-CAPA uses symbols
7328: or "symbs"X<symb>. These identifiers are built from the URL of the
7329: map, the resource number of the resource in the map, and the URL of
7330: the resource itself. The latter is somewhat redundant, but might help
7331: if maps change.
7332:
7333: An example is
7334:
7335: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
7336:
7337: The respective map entry is
7338:
7339: <resource id="19" src="/res/msu/korte/tests/part12.problem"
7340: title="Problem 2">
7341: </resource>
7342:
7343: Symbs are used by the random number generator, as well as to store and
7344: restore data specific to a certain instance of for example a problem.
7345:
7346: =head2 Storing And Retrieving Data
7347:
7348: X<store()>X<cstore()>X<restore()>Three of the most important functions
7349: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
7350: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
7351: is is the non-critical message twin of cstore. These functions are for
7352: handlers to store a perl hash to a user's permanent data space in an
7353: easy manner, and to retrieve it again on another call. It is expected
7354: that a handler would use this once at the beginning to retrieve data,
7355: and then again once at the end to send only the new data back.
7356:
7357: The data is stored in the user's data directory on the user's
7358: homeserver under the ID of the course.
7359:
7360: The hash that is returned by restore will have all of the previous
7361: value for all of the elements of the hash.
7362:
7363: Example:
7364:
7365: #creating a hash
7366: my %hash;
7367: $hash{'foo'}='bar';
7368:
7369: #storing it
7370: &Apache::lonnet::cstore(\%hash);
7371:
7372: #changing a value
7373: $hash{'foo'}='notbar';
7374:
7375: #adding a new value
7376: $hash{'bar'}='foo';
7377: &Apache::lonnet::cstore(\%hash);
7378:
7379: #retrieving the hash
7380: my %history=&Apache::lonnet::restore();
7381:
7382: #print the hash
7383: foreach my $key (sort(keys(%history))) {
7384: print("\%history{$key} = $history{$key}");
7385: }
7386:
7387: Will print out:
1.191 harris41 7388:
1.394 bowersj2 7389: %history{1:foo} = bar
7390: %history{1:keys} = foo:timestamp
7391: %history{1:timestamp} = 990455579
7392: %history{2:bar} = foo
7393: %history{2:foo} = notbar
7394: %history{2:keys} = foo:bar:timestamp
7395: %history{2:timestamp} = 990455580
7396: %history{bar} = foo
7397: %history{foo} = notbar
7398: %history{timestamp} = 990455580
7399: %history{version} = 2
7400:
7401: Note that the special hash entries C<keys>, C<version> and
7402: C<timestamp> were added to the hash. C<version> will be equal to the
7403: total number of versions of the data that have been stored. The
7404: C<timestamp> attribute will be the UNIX time the hash was
7405: stored. C<keys> is available in every historical section to list which
7406: keys were added or changed at a specific historical revision of a
7407: hash.
7408:
7409: B<Warning>: do not store the hash that restore returns directly. This
7410: will cause a mess since it will restore the historical keys as if the
7411: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 7412:
1.394 bowersj2 7413: Calling convention:
1.191 harris41 7414:
1.394 bowersj2 7415: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
7416: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 7417:
1.394 bowersj2 7418: For more detailed information, see lonnet specific documentation.
1.191 harris41 7419:
1.394 bowersj2 7420: =head1 RETURN MESSAGES
1.191 harris41 7421:
1.394 bowersj2 7422: =over 4
1.191 harris41 7423:
1.394 bowersj2 7424: =item * B<con_lost>: unable to contact remote host
1.191 harris41 7425:
1.394 bowersj2 7426: =item * B<con_delayed>: unable to contact remote host, message will be delivered
7427: when the connection is brought back up
1.191 harris41 7428:
1.394 bowersj2 7429: =item * B<con_failed>: unable to contact remote host and unable to save message
7430: for later delivery
1.191 harris41 7431:
1.394 bowersj2 7432: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 7433:
1.394 bowersj2 7434: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 7435: that was requested
1.191 harris41 7436:
1.243 albertel 7437: =back
1.191 harris41 7438:
1.243 albertel 7439: =head1 PUBLIC SUBROUTINES
1.191 harris41 7440:
1.243 albertel 7441: =head2 Session Environment Functions
1.191 harris41 7442:
1.243 albertel 7443: =over 4
1.191 harris41 7444:
1.394 bowersj2 7445: =item *
7446: X<appenv()>
7447: B<appenv(%hash)>: the value of %hash is written to
7448: the user envirnoment file, and will be restored for each access this
1.620 albertel 7449: user makes during this session, also modifies the %env for the current
1.394 bowersj2 7450: process
1.191 harris41 7451:
7452: =item *
1.394 bowersj2 7453: X<delenv()>
7454: B<delenv($regexp)>: removes all items from the session
7455: environment file that matches the regular expression in $regexp. The
1.620 albertel 7456: values are also delted from the current processes %env.
1.191 harris41 7457:
1.243 albertel 7458: =back
7459:
7460: =head2 User Information
1.191 harris41 7461:
1.243 albertel 7462: =over 4
1.191 harris41 7463:
7464: =item *
1.394 bowersj2 7465: X<queryauthenticate()>
7466: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 7467: authentication scheme
7468:
7469: =item *
1.394 bowersj2 7470: X<authenticate()>
7471: B<authenticate($uname,$upass,$udom)>: try to
7472: authenticate user from domain's lib servers (first use the current
7473: one). C<$upass> should be the users password.
1.191 harris41 7474:
7475: =item *
1.394 bowersj2 7476: X<homeserver()>
7477: B<homeserver($uname,$udom)>: find the server which has
7478: the user's directory and files (there must be only one), this caches
7479: the answer, and also caches if there is a borken connection.
1.191 harris41 7480:
7481: =item *
1.394 bowersj2 7482: X<idget()>
7483: B<idget($udom,@ids)>: find the usernames behind a list of IDs
7484: (IDs are a unique resource in a domain, there must be only 1 ID per
7485: username, and only 1 username per ID in a specific domain) (returns
7486: hash: id=>name,id=>name)
1.191 harris41 7487:
7488: =item *
1.394 bowersj2 7489: X<idrget()>
7490: B<idrget($udom,@unames)>: find the IDs behind a list of
7491: usernames (returns hash: name=>id,name=>id)
1.191 harris41 7492:
7493: =item *
1.394 bowersj2 7494: X<idput()>
7495: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 7496:
7497: =item *
1.394 bowersj2 7498: X<rolesinit()>
7499: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 7500:
7501: =item *
1.551 albertel 7502: X<getsection()>
7503: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 7504: course $cname, return section name/number or '' for "not in course"
7505: and '-1' for "no section"
7506:
7507: =item *
1.394 bowersj2 7508: X<userenvironment()>
7509: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 7510: passed in @what from the requested user's environment, returns a hash
7511:
7512: =back
7513:
7514: =head2 User Roles
7515:
7516: =over 4
7517:
7518: =item *
7519:
7520: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
7521: actions
7522: F: full access
7523: U,I,K: authentication modes (cxx only)
7524: '': forbidden
7525: 1: user needs to choose course
7526: 2: browse allowed
1.766 albertel 7527: A: passphrase authentication needed
1.243 albertel 7528:
7529: =item *
7530:
7531: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
7532: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
7533: and course level
7534:
7535: =item *
7536:
7537: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
7538: explanation of a user role term
7539:
7540: =back
7541:
7542: =head2 User Modification
7543:
7544: =over 4
7545:
7546: =item *
7547:
7548: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
7549: user for the level given by URL. Optional start and end dates (leave empty
7550: string or zero for "no date")
1.191 harris41 7551:
7552: =item *
7553:
1.243 albertel 7554: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
7555: change a users, password, possible return values are: ok,
7556: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
7557: refused
1.191 harris41 7558:
7559: =item *
7560:
1.243 albertel 7561: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 7562:
7563: =item *
7564:
1.243 albertel 7565: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
7566: modify user
1.191 harris41 7567:
7568: =item *
7569:
1.286 matthew 7570: modifystudent
7571:
7572: modify a students enrollment and identification information.
7573: The course id is resolved based on the current users environment.
7574: This means the envoking user must be a course coordinator or otherwise
7575: associated with a course.
7576:
1.297 matthew 7577: This call is essentially a wrapper for lonnet::modifyuser and
7578: lonnet::modify_student_enrollment
1.286 matthew 7579:
7580: Inputs:
7581:
7582: =over 4
7583:
7584: =item B<$udom> Students loncapa domain
7585:
7586: =item B<$uname> Students loncapa login name
7587:
7588: =item B<$uid> Students id/student number
7589:
7590: =item B<$umode> Students authentication mode
7591:
7592: =item B<$upass> Students password
7593:
7594: =item B<$first> Students first name
7595:
7596: =item B<$middle> Students middle name
7597:
7598: =item B<$last> Students last name
7599:
7600: =item B<$gene> Students generation
7601:
7602: =item B<$usec> Students section in course
7603:
7604: =item B<$end> Unix time of the roles expiration
7605:
7606: =item B<$start> Unix time of the roles start date
7607:
7608: =item B<$forceid> If defined, allow $uid to be changed
7609:
7610: =item B<$desiredhome> server to use as home server for student
7611:
7612: =back
1.297 matthew 7613:
7614: =item *
7615:
7616: modify_student_enrollment
7617:
7618: Change a students enrollment status in a class. The environment variable
7619: 'role.request.course' must be defined for this function to proceed.
7620:
7621: Inputs:
7622:
7623: =over 4
7624:
7625: =item $udom, students domain
7626:
7627: =item $uname, students name
7628:
7629: =item $uid, students user id
7630:
7631: =item $first, students first name
7632:
7633: =item $middle
7634:
7635: =item $last
7636:
7637: =item $gene
7638:
7639: =item $usec
7640:
7641: =item $end
7642:
7643: =item $start
7644:
7645: =back
7646:
1.191 harris41 7647:
7648: =item *
7649:
1.243 albertel 7650: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
7651: custom role; give a custom role to a user for the level given by URL. Specify
7652: name and domain of role author, and role name
1.191 harris41 7653:
7654: =item *
7655:
1.243 albertel 7656: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 7657:
7658: =item *
7659:
1.243 albertel 7660: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
7661:
7662: =back
7663:
7664: =head2 Course Infomation
7665:
7666: =over 4
1.191 harris41 7667:
7668: =item *
7669:
1.631 albertel 7670: coursedescription($courseid) : returns a hash of information about the
7671: specified course id, including all environment settings for the
7672: course, the description of the course will be in the hash under the
7673: key 'description'
1.191 harris41 7674:
7675: =item *
7676:
1.624 albertel 7677: resdata($name,$domain,$type,@which) : request for current parameter
7678: setting for a specific $type, where $type is either 'course' or 'user',
7679: @what should be a list of parameters to ask about. This routine caches
7680: answers for 5 minutes.
1.243 albertel 7681:
7682: =back
7683:
7684: =head2 Course Modification
7685:
7686: =over 4
1.191 harris41 7687:
7688: =item *
7689:
1.243 albertel 7690: writecoursepref($courseid,%prefs) : write preferences (environment
7691: database) for a course
1.191 harris41 7692:
7693: =item *
7694:
1.243 albertel 7695: createcourse($udom,$description,$url) : make/modify course
7696:
7697: =back
7698:
7699: =head2 Resource Subroutines
7700:
7701: =over 4
1.191 harris41 7702:
7703: =item *
7704:
1.243 albertel 7705: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 7706:
7707: =item *
7708:
1.243 albertel 7709: repcopy($filename) : subscribes to the requested file, and attempts to
7710: replicate from the owning library server, Might return
1.607 raeburn 7711: 'unavailable', 'not_found', 'forbidden', 'ok', or
7712: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 7713: resource. Expects the local filesystem pathname
7714: (/home/httpd/html/res/....)
7715:
7716: =back
7717:
7718: =head2 Resource Information
7719:
7720: =over 4
1.191 harris41 7721:
7722: =item *
7723:
1.243 albertel 7724: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
7725: a vairety of different possible values, $varname should be a request
7726: string, and the other parameters can be used to specify who and what
7727: one is asking about.
7728:
7729: Possible values for $varname are environment.lastname (or other item
7730: from the envirnment hash), user.name (or someother aspect about the
7731: user), resource.0.maxtries (or some other part and parameter of a
7732: resource)
1.204 albertel 7733:
7734: =item *
7735:
1.243 albertel 7736: directcondval($number) : get current value of a condition; reads from a state
7737: string
1.204 albertel 7738:
7739: =item *
7740:
1.243 albertel 7741: condval($condidx) : value of condition index based on state
1.204 albertel 7742:
7743: =item *
7744:
1.243 albertel 7745: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
7746: resource's metadata, $what should be either a specific key, or either
7747: 'keys' (to get a list of possible keys) or 'packages' to get a list of
7748: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
7749:
7750: this function automatically caches all requests
1.191 harris41 7751:
7752: =item *
7753:
1.243 albertel 7754: metadata_query($query,$custom,$customshow) : make a metadata query against the
7755: network of library servers; returns file handle of where SQL and regex results
7756: will be stored for query
1.191 harris41 7757:
7758: =item *
7759:
1.243 albertel 7760: symbread($filename) : return symbolic list entry (filename argument optional);
7761: returns the data handle
1.191 harris41 7762:
7763: =item *
7764:
1.243 albertel 7765: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 7766: a possible symb for the URL in $thisfn, and if is an encryypted
7767: resource that the user accessed using /enc/ returns a 1 on success, 0
7768: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 7769: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 7770:
1.191 harris41 7771:
7772: =item *
7773:
1.243 albertel 7774: symbclean($symb) : removes versions numbers from a symb, returns the
7775: cleaned symb
1.191 harris41 7776:
7777: =item *
7778:
1.243 albertel 7779: is_on_map($uri) : checks if the $uri is somewhere on the current
7780: course map, user must be in a course for it to work.
1.191 harris41 7781:
7782: =item *
7783:
1.243 albertel 7784: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 7785:
7786: =item *
7787:
1.243 albertel 7788: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
7789: a random seed, all arguments are optional, if they aren't sent it uses the
7790: environment to derive them. Note: if symb isn't sent and it can't get one
7791: from &symbread it will use the current time as its return value
1.191 harris41 7792:
7793: =item *
7794:
1.243 albertel 7795: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
7796: unfakeable, receipt
1.191 harris41 7797:
7798: =item *
7799:
1.620 albertel 7800: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 7801:
7802: =item *
7803:
1.243 albertel 7804: countacc($url) : count the number of accesses to a given URL
1.191 harris41 7805:
7806: =item *
7807:
1.243 albertel 7808: 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 7809:
7810: =item *
7811:
1.243 albertel 7812: 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 7813:
7814: =item *
7815:
1.243 albertel 7816: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 7817:
7818: =item *
7819:
1.243 albertel 7820: devalidate($symb) : devalidate temporary spreadsheet calculations,
7821: forcing spreadsheet to reevaluate the resource scores next time.
7822:
7823: =back
7824:
7825: =head2 Storing/Retreiving Data
7826:
7827: =over 4
1.191 harris41 7828:
7829: =item *
7830:
1.243 albertel 7831: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
7832: for this url; hashref needs to be given and should be a \%hashname; the
7833: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 7834: be derived from the env
1.191 harris41 7835:
7836: =item *
7837:
1.243 albertel 7838: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
7839: uses critical subroutine
1.191 harris41 7840:
7841: =item *
7842:
1.243 albertel 7843: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
7844: all args are optional
1.191 harris41 7845:
7846: =item *
7847:
1.717 albertel 7848: dumpstore($namespace,$udom,$uname,$regexp,$range) :
7849: dumps the complete (or key matching regexp) namespace into a hash
7850: ($udom, $uname, $regexp, $range are optional) for a namespace that is
7851: normally &store()ed into
7852:
7853: $range should be either an integer '100' (give me the first 100
7854: matching records)
7855: or be two integers sperated by a - with no spaces
7856: '30-50' (give me the 30th through the 50th matching
7857: records)
7858:
7859:
7860: =item *
7861:
7862: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
7863: replaces a &store() version of data with a replacement set of data
7864: for a particular resource in a namespace passed in the $storehash hash
7865: reference
7866:
7867: =item *
7868:
1.243 albertel 7869: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
7870: works very similar to store/cstore, but all data is stored in a
7871: temporary location and can be reset using tmpreset, $storehash should
7872: be a hash reference, returns nothing on success
1.191 harris41 7873:
7874: =item *
7875:
1.243 albertel 7876: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
7877: similar to restore, but all data is stored in a temporary location and
7878: can be reset using tmpreset. Returns a hash of values on success,
7879: error string otherwise.
1.191 harris41 7880:
7881: =item *
7882:
1.243 albertel 7883: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
7884: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 7885:
7886: =item *
7887:
1.243 albertel 7888: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
7889: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 7890:
7891: =item *
7892:
1.243 albertel 7893: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
7894: namesp ($udom and $uname are optional)
1.191 harris41 7895:
7896: =item *
7897:
1.702 albertel 7898: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 7899: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 7900: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 7901:
1.702 albertel 7902: $range should be either an integer '100' (give me the first 100
7903: matching records)
7904: or be two integers sperated by a - with no spaces
7905: '30-50' (give me the 30th through the 50th matching
7906: records)
1.449 matthew 7907: =item *
7908:
7909: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
7910: $store can be a scalar, an array reference, or if the amount to be
7911: incremented is > 1, a hash reference.
7912:
7913: ($udom and $uname are optional)
1.191 harris41 7914:
7915: =item *
7916:
1.243 albertel 7917: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
7918: ($udom and $uname are optional)
1.191 harris41 7919:
7920: =item *
7921:
1.243 albertel 7922: cput($namespace,$storehash,$udom,$uname) : critical put
7923: ($udom and $uname are optional)
1.191 harris41 7924:
7925: =item *
7926:
1.748 albertel 7927: newput($namespace,$storehash,$udom,$uname) :
7928:
7929: Attempts to store the items in the $storehash, but only if they don't
7930: currently exist, if this succeeds you can be certain that you have
7931: successfully created a new key value pair in the $namespace db.
7932:
7933:
7934: Args:
7935: $namespace: name of database to store values to
7936: $storehash: hashref to store to the db
7937: $udom: (optional) domain of user containing the db
7938: $uname: (optional) name of user caontaining the db
7939:
7940: Returns:
7941: 'ok' -> succeeded in storing all keys of $storehash
7942: 'key_exists: <key>' -> failed to anything out of $storehash, as at
7943: least <key> already existed in the db (other
7944: requested keys may also already exist)
7945: 'error: <msg>' -> unable to tie the DB or other erorr occured
7946: 'con_lost' -> unable to contact request server
7947: 'refused' -> action was not allowed by remote machine
7948:
7949:
7950: =item *
7951:
1.243 albertel 7952: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
7953: reference filled in from namesp (encrypts the return communication)
7954: ($udom and $uname are optional)
1.191 harris41 7955:
7956: =item *
7957:
1.243 albertel 7958: log($udom,$name,$home,$message) : write to permanent log for user; use
7959: critical subroutine
7960:
7961: =back
7962:
7963: =head2 Network Status Functions
7964:
7965: =over 4
1.191 harris41 7966:
7967: =item *
7968:
7969: dirlist($uri) : return directory list based on URI
7970:
7971: =item *
7972:
1.243 albertel 7973: spareserver() : find server with least workload from spare.tab
7974:
7975: =back
7976:
7977: =head2 Apache Request
7978:
7979: =over 4
1.191 harris41 7980:
7981: =item *
7982:
1.243 albertel 7983: ssi($url,%hash) : server side include, does a complete request cycle on url to
7984: localhost, posts hash
7985:
7986: =back
7987:
7988: =head2 Data to String to Data
7989:
7990: =over 4
1.191 harris41 7991:
7992: =item *
7993:
1.243 albertel 7994: hash2str(%hash) : convert a hash into a string complete with escaping and '='
7995: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 7996:
7997: =item *
7998:
1.243 albertel 7999: hashref2str($hashref) : convert a hashref into a string complete with
8000: escaping and '=' and '&' separators, supports elements that are
8001: arrayrefs and hashrefs
1.191 harris41 8002:
8003: =item *
8004:
1.243 albertel 8005: arrayref2str($arrayref) : convert an arrayref into a string complete
8006: with escaping and '&' separators, supports elements that are arrayrefs
8007: and hashrefs
1.191 harris41 8008:
8009: =item *
8010:
1.243 albertel 8011: str2hash($string) : convert string to hash using unescaping and
8012: splitting on '=' and '&', supports elements that are arrayrefs and
8013: hashrefs
1.191 harris41 8014:
8015: =item *
8016:
1.243 albertel 8017: str2array($string) : convert string to hash using unescaping and
8018: splitting on '&', supports elements that are arrayrefs and hashrefs
8019:
8020: =back
8021:
8022: =head2 Logging Routines
8023:
8024: =over 4
8025:
8026: These routines allow one to make log messages in the lonnet.log and
8027: lonnet.perm logfiles.
1.191 harris41 8028:
8029: =item *
8030:
1.243 albertel 8031: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 8032:
8033: =item *
8034:
1.243 albertel 8035: logthis() : append message to the normal lonnet.log file, it gets
8036: preiodically rolled over and deleted.
1.191 harris41 8037:
8038: =item *
8039:
1.243 albertel 8040: logperm() : append a permanent message to lonnet.perm.log, this log
8041: file never gets deleted by any automated portion of the system, only
8042: messages of critical importance should go in here.
8043:
8044: =back
8045:
8046: =head2 General File Helper Routines
8047:
8048: =over 4
1.191 harris41 8049:
8050: =item *
8051:
1.481 raeburn 8052: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8053: (a) files in /uploaded
8054: (i) If a local copy of the file exists -
8055: compares modification date of local copy with last-modified date for
8056: definitive version stored on home server for course. If local copy is
8057: stale, requests a new version from the home server and stores it.
8058: If the original has been removed from the home server, then local copy
8059: is unlinked.
8060: (ii) If local copy does not exist -
8061: requests the file from the home server and stores it.
8062:
8063: If $caller is 'uploadrep':
8064: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8065: for request for files originally uploaded via DOCS.
8066: - returns 'ok' if fresh local copy now available, -1 otherwise.
8067:
8068: Otherwise:
8069: This indicates a call from the content generation phase of the request.
8070: - returns the entire contents of the file or -1.
8071:
8072: (b) files in /res
8073: - returns the entire contents of a file or -1;
8074: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 8075:
1.712 albertel 8076:
8077: =item *
8078:
8079: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8080: reference
8081:
8082: returns either a stat() list of data about the file or an empty list
8083: if the file doesn't exist or couldn't find out about it (connection
8084: problems or user unknown)
8085:
1.191 harris41 8086: =item *
8087:
1.243 albertel 8088: filelocation($dir,$file) : returns file system location of a file
8089: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8090: directory that relative $file lookups are to looked in ($dir of /a/dir
8091: and a file of ../bob will become /a/bob)
1.191 harris41 8092:
8093: =item *
8094:
8095: hreflocation($dir,$file) : returns file system location or a URL; same as
8096: filelocation except for hrefs
8097:
8098: =item *
8099:
8100: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8101:
1.243 albertel 8102: =back
8103:
1.608 albertel 8104: =head2 Usererfile file routines (/uploaded*)
8105:
8106: =over 4
8107:
8108: =item *
8109:
8110: userfileupload(): main rotine for putting a file in a user or course's
8111: filespace, arguments are,
8112:
1.620 albertel 8113: formname - required - this is the name of the element in $env where the
1.608 albertel 8114: filename, and the contents of the file to create/modifed exist
1.620 albertel 8115: the filename is in $env{'form.'.$formname.'.filename'} and the
8116: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 8117: coursedoc - if true, store the file in the course of the active role
8118: of the current user
8119: subdir - required - subdirectory to put the file in under ../userfiles/
8120: if undefined, it will be placed in "unknown"
8121:
8122: (This routine calls clean_filename() to remove any dangerous
8123: characters from the filename, and then calls finuserfileupload() to
8124: complete the transaction)
8125:
8126: returns either the url of the uploaded file (/uploaded/....) if successful
8127: and /adm/notfound.html if unsuccessful
8128:
8129: =item *
8130:
8131: clean_filename(): routine for cleaing a filename up for storage in
8132: userfile space, argument is:
8133:
8134: filename - proposed filename
8135:
8136: returns: the new clean filename
8137:
8138: =item *
8139:
8140: finishuserfileupload(): routine that creaes and sends the file to
8141: userspace, probably shouldn't be called directly
8142:
8143: docuname: username or courseid of destination for the file
8144: docudom: domain of user/course of destination for the file
8145: formname: same as for userfileupload()
8146: fname: filename (inculding subdirectories) for the file
8147:
8148: returns either the url of the uploaded file (/uploaded/....) if successful
8149: and /adm/notfound.html if unsuccessful
8150:
8151: =item *
8152:
8153: renameuserfile(): renames an existing userfile to a new name
8154:
8155: Args:
8156: docuname: username or courseid of destination for the file
8157: docudom: domain of user/course of destination for the file
8158: old: current file name (including any subdirs under userfiles)
8159: new: desired file name (including any subdirs under userfiles)
8160:
8161: =item *
8162:
8163: mkdiruserfile(): creates a directory is a userfiles dir
8164:
8165: Args:
8166: docuname: username or courseid of destination for the file
8167: docudom: domain of user/course of destination for the file
8168: dir: dir to create (including any subdirs under userfiles)
8169:
8170: =item *
8171:
8172: removeuserfile(): removes a file that exists in userfiles
8173:
8174: Args:
8175: docuname: username or courseid of destination for the file
8176: docudom: domain of user/course of destination for the file
8177: fname: filname to delete (including any subdirs under userfiles)
8178:
8179: =item *
8180:
8181: removeuploadedurl(): convience function for removeuserfile()
8182:
8183: Args:
8184: url: a full /uploaded/... url to delete
8185:
1.747 albertel 8186: =item *
8187:
8188: get_portfile_permissions():
8189: Args:
8190: domain: domain of user or course contain the portfolio files
8191: user: name of user or num of course contain the portfolio files
8192: Returns:
8193: hashref of a dump of the proper file_permissions.db
8194:
8195:
8196: =item *
8197:
8198: get_access_controls():
8199:
8200: Args:
8201: current_permissions: the hash ref returned from get_portfile_permissions()
8202: group: (optional) the group you want the files associated with
8203: file: (optional) the file you want access info on
8204:
8205: Returns:
1.749 raeburn 8206: a hash (keys are file names) of hashes containing
8207: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
8208: values are XML containing access control settings (see below)
1.747 albertel 8209:
8210: Internal notes:
8211:
1.749 raeburn 8212: access controls are stored in file_permissions.db as key=value pairs.
8213: key -> path to file/file_name\0uniqueID:scope_end_start
8214: where scope -> public,guest,course,group,domains or users.
8215: end -> UNIX time for end of access (0 -> no end date)
8216: start -> UNIX time for start of access
8217:
8218: value -> XML description of access control
8219: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
8220: <start></start>
8221: <end></end>
8222:
8223: <password></password> for scope type = guest
8224:
8225: <domain></domain> for scope type = course or group
8226: <number></number>
8227: <roles id="">
8228: <role></role>
8229: <access></access>
8230: <section></section>
8231: <group></group>
8232: </roles>
8233:
8234: <dom></dom> for scope type = domains
8235:
8236: <users> for scope type = users
8237: <user>
8238: <uname></uname>
8239: <udom></udom>
8240: </user>
8241: </users>
8242: </scope>
8243:
8244: Access data is also aggregated for each file in an additional key=value pair:
8245: key -> path to file/file_name\0accesscontrol
8246: value -> reference to hash
8247: hash contains key = value pairs
8248: where key = uniqueID:scope_end_start
8249: value = UNIX time record was last updated
8250:
8251: Used to improve speed of look-ups of access controls for each file.
8252:
8253: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
8254:
8255: modify_access_controls():
8256:
8257: Modifies access controls for a portfolio file
8258: Args
8259: 1. file name
8260: 2. reference to hash of required changes,
8261: 3. domain
8262: 4. username
8263: where domain,username are the domain of the portfolio owner
8264: (either a user or a course)
8265:
8266: Returns:
8267: 1. result of additions or updates ('ok' or 'error', with error message).
8268: 2. result of deletions ('ok' or 'error', with error message).
8269: 3. reference to hash of any new or updated access controls.
8270: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
8271: key = integer (inbound ID)
8272: value = uniqueID
1.747 albertel 8273:
1.608 albertel 8274: =back
8275:
1.243 albertel 8276: =head2 HTTP Helper Routines
8277:
8278: =over 4
8279:
1.191 harris41 8280: =item *
8281:
8282: escape() : unpack non-word characters into CGI-compatible hex codes
8283:
8284: =item *
8285:
8286: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
8287:
1.243 albertel 8288: =back
8289:
8290: =head1 PRIVATE SUBROUTINES
8291:
8292: =head2 Underlying communication routines (Shouldn't call)
8293:
8294: =over 4
8295:
8296: =item *
8297:
8298: subreply() : tries to pass a message to lonc, returns con_lost if incapable
8299:
8300: =item *
8301:
8302: reply() : uses subreply to send a message to remote machine, logs all failures
8303:
8304: =item *
8305:
8306: critical() : passes a critical message to another server; if cannot
8307: get through then place message in connection buffer directory and
8308: returns con_delayed, if incapable of saving message, returns
8309: con_failed
8310:
8311: =item *
8312:
8313: reconlonc() : tries to reconnect lonc client processes.
8314:
8315: =back
8316:
8317: =head2 Resource Access Logging
8318:
8319: =over 4
8320:
8321: =item *
8322:
8323: flushcourselogs() : flush (save) buffer logs and access logs
8324:
8325: =item *
8326:
8327: courselog($what) : save message for course in hash
8328:
8329: =item *
8330:
8331: courseacclog($what) : save message for course using &courselog(). Perform
8332: special processing for specific resource types (problems, exams, quizzes, etc).
8333:
1.191 harris41 8334: =item *
8335:
8336: goodbye() : flush course logs and log shutting down; it is called in srm.conf
8337: as a PerlChildExitHandler
1.243 albertel 8338:
8339: =back
8340:
8341: =head2 Other
8342:
8343: =over 4
8344:
8345: =item *
8346:
8347: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 8348:
8349: =back
8350:
8351: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>