Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.870
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.870 ! albertel 4: # $Id: lonnet.pm,v 1.869 2007/04/11 22:52:03 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.486 www 34: use HTTP::Date;
35: # use Date::Parse;
1.11 www 36: use vars
1.847 albertel 37: qw(%perlvar %badServerCache %spareid
1.845 albertel 38: %pr %prp $memcache %packagetab
1.662 raeburn 39: %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount
1.741 raeburn 40: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.685 raeburn 41: $tmpdir $_64bit %env);
1.403 www 42:
1.1 albertel 43: use IO::Socket;
1.31 www 44: use GDBM_File;
1.208 albertel 45: use HTML::LCParser;
1.88 www 46: use Fcntl qw(:flock);
1.870 ! albertel 47: use Storable qw(thaw nfreeze);
1.539 albertel 48: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 49: use Cache::Memcached;
1.676 albertel 50: use Digest::MD5;
1.790 albertel 51: use Math::Random;
1.807 albertel 52: use LONCAPA qw(:DEFAULT :match);
1.740 www 53: use LONCAPA::Configuration;
1.676 albertel 54:
1.195 www 55: my $readit;
1.550 foxr 56: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 57:
1.619 albertel 58: require Exporter;
59:
60: our @ISA = qw (Exporter);
61: our @EXPORT = qw(%env);
62:
1.449 matthew 63: =pod
64:
65: =head1 Package Variables
66:
67: These are largely undocumented, so if you decipher one please note it here.
68:
69: =over 4
70:
71: =item $processmarker
72:
73: Contains the time this process was started and this servers host id.
74:
75: =item $dumpcount
76:
77: Counts the number of times a message log flush has been attempted (regardless
78: of success) by this process. Used as part of the filename when messages are
79: delayed.
80:
81: =back
82:
83: =cut
84:
85:
1.1 albertel 86: # --------------------------------------------------------------------- Logging
1.729 www 87: {
88: my $logid;
89: sub instructor_log {
90: my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
91: $logid++;
92: my $id=time().'00000'.$$.'00000'.$logid;
93: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 94: { $id => {
95: 'exe_uname' => $env{'user.name'},
96: 'exe_udom' => $env{'user.domain'},
97: 'exe_time' => time(),
98: 'exe_ip' => $ENV{'REMOTE_ADDR'},
99: 'delflag' => $delflag,
100: 'logentry' => $storehash,
101: 'uname' => $uname,
102: 'udom' => $udom,
103: }
104: },
1.729 www 105: $env{'course.'.$env{'request.course.id'}.'.domain'},
106: $env{'course.'.$env{'request.course.id'}.'.num'}
107: );
108: }
109: }
1.1 albertel 110:
1.163 harris41 111: sub logtouch {
112: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 113: unless (-e "$execdir/logs/lonnet.log") {
114: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 115: close $fh;
116: }
117: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
118: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
119: }
120:
1.1 albertel 121: sub logthis {
122: my $message=shift;
123: my $execdir=$perlvar{'lonDaemons'};
124: my $now=time;
125: my $local=localtime($now);
1.448 albertel 126: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
127: print $fh "$local ($$): $message\n";
128: close($fh);
129: }
1.1 albertel 130: return 1;
131: }
132:
133: sub logperm {
134: my $message=shift;
135: my $execdir=$perlvar{'lonDaemons'};
136: my $now=time;
137: my $local=localtime($now);
1.448 albertel 138: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
139: print $fh "$now:$message:$local\n";
140: close($fh);
141: }
1.1 albertel 142: return 1;
143: }
144:
1.850 albertel 145: sub create_connection {
1.853 albertel 146: my ($hostname,$lonid) = @_;
1.851 albertel 147: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 148: Type => SOCK_STREAM,
149: Timeout => 10);
150: return 0 if (!$client);
1.854 albertel 151: print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
1.850 albertel 152: my $result = <$client>;
153: chomp($result);
154: return 1 if ($result eq 'done');
155: return 0;
156: }
157:
158:
1.1 albertel 159: # -------------------------------------------------- Non-critical communication
160: sub subreply {
161: my ($cmd,$server)=@_;
1.838 albertel 162: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 163: #
164: # With loncnew process trimming, there's a timing hole between lonc server
165: # process exit and the master server picking up the listen on the AF_UNIX
166: # socket. In that time interval, a lock file will exist:
167:
168: my $lockfile=$peerfile.".lock";
169: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
170: sleep(1);
171: }
172: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 173: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 174: #
1.550 foxr 175: # We'll give the connection a few tries before abandoning it. If
176: # connection is not possible, we'll con_lost back to the client.
177: #
178: my $client;
179: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
180: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
181: Type => SOCK_STREAM,
182: Timeout => 10);
1.869 albertel 183: if ($client) {
1.550 foxr 184: last; # Connected!
1.850 albertel 185: } else {
1.853 albertel 186: &create_connection(&hostname($server),$server);
1.550 foxr 187: }
1.850 albertel 188: sleep(1); # Try again later if failed connection.
1.550 foxr 189: }
190: my $answer;
191: if ($client) {
1.704 albertel 192: print $client "sethost:$server:$cmd\n";
1.550 foxr 193: $answer=<$client>;
194: if (!$answer) { $answer="con_lost"; }
195: chomp($answer);
196: } else {
197: $answer = 'con_lost'; # Failed connection.
198: }
1.1 albertel 199: return $answer;
200: }
201:
202: sub reply {
203: my ($cmd,$server)=@_;
1.838 albertel 204: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 205: my $answer=subreply($cmd,$server);
1.65 www 206: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 207: &logthis("<font color=\"blue\">WARNING:".
1.12 www 208: " $cmd to $server returned $answer</font>");
209: }
1.1 albertel 210: return $answer;
211: }
212:
213: # ----------------------------------------------------------- Send USR1 to lonc
214:
215: sub reconlonc {
1.836 www 216: &logthis("Trying to reconnect lonc");
1.1 albertel 217: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 218: if (open(my $fh,"<$loncfile")) {
1.1 albertel 219: my $loncpid=<$fh>;
220: chomp($loncpid);
221: if (kill 0 => $loncpid) {
222: &logthis("lonc at pid $loncpid responding, sending USR1");
223: kill USR1 => $loncpid;
224: sleep 1;
1.836 www 225: } else {
1.12 www 226: &logthis(
1.672 albertel 227: "<font color=\"blue\">WARNING:".
1.12 www 228: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 229: }
230: } else {
1.836 www 231: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 232: }
233: }
234:
235: # ------------------------------------------------------ Critical communication
1.12 www 236:
1.1 albertel 237: sub critical {
238: my ($cmd,$server)=@_;
1.838 albertel 239: unless (&hostname($server)) {
1.672 albertel 240: &logthis("<font color=\"blue\">WARNING:".
1.89 www 241: " Critical message to unknown server ($server)</font>");
242: return 'no_such_host';
243: }
1.1 albertel 244: my $answer=reply($cmd,$server);
245: if ($answer eq 'con_lost') {
246: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 247: my $answer=reply($cmd,$server);
1.1 albertel 248: if ($answer eq 'con_lost') {
249: my $now=time;
250: my $middlename=$cmd;
1.5 www 251: $middlename=substr($middlename,0,16);
1.1 albertel 252: $middlename=~s/\W//g;
253: my $dfilename=
1.305 www 254: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
255: $dumpcount++;
1.1 albertel 256: {
1.448 albertel 257: my $dfh;
258: if (open($dfh,">$dfilename")) {
259: print $dfh "$cmd\n";
260: close($dfh);
261: }
1.1 albertel 262: }
263: sleep 2;
264: my $wcmd='';
265: {
1.448 albertel 266: my $dfh;
267: if (open($dfh,"<$dfilename")) {
268: $wcmd=<$dfh>;
269: close($dfh);
270: }
1.1 albertel 271: }
272: chomp($wcmd);
1.7 www 273: if ($wcmd eq $cmd) {
1.672 albertel 274: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 275: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 276: &logperm("D:$server:$cmd");
277: return 'con_delayed';
278: } else {
1.672 albertel 279: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 280: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 281: &logperm("F:$server:$cmd");
282: return 'con_failed';
283: }
284: }
285: }
286: return $answer;
1.405 albertel 287: }
288:
1.755 albertel 289: # ------------------------------------------- check if return value is an error
290:
291: sub error {
292: my ($result) = @_;
1.756 albertel 293: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 294: if ($2 == 2) { return undef; }
295: return $1;
296: }
297: return undef;
298: }
299:
1.783 albertel 300: sub convert_and_load_session_env {
301: my ($lonidsdir,$handle)=@_;
302: my @profile;
303: {
304: open(my $idf,"$lonidsdir/$handle.id");
305: flock($idf,LOCK_SH);
306: @profile=<$idf>;
307: close($idf);
308: }
309: my %temp_env;
310: foreach my $line (@profile) {
1.786 albertel 311: if ($line !~ m/=/) {
312: return 0;
313: }
1.783 albertel 314: chomp($line);
315: my ($envname,$envvalue)=split(/=/,$line,2);
316: $temp_env{&unescape($envname)} = &unescape($envvalue);
317: }
318: unlink("$lonidsdir/$handle.id");
319: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
320: 0640)) {
321: %disk_env = %temp_env;
322: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
323: untie(%disk_env);
324: }
1.786 albertel 325: return 1;
1.783 albertel 326: }
327:
1.374 www 328: # ------------------------------------------- Transfer profile into environment
1.780 albertel 329: my $env_loaded;
330: sub transfer_profile_to_env {
1.788 albertel 331: my ($lonidsdir,$handle,$force_transfer) = @_;
332: if (!$force_transfer && $env_loaded) { return; }
1.374 www 333:
1.720 albertel 334: if (!defined($lonidsdir)) {
335: $lonidsdir = $perlvar{'lonIDsDir'};
336: }
337: if (!defined($handle)) {
338: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
339: }
340:
1.786 albertel 341: my $convert;
342: {
343: open(my $idf,"$lonidsdir/$handle.id");
344: flock($idf,LOCK_SH);
345: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
346: &GDBM_READER(),0640)) {
347: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
348: untie(%disk_env);
349: } else {
350: $convert = 1;
351: }
352: }
353: if ($convert) {
354: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
355: &logthis("Failed to load session, or convert session.");
356: }
1.374 www 357: }
1.783 albertel 358:
1.786 albertel 359: my %remove;
1.783 albertel 360: while ( my $envname = each(%env) ) {
1.433 matthew 361: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
362: if ($time < time-300) {
1.783 albertel 363: $remove{$key}++;
1.433 matthew 364: }
365: }
366: }
1.783 albertel 367:
1.619 albertel 368: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 369: $env_loaded=1;
1.783 albertel 370: foreach my $expired_key (keys(%remove)) {
1.433 matthew 371: &delenv($expired_key);
1.374 www 372: }
1.1 albertel 373: }
374:
1.830 albertel 375: sub timed_flock {
376: my ($file,$lock_type) = @_;
377: my $failed=0;
378: eval {
379: local $SIG{__DIE__}='DEFAULT';
380: local $SIG{ALRM}=sub {
381: $failed=1;
382: die("failed lock");
383: };
384: alarm(13);
385: flock($file,$lock_type);
386: alarm(0);
387: };
388: if ($failed) {
389: return undef;
390: } else {
391: return 1;
392: }
393: }
394:
1.5 www 395: # ---------------------------------------------------------- Append Environment
396:
397: sub appenv {
1.6 www 398: my %newenv=@_;
1.692 albertel 399: foreach my $key (keys(%newenv)) {
400: if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672 albertel 401: &logthis("<font color=\"blue\">WARNING: ".
1.692 albertel 402: "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151 www 403: .'</font>');
1.692 albertel 404: delete($newenv{$key});
1.35 www 405: } else {
1.692 albertel 406: $env{$key}=$newenv{$key};
1.35 www 407: }
1.191 harris41 408: }
1.830 albertel 409: open(my $env_file,$env{'user.environment'});
410: if (&timed_flock($env_file,LOCK_EX)
411: &&
412: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
413: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 414: while (my ($key,$value) = each(%newenv)) {
415: $disk_env{$key} = $value;
1.448 albertel 416: }
1.783 albertel 417: untie(%disk_env);
1.56 www 418: }
419: return 'ok';
420: }
421: # ----------------------------------------------------- Delete from Environment
422:
423: sub delenv {
424: my $delthis=shift;
425: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672 albertel 426: &logthis("<font color=\"blue\">WARNING: ".
1.56 www 427: "Attempt to delete from environment ".$delthis);
428: return 'error';
429: }
1.830 albertel 430: open(my $env_file,$env{'user.environment'});
431: if (&timed_flock($env_file,LOCK_EX)
432: &&
433: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
434: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 435: foreach my $key (keys(%disk_env)) {
436: if ($key=~/^$delthis/) {
1.619 albertel 437: delete($env{$key});
1.783 albertel 438: delete($disk_env{$key});
1.473 matthew 439: }
1.448 albertel 440: }
1.783 albertel 441: untie(%disk_env);
1.5 www 442: }
443: return 'ok';
1.369 albertel 444: }
445:
1.790 albertel 446: sub get_env_multiple {
447: my ($name) = @_;
448: my @values;
449: if (defined($env{$name})) {
450: # exists is it an array
451: if (ref($env{$name})) {
452: @values=@{ $env{$name} };
453: } else {
454: $values[0]=$env{$name};
455: }
456: }
457: return(@values);
458: }
459:
1.369 albertel 460: # ------------------------------------------ Find out current server userload
461: # there is a copy in lond
462: sub userload {
463: my $numusers=0;
464: {
465: opendir(LONIDS,$perlvar{'lonIDsDir'});
466: my $filename;
467: my $curtime=time;
468: while ($filename=readdir(LONIDS)) {
469: if ($filename eq '.' || $filename eq '..') {next;}
1.404 albertel 470: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 471: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 472: }
473: closedir(LONIDS);
474: }
475: my $userloadpercent=0;
476: my $maxuserload=$perlvar{'lonUserLoadLim'};
477: if ($maxuserload) {
1.371 albertel 478: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 479: }
1.372 albertel 480: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 481: return $userloadpercent;
1.283 www 482: }
483:
484: # ------------------------------------------ Fight off request when overloaded
485:
486: sub overloaderror {
487: my ($r,$checkserver)=@_;
488: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
489: my $loadavg;
490: if ($checkserver eq $perlvar{'lonHostID'}) {
1.448 albertel 491: open(my $loadfile,'/proc/loadavg');
1.283 www 492: $loadavg=<$loadfile>;
493: $loadavg =~ s/\s.*//g;
1.285 matthew 494: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448 albertel 495: close($loadfile);
1.283 www 496: } else {
497: $loadavg=&reply('load',$checkserver);
498: }
1.285 matthew 499: my $overload=$loadavg-100;
1.283 www 500: if ($overload>0) {
1.285 matthew 501: $r->err_headers_out->{'Retry-After'}=$overload;
1.283 www 502: $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554 www 503: return 413;
1.283 www 504: }
505: return '';
1.5 www 506: }
1.1 albertel 507:
508: # ------------------------------ Find server with least workload from spare.tab
1.11 www 509:
1.1 albertel 510: sub spareserver {
1.670 albertel 511: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784 albertel 512: my $spare_server;
1.370 albertel 513: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 514: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
515: : $userloadpercent;
516:
517: foreach my $try_server (@{ $spareid{'primary'} }) {
518: ($spare_server, $lowest_load) =
519: &compare_server_load($try_server, $spare_server, $lowest_load);
520: }
521:
522: my $found_server = ($spare_server ne '' && $lowest_load < 100);
523:
524: if (!$found_server) {
525: foreach my $try_server (@{ $spareid{'default'} }) {
526: ($spare_server, $lowest_load) =
527: &compare_server_load($try_server, $spare_server, $lowest_load);
528: }
529: }
530:
531: if (!$want_server_name) {
1.838 albertel 532: $spare_server="http://".&hostname($spare_server);
1.784 albertel 533: }
534: return $spare_server;
535: }
536:
537: sub compare_server_load {
538: my ($try_server, $spare_server, $lowest_load) = @_;
539:
540: my $loadans = &reply('load', $try_server);
541: my $userloadans = &reply('userload',$try_server);
542:
543: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
544: next; #didn't get a number from the server
545: }
546:
547: my $load;
548: if ($loadans =~ /\d/) {
549: if ($userloadans =~ /\d/) {
550: #both are numbers, pick the bigger one
551: $load = ($loadans > $userloadans) ? $loadans
552: : $userloadans;
1.411 albertel 553: } else {
1.784 albertel 554: $load = $loadans;
1.411 albertel 555: }
1.784 albertel 556: } else {
557: $load = $userloadans;
558: }
559:
560: if (($load =~ /\d/) && ($load < $lowest_load)) {
561: $spare_server = $try_server;
562: $lowest_load = $load;
1.370 albertel 563: }
1.784 albertel 564: return ($spare_server,$lowest_load);
1.202 matthew 565: }
566: # --------------------------------------------- Try to change a user's password
567:
568: sub changepass {
1.799 raeburn 569: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 570: $currentpass = &escape($currentpass);
571: $newpass = &escape($newpass);
1.799 raeburn 572: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202 matthew 573: $server);
574: if (! $answer) {
575: &logthis("No reply on password change request to $server ".
576: "by $uname in domain $udom.");
577: } elsif ($answer =~ "^ok") {
578: &logthis("$uname in $udom successfully changed their password ".
579: "on $server.");
580: } elsif ($answer =~ "^pwchange_failure") {
581: &logthis("$uname in $udom was unable to change their password ".
582: "on $server. The action was blocked by either lcpasswd ".
583: "or pwchange");
584: } elsif ($answer =~ "^non_authorized") {
585: &logthis("$uname in $udom did not get their password correct when ".
586: "attempting to change it on $server.");
587: } elsif ($answer =~ "^auth_mode_error") {
588: &logthis("$uname in $udom attempted to change their password despite ".
589: "not being locally or internally authenticated on $server.");
590: } elsif ($answer =~ "^unknown_user") {
591: &logthis("$uname in $udom attempted to change their password ".
592: "on $server but were unable to because $server is not ".
593: "their home server.");
594: } elsif ($answer =~ "^refused") {
595: &logthis("$server refused to change $uname in $udom password because ".
596: "it was sent an unencrypted request to change the password.");
597: }
598: return $answer;
1.1 albertel 599: }
600:
1.169 harris41 601: # ----------------------- Try to determine user's current authentication scheme
602:
603: sub queryauthenticate {
604: my ($uname,$udom)=@_;
1.456 albertel 605: my $uhome=&homeserver($uname,$udom);
606: if (!$uhome) {
607: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
608: return 'no_host';
609: }
610: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
611: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
612: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 613: }
1.456 albertel 614: return $answer;
1.169 harris41 615: }
616:
1.1 albertel 617: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 618:
1.1 albertel 619: sub authenticate {
620: my ($uname,$upass,$udom)=@_;
1.807 albertel 621: $upass=&escape($upass);
622: $uname= &LONCAPA::clean_username($uname);
1.836 www 623: my $uhome=&homeserver($uname,$udom,1);
624: if ((!$uhome) || ($uhome eq 'no_host')) {
625: # Maybe the machine was offline and only re-appeared again recently?
626: &reconlonc();
627: # One more
628: my $uhome=&homeserver($uname,$udom,1);
629: if ((!$uhome) || ($uhome eq 'no_host')) {
630: &logthis("User $uname at $udom is unknown in authenticate");
631: }
1.471 albertel 632: return 'no_host';
1.1 albertel 633: }
1.471 albertel 634: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
635: if ($answer eq 'authorized') {
636: &logthis("User $uname at $udom authorized by $uhome");
637: return $uhome;
638: }
639: if ($answer eq 'non_authorized') {
640: &logthis("User $uname at $udom rejected by $uhome");
641: return 'no_host';
1.9 www 642: }
1.471 albertel 643: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 644: return 'no_host';
645: }
646:
647: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 648:
1.599 albertel 649: my %homecache;
1.1 albertel 650: sub homeserver {
1.230 stredwic 651: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 652: my $index="$uname:$udom";
1.426 albertel 653:
1.599 albertel 654: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 655:
656: my %servers = &get_servers($udom,'library');
657: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 658: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 659: exists($badServerCache{$tryserver}));
1.841 albertel 660:
661: my $answer=reply("home:$udom:$uname",$tryserver);
662: if ($answer eq 'found') {
663: delete($badServerCache{$tryserver});
664: return $homecache{$index}=$tryserver;
665: } elsif ($answer eq 'no_host') {
666: $badServerCache{$tryserver}=1;
667: }
1.1 albertel 668: }
669: return 'no_host';
1.70 www 670: }
671:
672: # ------------------------------------- Find the usernames behind a list of IDs
673:
674: sub idget {
675: my ($udom,@ids)=@_;
676: my %returnhash=();
677:
1.841 albertel 678: my %servers = &get_servers($udom,'library');
679: foreach my $tryserver (keys(%servers)) {
680: my $idlist=join('&',@ids);
681: $idlist=~tr/A-Z/a-z/;
682: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
683: my @answer=();
684: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
685: @answer=split(/\&/,$reply);
686: } ;
687: my $i;
688: for ($i=0;$i<=$#ids;$i++) {
689: if ($answer[$i]) {
690: $returnhash{$ids[$i]}=$answer[$i];
691: }
692: }
693: }
1.70 www 694: return %returnhash;
695: }
696:
697: # ------------------------------------- Find the IDs behind a list of usernames
698:
699: sub idrget {
700: my ($udom,@unames)=@_;
701: my %returnhash=();
1.800 albertel 702: foreach my $uname (@unames) {
703: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 704: }
1.70 www 705: return %returnhash;
706: }
707:
708: # ------------------------------- Store away a list of names and associated IDs
709:
710: sub idput {
711: my ($udom,%ids)=@_;
712: my %servers=();
1.800 albertel 713: foreach my $uname (keys(%ids)) {
714: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
715: my $uhom=&homeserver($uname,$udom);
1.70 www 716: if ($uhom ne 'no_host') {
1.800 albertel 717: my $id=&escape($ids{$uname});
1.70 www 718: $id=~tr/A-Z/a-z/;
1.800 albertel 719: my $esc_unam=&escape($uname);
1.70 www 720: if ($servers{$uhom}) {
1.800 albertel 721: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 722: } else {
1.800 albertel 723: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 724: }
725: }
1.191 harris41 726: }
1.800 albertel 727: foreach my $server (keys(%servers)) {
728: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 729: }
1.344 www 730: }
731:
1.806 raeburn 732: # ------------------------------------------- get items from domain db files
733:
734: sub get_dom {
1.860 raeburn 735: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 736: my $items='';
737: foreach my $item (@$storearr) {
738: $items.=&escape($item).'&';
739: }
740: $items=~s/\&$//;
1.860 raeburn 741: if (!$udom) {
742: $udom=$env{'user.domain'};
743: if (defined(&domain($udom,'primary'))) {
744: $uhome=&domain($udom,'primary');
745: } else {
746: $uhome eq '';
747: }
748: } else {
749: if (!$uhome) {
750: if (defined(&domain($udom,'primary'))) {
751: $uhome=&domain($udom,'primary');
752: }
753: }
754: }
755: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 756: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 757: my %returnhash;
758: if ($rep =~ /^error: 2 /) {
759: return %returnhash;
760: }
1.806 raeburn 761: my @pairs=split(/\&/,$rep);
762: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
763: return @pairs;
764: }
765: my %returnhash=();
766: my $i=0;
767: foreach my $item (@$storearr) {
768: $returnhash{$item}=&thaw_unescape($pairs[$i]);
769: $i++;
770: }
771: return %returnhash;
772: } else {
1.860 raeburn 773: &logthis("get_dom failed - no homeserver and/or domain");
1.806 raeburn 774: }
775: }
776:
777: # -------------------------------------------- put items in domain db files
778:
779: sub put_dom {
1.860 raeburn 780: my ($namespace,$storehash,$udom,$uhome)=@_;
781: if (!$udom) {
782: $udom=$env{'user.domain'};
783: if (defined(&domain($udom,'primary'))) {
784: $uhome=&domain($udom,'primary');
785: } else {
786: $uhome eq '';
787: }
788: } else {
789: if (!$uhome) {
790: if (defined(&domain($udom,'primary'))) {
791: $uhome=&domain($udom,'primary');
792: }
793: }
794: }
795: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 796: my $items='';
797: foreach my $item (keys(%$storehash)) {
798: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
799: }
800: $items=~s/\&$//;
801: return &reply("putdom:$udom:$namespace:$items",$uhome);
802: } else {
1.860 raeburn 803: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 804: }
805: }
806:
1.837 raeburn 807: sub retrieve_inst_usertypes {
808: my ($udom) = @_;
809: my (%returnhash,@order);
1.846 albertel 810: if (defined(&domain($udom,'primary'))) {
811: my $uhome=&domain($udom,'primary');
1.837 raeburn 812: my $rep=&reply("inst_usertypes:$udom",$uhome);
813: my ($hashitems,$orderitems) = split(/:/,$rep);
814: my @pairs=split(/\&/,$hashitems);
815: foreach my $item (@pairs) {
816: my ($key,$value)=split(/=/,$item,2);
817: $key = &unescape($key);
818: next if ($key =~ /^error: 2 /);
819: $returnhash{$key}=&thaw_unescape($value);
820: }
821: my @esc_order = split(/\&/,$orderitems);
822: foreach my $item (@esc_order) {
823: push(@order,&unescape($item));
824: }
825: } else {
826: &logthis("get_dom failed - no primary domain server for $udom");
827: }
828: return (\%returnhash,\@order);
829: }
830:
1.868 raeburn 831: sub is_domainimage {
832: my ($url) = @_;
833: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
834: if (&domain($1) ne '') {
835: return '1';
836: }
837: }
838: return;
839: }
840:
1.344 www 841: # --------------------------------------------------- Assign a key to a student
842:
843: sub assign_access_key {
1.364 www 844: #
845: # a valid key looks like uname:udom#comments
846: # comments are being appended
847: #
1.498 www 848: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
849: $kdom=
1.620 albertel 850: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 851: $knum=
1.620 albertel 852: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 853: $cdom=
1.620 albertel 854: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 855: $cnum=
1.620 albertel 856: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
857: $udom=$env{'user.name'} unless (defined($udom));
858: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 859: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 860: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 861: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 862: # assigned to this person
863: # - this should not happen,
1.345 www 864: # unless something went wrong
865: # the first time around
866: # ready to assign
1.364 www 867: $logentry=$1.'; '.$logentry;
1.496 www 868: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 869: $kdom,$knum) eq 'ok') {
1.345 www 870: # key now belongs to user
1.346 www 871: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 872: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
873: &appenv('environment.'.$envkey => $ckey);
874: return 'ok';
875: } else {
876: return
877: 'error: Count not permanently assign key, will need to be re-entered later.';
878: }
879: } else {
880: return 'error: Could not assign key, try again later.';
881: }
1.364 www 882: } elsif (!$existing{$ckey}) {
1.345 www 883: # the key does not exist
884: return 'error: The key does not exist';
885: } else {
886: # the key is somebody else's
887: return 'error: The key is already in use';
888: }
1.344 www 889: }
890:
1.364 www 891: # ------------------------------------------ put an additional comment on a key
892:
893: sub comment_access_key {
894: #
895: # a valid key looks like uname:udom#comments
896: # comments are being appended
897: #
898: my ($ckey,$cdom,$cnum,$logentry)=@_;
899: $cdom=
1.620 albertel 900: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 901: $cnum=
1.620 albertel 902: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 903: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
904: if ($existing{$ckey}) {
905: $existing{$ckey}.='; '.$logentry;
906: # ready to assign
1.367 www 907: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 908: $cdom,$cnum) eq 'ok') {
909: return 'ok';
910: } else {
911: return 'error: Count not store comment.';
912: }
913: } else {
914: # the key does not exist
915: return 'error: The key does not exist';
916: }
917: }
918:
1.344 www 919: # ------------------------------------------------------ Generate a set of keys
920:
921: sub generate_access_keys {
1.364 www 922: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 923: $cdom=
1.620 albertel 924: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 925: $cnum=
1.620 albertel 926: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 927: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 928: unless (($cdom) && ($cnum)) { return 0; }
929: if ($number>10000) { return 0; }
930: sleep(2); # make sure don't get same seed twice
931: srand(time()^($$+($$<<15))); # from "Programming Perl"
932: my $total=0;
933: for (my $i=1;$i<=$number;$i++) {
934: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
935: sprintf("%lx",int(100000*rand)).'-'.
936: sprintf("%lx",int(100000*rand));
937: $newkey=~s/1/g/g; # folks mix up 1 and l
938: $newkey=~s/0/h/g; # and also 0 and O
939: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
940: if ($existing{$newkey}) {
941: $i--;
942: } else {
1.364 www 943: if (&put('accesskeys',
944: { $newkey => '# generated '.localtime().
1.620 albertel 945: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 946: '; '.$logentry },
947: $cdom,$cnum) eq 'ok') {
1.344 www 948: $total++;
949: }
950: }
951: }
1.620 albertel 952: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 953: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
954: return $total;
955: }
956:
957: # ------------------------------------------------------- Validate an accesskey
958:
959: sub validate_access_key {
960: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
961: $cdom=
1.620 albertel 962: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 963: $cnum=
1.620 albertel 964: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
965: $udom=$env{'user.domain'} unless (defined($udom));
966: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 967: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 968: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 969: }
970:
971: # ------------------------------------- Find the section of student in a course
1.652 albertel 972: sub devalidate_getsection_cache {
973: my ($udom,$unam,$courseid)=@_;
974: my $hashid="$udom:$unam:$courseid";
975: &devalidate_cache_new('getsection',$hashid);
976: }
1.298 matthew 977:
1.815 albertel 978: sub courseid_to_courseurl {
979: my ($courseid) = @_;
980: #already url style courseid
981: return $courseid if ($courseid =~ m{^/});
982:
983: if (exists($env{'course.'.$courseid.'.num'})) {
984: my $cnum = $env{'course.'.$courseid.'.num'};
985: my $cdom = $env{'course.'.$courseid.'.domain'};
986: return "/$cdom/$cnum";
987: }
988:
989: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
990: if (exists($courseinfo{'num'})) {
991: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
992: }
993:
994: return undef;
995: }
996:
1.298 matthew 997: sub getsection {
998: my ($udom,$unam,$courseid)=@_;
1.599 albertel 999: my $cachetime=1800;
1.551 albertel 1000:
1001: my $hashid="$udom:$unam:$courseid";
1.599 albertel 1002: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 1003: if (defined($cached)) { return $result; }
1004:
1.298 matthew 1005: my %Pending;
1006: my %Expired;
1007: #
1008: # Each role can either have not started yet (pending), be active,
1009: # or have expired.
1010: #
1011: # If there is an active role, we are done.
1012: #
1013: # If there is more than one role which has not started yet,
1014: # choose the one which will start sooner
1015: # If there is one role which has not started yet, return it.
1016: #
1017: # If there is more than one expired role, choose the one which ended last.
1018: # If there is a role which has expired, return it.
1019: #
1.815 albertel 1020: $courseid = &courseid_to_courseurl($courseid);
1.817 raeburn 1021: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1022: foreach my $key (keys(%roleshash)) {
1.479 albertel 1023: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 1024: my $section=$1;
1025: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 1026: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 1027: my $now=time;
1.548 albertel 1028: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 1029: $Expired{$end}=$section;
1030: next;
1031: }
1.548 albertel 1032: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 1033: $Pending{$start}=$section;
1034: next;
1035: }
1.599 albertel 1036: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 1037: }
1038: #
1039: # Presumedly there will be few matching roles from the above
1040: # loop and the sorting time will be negligible.
1041: if (scalar(keys(%Pending))) {
1042: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 1043: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 1044: }
1045: if (scalar(keys(%Expired))) {
1046: my @sorted = sort {$a <=> $b} keys(%Expired);
1047: my $time = pop(@sorted);
1.599 albertel 1048: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 1049: }
1.599 albertel 1050: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 1051: }
1.70 www 1052:
1.599 albertel 1053: sub save_cache {
1054: &purge_remembered();
1.722 albertel 1055: #&Apache::loncommon::validate_page();
1.620 albertel 1056: undef(%env);
1.780 albertel 1057: undef($env_loaded);
1.599 albertel 1058: }
1.452 albertel 1059:
1.599 albertel 1060: my $to_remember=-1;
1061: my %remembered;
1062: my %accessed;
1063: my $kicks=0;
1064: my $hits=0;
1.849 albertel 1065: sub make_key {
1066: my ($name,$id) = @_;
1067: if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
1068: return &escape($name.':'.$id);
1069: }
1070:
1.599 albertel 1071: sub devalidate_cache_new {
1072: my ($name,$id,$debug) = @_;
1073: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 1074: $id=&make_key($name,$id);
1.599 albertel 1075: $memcache->delete($id);
1076: delete($remembered{$id});
1077: delete($accessed{$id});
1078: }
1079:
1080: sub is_cached_new {
1081: my ($name,$id,$debug) = @_;
1.849 albertel 1082: $id=&make_key($name,$id);
1.599 albertel 1083: if (exists($remembered{$id})) {
1084: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1085: $accessed{$id}=[&gettimeofday()];
1086: $hits++;
1087: return ($remembered{$id},1);
1088: }
1089: my $value = $memcache->get($id);
1090: if (!(defined($value))) {
1091: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 1092: return (undef,undef);
1.416 albertel 1093: }
1.599 albertel 1094: if ($value eq '__undef__') {
1095: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1096: $value=undef;
1097: }
1098: &make_room($id,$value,$debug);
1099: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1100: return ($value,1);
1101: }
1102:
1103: sub do_cache_new {
1104: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 1105: $id=&make_key($name,$id);
1.599 albertel 1106: my $setvalue=$value;
1107: if (!defined($setvalue)) {
1108: $setvalue='__undef__';
1109: }
1.623 albertel 1110: if (!defined($time) ) {
1111: $time=600;
1112: }
1.599 albertel 1113: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600 albertel 1114: $memcache->set($id,$setvalue,$time);
1115: # need to make a copy of $value
1116: #&make_room($id,$value,$debug);
1.599 albertel 1117: return $value;
1118: }
1119:
1120: sub make_room {
1121: my ($id,$value,$debug)=@_;
1122: $remembered{$id}=$value;
1123: if ($to_remember<0) { return; }
1124: $accessed{$id}=[&gettimeofday()];
1125: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1126: my $to_kick;
1127: my $max_time=0;
1128: foreach my $other (keys(%accessed)) {
1129: if (&tv_interval($accessed{$other}) > $max_time) {
1130: $to_kick=$other;
1131: $max_time=&tv_interval($accessed{$other});
1132: }
1133: }
1134: delete($remembered{$to_kick});
1135: delete($accessed{$to_kick});
1136: $kicks++;
1137: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 1138: return;
1139: }
1140:
1.599 albertel 1141: sub purge_remembered {
1.604 albertel 1142: #&logthis("Tossing ".scalar(keys(%remembered)));
1143: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 1144: undef(%remembered);
1145: undef(%accessed);
1.428 albertel 1146: }
1.70 www 1147: # ------------------------------------- Read an entry from a user's environment
1148:
1149: sub userenvironment {
1150: my ($udom,$unam,@what)=@_;
1151: my %returnhash=();
1152: my @answer=split(/\&/,
1153: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
1154: &homeserver($unam,$udom)));
1155: my $i;
1156: for ($i=0;$i<=$#what;$i++) {
1157: $returnhash{$what[$i]}=&unescape($answer[$i]);
1158: }
1159: return %returnhash;
1.1 albertel 1160: }
1161:
1.617 albertel 1162: # ---------------------------------------------------------- Get a studentphoto
1163: sub studentphoto {
1164: my ($udom,$unam,$ext) = @_;
1165: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 1166: if (defined($env{'request.course.id'})) {
1.708 raeburn 1167: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 1168: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1169: return(&retrievestudentphoto($udom,$unam,$ext));
1170: } else {
1171: my ($result,$perm_reqd)=
1.707 albertel 1172: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1173: if ($result eq 'ok') {
1174: if (!($perm_reqd eq 'yes')) {
1175: return(&retrievestudentphoto($udom,$unam,$ext));
1176: }
1177: }
1178: }
1179: }
1180: } else {
1181: my ($result,$perm_reqd) =
1.707 albertel 1182: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 1183: if ($result eq 'ok') {
1184: if (!($perm_reqd eq 'yes')) {
1185: return(&retrievestudentphoto($udom,$unam,$ext));
1186: }
1187: }
1188: }
1189: return '/adm/lonKaputt/lonlogo_broken.gif';
1190: }
1191:
1192: sub retrievestudentphoto {
1193: my ($udom,$unam,$ext,$type) = @_;
1194: my $home=&Apache::lonnet::homeserver($unam,$udom);
1195: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1196: if ($ret eq 'ok') {
1197: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1198: if ($type eq 'thumbnail') {
1199: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1200: }
1201: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1202: return $tokenurl;
1203: } else {
1204: if ($type eq 'thumbnail') {
1205: return '/adm/lonKaputt/genericstudent_tn.gif';
1206: } else {
1207: return '/adm/lonKaputt/lonlogo_broken.gif';
1208: }
1.617 albertel 1209: }
1210: }
1211:
1.263 www 1212: # -------------------------------------------------------------------- New chat
1213:
1214: sub chatsend {
1.724 raeburn 1215: my ($newentry,$anon,$group)=@_;
1.620 albertel 1216: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1217: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1218: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 1219: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 1220: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 1221: &escape($newentry)).':'.$group,$chome);
1.292 www 1222: }
1223:
1224: # ------------------------------------------ Find current version of a resource
1225:
1226: sub getversion {
1227: my $fname=&clutter(shift);
1228: unless ($fname=~/^\/res\//) { return -1; }
1229: return ¤tversion(&filelocation('',$fname));
1230: }
1231:
1232: sub currentversion {
1233: my $fname=shift;
1.599 albertel 1234: my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440 www 1235: if (defined($cached)) { return $result; }
1.292 www 1236: my $author=$fname;
1237: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1238: my ($udom,$uname)=split(/\//,$author);
1239: my $home=homeserver($uname,$udom);
1240: if ($home eq 'no_host') {
1241: return -1;
1242: }
1243: my $answer=reply("currentversion:$fname",$home);
1244: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1245: return -1;
1246: }
1.599 albertel 1247: return &do_cache_new('resversion',$fname,$answer,600);
1.263 www 1248: }
1249:
1.1 albertel 1250: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 1251:
1.1 albertel 1252: sub subscribe {
1253: my $fname=shift;
1.761 raeburn 1254: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 1255: $fname=~s/[\n\r]//g;
1.1 albertel 1256: my $author=$fname;
1257: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1258: my ($udom,$uname)=split(/\//,$author);
1259: my $home=homeserver($uname,$udom);
1.335 albertel 1260: if ($home eq 'no_host') {
1261: return 'not_found';
1.1 albertel 1262: }
1263: my $answer=reply("sub:$fname",$home);
1.64 www 1264: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1265: $answer.=' by '.$home;
1266: }
1.1 albertel 1267: return $answer;
1268: }
1269:
1.8 www 1270: # -------------------------------------------------------------- Replicate file
1271:
1272: sub repcopy {
1273: my $filename=shift;
1.23 www 1274: $filename=~s/\/+/\//g;
1.607 raeburn 1275: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1276: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 1277: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 1278: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 1279: return &repcopy_userfile($filename);
1280: }
1.532 albertel 1281: $filename=~s/[\n\r]//g;
1.8 www 1282: my $transname="$filename.in.transfer";
1.828 www 1283: # FIXME: this should flock
1.607 raeburn 1284: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 1285: my $remoteurl=subscribe($filename);
1.64 www 1286: if ($remoteurl =~ /^con_lost by/) {
1287: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1288: return 'unavailable';
1.8 www 1289: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 1290: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 1291: return 'not_found';
1.64 www 1292: } elsif ($remoteurl =~ /^rejected by/) {
1293: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 1294: return 'forbidden';
1.20 www 1295: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 1296: return 'ok';
1.8 www 1297: } else {
1.290 www 1298: my $author=$filename;
1299: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1300: my ($udom,$uname)=split(/\//,$author);
1301: my $home=homeserver($uname,$udom);
1302: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 1303: my @parts=split(/\//,$filename);
1304: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1305: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1306: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 1307: return 'bad_request';
1.8 www 1308: }
1309: my $count;
1310: for ($count=5;$count<$#parts;$count++) {
1311: $path.="/$parts[$count]";
1312: if ((-e $path)!=1) {
1313: mkdir($path,0777);
1314: }
1315: }
1316: my $ua=new LWP::UserAgent;
1317: my $request=new HTTP::Request('GET',"$remoteurl");
1318: my $response=$ua->request($request,$transname);
1319: if ($response->is_error()) {
1320: unlink($transname);
1321: my $message=$response->status_line;
1.672 albertel 1322: &logthis("<font color=\"blue\">WARNING:"
1.12 www 1323: ." LWP get: $message: $filename</font>");
1.607 raeburn 1324: return 'unavailable';
1.8 www 1325: } else {
1.16 www 1326: if ($remoteurl!~/\.meta$/) {
1327: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1328: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1329: if ($mresponse->is_error()) {
1330: unlink($filename.'.meta');
1331: &logthis(
1.672 albertel 1332: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 1333: }
1334: }
1.8 www 1335: rename($transname,$filename);
1.607 raeburn 1336: return 'ok';
1.8 www 1337: }
1.290 www 1338: }
1.8 www 1339: }
1.330 www 1340: }
1341:
1342: # ------------------------------------------------ Get server side include body
1343: sub ssi_body {
1.381 albertel 1344: my ($filelink,%form)=@_;
1.606 matthew 1345: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1346: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1347: }
1.330 www 1348: my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381 albertel 1349: &ssi($filelink,%form));
1.778 albertel 1350: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 1351: $output=~s/^.*?\<body[^\>]*\>//si;
1352: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330 www 1353: return $output;
1.8 www 1354: }
1355:
1.15 www 1356: # --------------------------------------------------------- Server Side Include
1357:
1.782 albertel 1358: sub absolute_url {
1359: my ($host_name) = @_;
1360: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1361: if ($host_name eq '') {
1362: $host_name = $ENV{'SERVER_NAME'};
1363: }
1364: return $protocol.$host_name;
1365: }
1366:
1.15 www 1367: sub ssi {
1368:
1.23 www 1369: my ($fn,%form)=@_;
1.15 www 1370:
1371: my $ua=new LWP::UserAgent;
1.23 www 1372:
1373: my $request;
1.711 albertel 1374:
1375: $form{'no_update_last_known'}=1;
1376:
1.23 www 1377: if (%form) {
1.782 albertel 1378: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201 albertel 1379: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23 www 1380: } else {
1.782 albertel 1381: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 1382: }
1383:
1.15 www 1384: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1385: my $response=$ua->request($request);
1386:
1.324 www 1387: return $response->content;
1388: }
1389:
1390: sub externalssi {
1391: my ($url)=@_;
1392: my $ua=new LWP::UserAgent;
1393: my $request=new HTTP::Request('GET',$url);
1394: my $response=$ua->request($request);
1.15 www 1395: return $response->content;
1396: }
1.254 www 1397:
1.492 albertel 1398: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1399:
1400: sub allowuploaded {
1401: my ($srcurl,$url)=@_;
1402: $url=&clutter(&declutter($url));
1403: my $dir=$url;
1404: $dir=~s/\/[^\/]+$//;
1405: my %httpref=();
1406: my $httpurl=&hreflocation('',$url);
1407: $httpref{'httpref.'.$httpurl}=$srcurl;
1408: &Apache::lonnet::appenv(%httpref);
1.254 www 1409: }
1.477 raeburn 1410:
1.478 albertel 1411: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 1412: # input: action, courseID, current domain, intended
1.637 raeburn 1413: # path to file, source of file, instruction to parse file for objects,
1414: # ref to hash for embedded objects,
1415: # ref to hash for codebase of java objects.
1416: #
1.485 raeburn 1417: # output: url to file (if action was uploaddoc),
1418: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 1419: #
1.478 albertel 1420: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1421: # course.
1.477 raeburn 1422: #
1.478 albertel 1423: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1424: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1425: # course's home server.
1.477 raeburn 1426: #
1.478 albertel 1427: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1428: # be copied from $source (current location) to
1429: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1430: # and will then be copied to
1431: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1432: # course's home server.
1.485 raeburn 1433: #
1.481 raeburn 1434: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 1435: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 1436: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1437: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1438: # in course's home server.
1.637 raeburn 1439: #
1.477 raeburn 1440:
1441: sub process_coursefile {
1.638 albertel 1442: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477 raeburn 1443: my $fetchresult;
1.638 albertel 1444: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 1445: if ($action eq 'propagate') {
1.638 albertel 1446: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1447: $home);
1.481 raeburn 1448: } else {
1.477 raeburn 1449: my $fpath = '';
1450: my $fname = $file;
1.478 albertel 1451: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 1452: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 1453: my $filepath = &build_filepath($fpath);
1.481 raeburn 1454: if ($action eq 'copy') {
1455: if ($source eq '') {
1456: $fetchresult = 'no source file';
1457: return $fetchresult;
1458: } else {
1459: my $destination = $filepath.'/'.$fname;
1460: rename($source,$destination);
1461: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1462: $home);
1.481 raeburn 1463: }
1464: } elsif ($action eq 'uploaddoc') {
1465: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 1466: print $fh $env{'form.'.$source};
1.481 raeburn 1467: close($fh);
1.637 raeburn 1468: if ($parser eq 'parse') {
1469: my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
1470: unless ($parse_result eq 'ok') {
1471: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1472: }
1473: }
1.477 raeburn 1474: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1475: $home);
1.481 raeburn 1476: if ($fetchresult eq 'ok') {
1477: return '/uploaded/'.$fpath.'/'.$fname;
1478: } else {
1479: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1480: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 1481: return '/adm/notfound.html';
1482: }
1.477 raeburn 1483: }
1484: }
1.485 raeburn 1485: unless ( $fetchresult eq 'ok') {
1.477 raeburn 1486: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 1487: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 1488: }
1489: return $fetchresult;
1490: }
1491:
1.637 raeburn 1492: sub build_filepath {
1493: my ($fpath) = @_;
1494: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1495: unless ($fpath eq '') {
1496: my @parts=split('/',$fpath);
1497: foreach my $part (@parts) {
1498: $filepath.= '/'.$part;
1499: if ((-e $filepath)!=1) {
1500: mkdir($filepath,0777);
1501: }
1502: }
1503: }
1504: return $filepath;
1505: }
1506:
1507: sub store_edited_file {
1.638 albertel 1508: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 1509: my $file = $primary_url;
1510: $file =~ s#^/uploaded/$docudom/$docuname/##;
1511: my $fpath = '';
1512: my $fname = $file;
1513: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1514: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1515: my $filepath = &build_filepath($fpath);
1516: open(my $fh,'>'.$filepath.'/'.$fname);
1517: print $fh $content;
1518: close($fh);
1.638 albertel 1519: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 1520: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 1521: $home);
1.637 raeburn 1522: if ($$fetchresult eq 'ok') {
1523: return '/uploaded/'.$fpath.'/'.$fname;
1524: } else {
1.638 albertel 1525: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1526: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 1527: return '/adm/notfound.html';
1528: }
1529: }
1530:
1.531 albertel 1531: sub clean_filename {
1.831 albertel 1532: my ($fname,$args)=@_;
1.315 www 1533: # Replace Windows backslashes by forward slashes
1.257 www 1534: $fname=~s/\\/\//g;
1.831 albertel 1535: if (!$args->{'keep_path'}) {
1536: # Get rid of everything but the actual filename
1537: $fname=~s/^.*\/([^\/]+)$/$1/;
1538: }
1.315 www 1539: # Replace spaces by underscores
1540: $fname=~s/\s+/\_/g;
1541: # Replace all other weird characters by nothing
1.831 albertel 1542: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 1543: # Replace all .\d. sequences with _\d. so they no longer look like version
1544: # numbers
1545: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 1546: return $fname;
1547: }
1548:
1.608 albertel 1549: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 1550: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719 banghart 1551: # the desired filenam is in $env{"form.$formname.filename"}
1.686 albertel 1552: # $coursedoc - if true up to the current course
1553: # if false
1554: # $subdir - directory in userfile to store the file into
1.858 raeburn 1555: # $parser - instruction to parse file for objects ($parser = parse)
1556: # $allfiles - reference to hash for embedded objects
1557: # $codebase - reference to hash for codebase of java objects
1558: # $desuname - username for permanent storage of uploaded file
1559: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 1560: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
1561: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858 raeburn 1562: #
1.686 albertel 1563: # output: url of file in userspace, or error: <message>
1564: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 1565:
1566:
1.531 albertel 1567: sub userfileupload {
1.860 raeburn 1568: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
1569: $destudom,$thumbwidth,$thumbheight)=@_;
1.531 albertel 1570: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 1571: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 1572: $fname=&clean_filename($fname);
1.315 www 1573: # See if there is anything left
1.257 www 1574: unless ($fname) { return 'error: no uploaded file'; }
1.620 albertel 1575: chop($env{'form.'.$formname});
1.523 raeburn 1576: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
1577: my $now = time;
1578: my $filepath = 'tmp/helprequests/'.$now;
1579: my @parts=split(/\//,$filepath);
1580: my $fullpath = $perlvar{'lonDaemons'};
1581: for (my $i=0;$i<@parts;$i++) {
1582: $fullpath .= '/'.$parts[$i];
1583: if ((-e $fullpath)!=1) {
1584: mkdir($fullpath,0777);
1585: }
1586: }
1587: open(my $fh,'>'.$fullpath.'/'.$fname);
1.620 albertel 1588: print $fh $env{'form.'.$formname};
1.523 raeburn 1589: close($fh);
1.741 raeburn 1590: return $fullpath.'/'.$fname;
1591: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
1592: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
1593: '_'.$env{'user.domain'}.'/pending';
1594: my @parts=split(/\//,$filepath);
1595: my $fullpath = $perlvar{'lonDaemons'};
1596: for (my $i=0;$i<@parts;$i++) {
1597: $fullpath .= '/'.$parts[$i];
1598: if ((-e $fullpath)!=1) {
1599: mkdir($fullpath,0777);
1600: }
1601: }
1602: open(my $fh,'>'.$fullpath.'/'.$fname);
1603: print $fh $env{'form.'.$formname};
1604: close($fh);
1605: return $fullpath.'/'.$fname;
1.523 raeburn 1606: }
1.719 banghart 1607:
1.258 www 1608: # Create the directory if not present
1.493 albertel 1609: $fname="$subdir/$fname";
1.259 www 1610: if ($coursedoc) {
1.638 albertel 1611: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1612: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 1613: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 1614: return &finishuserfileupload($docuname,$docudom,
1615: $formname,$fname,$parser,$allfiles,
1.860 raeburn 1616: $codebase,$thumbwidth,$thumbheight);
1.481 raeburn 1617: } else {
1.620 albertel 1618: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 1619: return &process_coursefile('uploaddoc',$docuname,$docudom,
1620: $fname,$formname,$parser,
1621: $allfiles,$codebase);
1.481 raeburn 1622: }
1.719 banghart 1623: } elsif (defined($destuname)) {
1624: my $docuname=$destuname;
1625: my $docudom=$destudom;
1.860 raeburn 1626: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1627: $parser,$allfiles,$codebase,
1628: $thumbwidth,$thumbheight);
1.719 banghart 1629:
1.259 www 1630: } else {
1.638 albertel 1631: my $docuname=$env{'user.name'};
1632: my $docudom=$env{'user.domain'};
1.714 raeburn 1633: if (exists($env{'form.group'})) {
1634: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
1635: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1636: }
1.860 raeburn 1637: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
1638: $parser,$allfiles,$codebase,
1639: $thumbwidth,$thumbheight);
1.259 www 1640: }
1.271 www 1641: }
1642:
1643: sub finishuserfileupload {
1.860 raeburn 1644: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1645: $thumbwidth,$thumbheight) = @_;
1.477 raeburn 1646: my $path=$docudom.'/'.$docuname.'/';
1.258 www 1647: my $filepath=$perlvar{'lonDocRoot'};
1.860 raeburn 1648: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 1649: $file=$fname;
1650: if ($fname=~m|/|) {
1651: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
1652: $path.=$fnamepath.'/';
1653: }
1.259 www 1654: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 1655: my $count;
1656: for ($count=4;$count<=$#parts;$count++) {
1657: $filepath.="/$parts[$count]";
1658: if ((-e $filepath)!=1) {
1659: mkdir($filepath,0777);
1660: }
1661: }
1662: # Save the file
1663: {
1.701 albertel 1664: if (!open(FH,'>'.$filepath.'/'.$file)) {
1665: &logthis('Failed to create '.$filepath.'/'.$file);
1666: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
1667: return '/adm/notfound.html';
1668: }
1669: if (!print FH ($env{'form.'.$formname})) {
1670: &logthis('Failed to write to '.$filepath.'/'.$file);
1671: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
1672: return '/adm/notfound.html';
1673: }
1.570 albertel 1674: close(FH);
1.258 www 1675: }
1.637 raeburn 1676: if ($parser eq 'parse') {
1.638 albertel 1677: my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
1678: $codebase);
1.637 raeburn 1679: unless ($parse_result eq 'ok') {
1.638 albertel 1680: &logthis('Failed to parse '.$filepath.$file.
1681: ' for embedded media: '.$parse_result);
1.637 raeburn 1682: }
1683: }
1.860 raeburn 1684: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
1685: my $input = $filepath.'/'.$file;
1686: my $output = $filepath.'/'.'tn-'.$file;
1687: my $thumbsize = $thumbwidth.'x'.$thumbheight;
1688: system("convert -sample $thumbsize $input $output");
1689: if (-e $filepath.'/'.'tn-'.$file) {
1690: $fetchthumb = 1;
1691: }
1692: }
1.858 raeburn 1693:
1.259 www 1694: # Notify homeserver to grep it
1695: #
1.638 albertel 1696: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 1697: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 1698: if ($fetchresult eq 'ok') {
1.860 raeburn 1699: if ($fetchthumb) {
1700: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
1701: if ($thumbresult ne 'ok') {
1702: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
1703: $docuhome.': '.$thumbresult);
1704: }
1705: }
1.259 www 1706: #
1.258 www 1707: # Return the URL to it
1.494 albertel 1708: return '/uploaded/'.$path.$file;
1.263 www 1709: } else {
1.494 albertel 1710: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
1711: ': '.$fetchresult);
1.263 www 1712: return '/adm/notfound.html';
1.858 raeburn 1713: }
1.493 albertel 1714: }
1715:
1.637 raeburn 1716: sub extract_embedded_items {
1.648 raeburn 1717: my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637 raeburn 1718: my @state = ();
1719: my %javafiles = (
1720: codebase => '',
1721: code => '',
1722: archive => ''
1723: );
1724: my %mediafiles = (
1725: src => '',
1726: movie => '',
1727: );
1.648 raeburn 1728: my $p;
1729: if ($content) {
1730: $p = HTML::LCParser->new($content);
1731: } else {
1732: $p = HTML::LCParser->new($filepath.'/'.$file);
1733: }
1.641 albertel 1734: while (my $t=$p->get_token()) {
1.640 albertel 1735: if ($t->[0] eq 'S') {
1736: my ($tagname, $attr) = ($t->[1],$t->[2]);
1737: push (@state, $tagname);
1.648 raeburn 1738: if (lc($tagname) eq 'allow') {
1739: &add_filetype($allfiles,$attr->{'src'},'src');
1740: }
1.640 albertel 1741: if (lc($tagname) eq 'img') {
1742: &add_filetype($allfiles,$attr->{'src'},'src');
1743: }
1.645 raeburn 1744: if (lc($tagname) eq 'script') {
1745: if ($attr->{'archive'} =~ /\.jar$/i) {
1746: &add_filetype($allfiles,$attr->{'archive'},'archive');
1747: } else {
1748: &add_filetype($allfiles,$attr->{'src'},'src');
1749: }
1750: }
1751: if (lc($tagname) eq 'link') {
1752: if (lc($attr->{'rel'}) eq 'stylesheet') {
1753: &add_filetype($allfiles,$attr->{'href'},'href');
1754: }
1755: }
1.640 albertel 1756: if (lc($tagname) eq 'object' ||
1757: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
1758: foreach my $item (keys(%javafiles)) {
1759: $javafiles{$item} = '';
1760: }
1761: }
1762: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
1763: my $name = lc($attr->{'name'});
1764: foreach my $item (keys(%javafiles)) {
1765: if ($name eq $item) {
1766: $javafiles{$item} = $attr->{'value'};
1767: last;
1768: }
1769: }
1770: foreach my $item (keys(%mediafiles)) {
1771: if ($name eq $item) {
1772: &add_filetype($allfiles, $attr->{'value'}, 'value');
1773: last;
1774: }
1775: }
1776: }
1777: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
1778: foreach my $item (keys(%javafiles)) {
1779: if ($attr->{$item}) {
1780: $javafiles{$item} = $attr->{$item};
1781: last;
1782: }
1783: }
1784: foreach my $item (keys(%mediafiles)) {
1785: if ($attr->{$item}) {
1786: &add_filetype($allfiles,$attr->{$item},$item);
1787: last;
1788: }
1789: }
1790: }
1791: } elsif ($t->[0] eq 'E') {
1792: my ($tagname) = ($t->[1]);
1793: if ($javafiles{'codebase'} ne '') {
1794: $javafiles{'codebase'} .= '/';
1795: }
1796: if (lc($tagname) eq 'applet' ||
1797: lc($tagname) eq 'object' ||
1798: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
1799: ) {
1800: foreach my $item (keys(%javafiles)) {
1801: if ($item ne 'codebase' && $javafiles{$item} ne '') {
1802: my $file=$javafiles{'codebase'}.$javafiles{$item};
1803: &add_filetype($allfiles,$file,$item);
1804: }
1805: }
1806: }
1807: pop @state;
1808: }
1809: }
1.637 raeburn 1810: return 'ok';
1811: }
1812:
1.639 albertel 1813: sub add_filetype {
1814: my ($allfiles,$file,$type)=@_;
1815: if (exists($allfiles->{$file})) {
1816: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
1817: push(@{$allfiles->{$file}}, &escape($type));
1818: }
1819: } else {
1820: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 1821: }
1822: }
1823:
1.493 albertel 1824: sub removeuploadedurl {
1825: my ($url)=@_;
1826: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 1827: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 1828: }
1829:
1830: sub removeuserfile {
1831: my ($docuname,$docudom,$fname)=@_;
1832: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1833: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1834: if ($result eq 'ok') {
1835: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
1836: my $metafile = $fname.'.meta';
1837: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 1838: my $url = "/uploaded/$docudom/$docuname/$fname";
1839: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1840: my $sqlresult =
1.823 albertel 1841: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1842: 'portfolio_metadata',$group,
1843: 'delete');
1.798 raeburn 1844: }
1845: }
1846: return $result;
1.257 www 1847: }
1.15 www 1848:
1.530 albertel 1849: sub mkdiruserfile {
1850: my ($docuname,$docudom,$dir)=@_;
1851: my $home=&homeserver($docuname,$docudom);
1852: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
1853: }
1854:
1.531 albertel 1855: sub renameuserfile {
1856: my ($docuname,$docudom,$old,$new)=@_;
1857: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 1858: my $result = &reply("renameuserfile:$docudom:$docuname:".
1859: &escape("$old").':'.&escape("$new"),$home);
1860: if ($result eq 'ok') {
1861: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
1862: my $oldmeta = $old.'.meta';
1863: my $newmeta = $new.'.meta';
1864: my $metaresult =
1865: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 1866: my $url = "/uploaded/$docudom/$docuname/$old";
1867: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 1868: my $sqlresult =
1.823 albertel 1869: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 1870: 'portfolio_metadata',$group,
1871: 'delete');
1.798 raeburn 1872: }
1873: }
1874: return $result;
1.531 albertel 1875: }
1876:
1.14 www 1877: # ------------------------------------------------------------------------- Log
1878:
1879: sub log {
1880: my ($dom,$nam,$hom,$what)=@_;
1.47 www 1881: return critical("log:$dom:$nam:$what",$hom);
1.157 www 1882: }
1883:
1884: # ------------------------------------------------------------------ Course Log
1.352 www 1885: #
1886: # This routine flushes several buffers of non-mission-critical nature
1887: #
1.157 www 1888:
1889: sub flushcourselogs {
1.352 www 1890: &logthis('Flushing log buffers');
1891: #
1892: # course logs
1893: # This is a log of all transactions in a course, which can be used
1894: # for data mining purposes
1895: #
1896: # It also collects the courseid database, which lists last transaction
1897: # times and course titles for all courseids
1898: #
1899: my %courseidbuffer=();
1.800 albertel 1900: foreach my $crsid (keys %courselogs) {
1.352 www 1901: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 1902: &escape($courselogs{$crsid}),
1903: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 1904: delete $courselogs{$crsid};
1905: } else {
1906: &logthis('Failed to flush log buffer for '.$crsid);
1907: if (length($courselogs{$crsid})>40000) {
1.672 albertel 1908: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 1909: " exceeded maximum size, deleting.</font>");
1910: delete $courselogs{$crsid};
1911: }
1.352 www 1912: }
1913: if ($courseidbuffer{$coursehombuf{$crsid}}) {
1914: $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516 raeburn 1915: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1916: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352 www 1917: } else {
1918: $courseidbuffer{$coursehombuf{$crsid}}=
1.516 raeburn 1919: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741 raeburn 1920: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571 raeburn 1921: }
1.191 harris41 1922: }
1.352 www 1923: #
1924: # Write course id database (reverse lookup) to homeserver of courses
1925: # Is used in pickcourse
1926: #
1.840 albertel 1927: foreach my $crs_home (keys(%courseidbuffer)) {
1.844 albertel 1928: &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840 albertel 1929: $crs_home);
1.352 www 1930: }
1931: #
1932: # File accesses
1933: # Writes to the dynamic metadata of resources to get hit counts, etc.
1934: #
1.449 matthew 1935: foreach my $entry (keys(%accesshash)) {
1.458 matthew 1936: if ($entry =~ /___count$/) {
1937: my ($dom,$name);
1.807 albertel 1938: ($dom,$name,undef)=
1.811 albertel 1939: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 1940: if (! defined($dom) || $dom eq '' ||
1941: ! defined($name) || $name eq '') {
1.620 albertel 1942: my $cid = $env{'request.course.id'};
1943: $dom = $env{'request.'.$cid.'.domain'};
1944: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 1945: }
1.450 matthew 1946: my $value = $accesshash{$entry};
1947: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
1948: my %temphash=($url => $value);
1.449 matthew 1949: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
1950: if ($result eq 'ok') {
1951: delete $accesshash{$entry};
1952: } elsif ($result eq 'unknown_cmd') {
1953: # Target server has old code running on it.
1.450 matthew 1954: my %temphash=($entry => $value);
1.449 matthew 1955: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1956: delete $accesshash{$entry};
1957: }
1958: }
1959: } else {
1.811 albertel 1960: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 1961: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 1962: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
1963: delete $accesshash{$entry};
1964: }
1.185 www 1965: }
1.191 harris41 1966: }
1.352 www 1967: #
1968: # Roles
1969: # Reverse lookup of user roles for course faculty/staff and co-authorship
1970: #
1.800 albertel 1971: foreach my $entry (keys(%userrolehash)) {
1.351 www 1972: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 1973: split(/\:/,$entry);
1974: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 1975: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 1976: $rudom,$runame) eq 'ok') {
1977: delete $userrolehash{$entry};
1978: }
1979: }
1.662 raeburn 1980: #
1981: # Reverse lookup of domain roles (dc, ad, li, sc, au)
1982: #
1983: my %domrolebuffer = ();
1984: foreach my $entry (keys %domainrolehash) {
1985: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
1986: if ($domrolebuffer{$rudom}) {
1987: $domrolebuffer{$rudom}.='&'.&escape($entry).
1988: '='.&escape($domainrolehash{$entry});
1989: } else {
1990: $domrolebuffer{$rudom}.=&escape($entry).
1991: '='.&escape($domainrolehash{$entry});
1992: }
1993: delete $domainrolehash{$entry};
1994: }
1995: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 1996: my %servers = &get_servers($dom,'library');
1997: foreach my $tryserver (keys(%servers)) {
1998: unless (&reply('domroleput:'.$dom.':'.
1999: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2000: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2001: }
1.662 raeburn 2002: }
2003: }
1.186 www 2004: $dumpcount++;
1.157 www 2005: }
2006:
2007: sub courselog {
2008: my $what=shift;
1.158 www 2009: $what=time.':'.$what;
1.620 albertel 2010: unless ($env{'request.course.id'}) { return ''; }
2011: $coursedombuf{$env{'request.course.id'}}=
2012: $env{'course.'.$env{'request.course.id'}.'.domain'};
2013: $coursenumbuf{$env{'request.course.id'}}=
2014: $env{'course.'.$env{'request.course.id'}.'.num'};
2015: $coursehombuf{$env{'request.course.id'}}=
2016: $env{'course.'.$env{'request.course.id'}.'.home'};
2017: $coursedescrbuf{$env{'request.course.id'}}=
2018: $env{'course.'.$env{'request.course.id'}.'.description'};
2019: $courseinstcodebuf{$env{'request.course.id'}}=
2020: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2021: $courseownerbuf{$env{'request.course.id'}}=
2022: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 2023: $coursetypebuf{$env{'request.course.id'}}=
2024: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 2025: if (defined $courselogs{$env{'request.course.id'}}) {
2026: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 2027: } else {
1.620 albertel 2028: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 2029: }
1.620 albertel 2030: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 2031: &flushcourselogs();
2032: }
1.158 www 2033: }
2034:
2035: sub courseacclog {
2036: my $fnsymb=shift;
1.620 albertel 2037: unless ($env{'request.course.id'}) { return ''; }
2038: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 2039: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 2040: $what.=':POST';
1.583 matthew 2041: # FIXME: Probably ought to escape things....
1.800 albertel 2042: foreach my $key (keys(%env)) {
2043: if ($key=~/^form\.(.*)/) {
2044: $what.=':'.$1.'='.$env{$key};
1.158 www 2045: }
1.191 harris41 2046: }
1.583 matthew 2047: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2048: # FIXME: We should not be depending on a form parameter that someone
2049: # editing lonsearchcat.pm might change in the future.
1.620 albertel 2050: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 2051: $what.= ':POST';
2052: # FIXME: Probably ought to escape things....
2053: foreach my $element ('courseexp','crsfulltext','crsrelated',
2054: 'crsdiscuss') {
1.620 albertel 2055: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 2056: }
2057: }
1.158 www 2058: }
2059: &courselog($what);
1.149 www 2060: }
2061:
1.185 www 2062: sub countacc {
2063: my $url=&declutter(shift);
1.458 matthew 2064: return if (! defined($url) || $url eq '');
1.620 albertel 2065: unless ($env{'request.course.id'}) { return ''; }
2066: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 2067: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 2068: $accesshash{$key}++;
1.185 www 2069: }
1.349 www 2070:
1.361 www 2071: sub linklog {
2072: my ($from,$to)=@_;
2073: $from=&declutter($from);
2074: $to=&declutter($to);
2075: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2076: $accesshash{$to.'___'.$from.'___goto'}=1;
2077: }
2078:
1.349 www 2079: sub userrolelog {
2080: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 2081: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 2082: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 2083: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2084: ($trole=~/^ta/)) {
1.350 www 2085: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2086: $userrolehash
2087: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 2088: =$tend.':'.$tstart;
1.662 raeburn 2089: }
2090: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2091: ($trole=~/^li/) || ($trole=~/^li/) ||
2092: ($trole=~/^au/) || ($trole=~/^dg/) ||
2093: ($trole=~/^sc/)) {
2094: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2095: $domainrolehash
2096: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2097: = $tend.':'.$tstart;
2098: }
1.351 www 2099: }
2100:
2101: sub get_course_adv_roles {
2102: my $cid=shift;
1.620 albertel 2103: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 2104: my %coursehash=&coursedescription($cid);
1.470 www 2105: my %nothide=();
1.800 albertel 2106: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2107: $nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470 www 2108: }
1.351 www 2109: my %returnhash=();
2110: my %dumphash=
2111: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2112: my $now=time;
1.800 albertel 2113: foreach my $entry (keys %dumphash) {
2114: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 2115: if (($tstart) && ($tstart<0)) { next; }
2116: if (($tend) && ($tend<$now)) { next; }
2117: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 2118: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 2119: if ($username eq '' || $domain eq '') { next; }
1.470 www 2120: if ((&privileged($username,$domain)) &&
2121: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 2122: if ($role eq 'cr') { next; }
1.351 www 2123: my $key=&plaintext($role);
2124: if ($section) { $key.=' (Sec/Grp '.$section.')'; }
2125: if ($returnhash{$key}) {
2126: $returnhash{$key}.=','.$username.':'.$domain;
2127: } else {
2128: $returnhash{$key}=$username.':'.$domain;
2129: }
1.400 www 2130: }
2131: return %returnhash;
2132: }
2133:
2134: sub get_my_roles {
1.858 raeburn 2135: my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620 albertel 2136: unless (defined($uname)) { $uname=$env{'user.name'}; }
2137: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858 raeburn 2138: my %dumphash;
2139: if ($context eq 'userroles') {
2140: %dumphash = &dump('roles',$udom,$uname);
2141: } else {
2142: %dumphash=
1.400 www 2143: &dump('nohist_userroles',$udom,$uname);
1.858 raeburn 2144: }
1.400 www 2145: my %returnhash=();
2146: my $now=time;
1.800 albertel 2147: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 2148: my ($role,$tend,$tstart);
2149: if ($context eq 'userroles') {
2150: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2151: } else {
2152: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2153: }
1.400 www 2154: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 2155: my $status = 'active';
2156: if (($tend) && ($tend<$now)) {
2157: $status = 'previous';
2158: }
2159: if (($tstart) && ($now<$tstart)) {
2160: $status = 'future';
2161: }
2162: if (ref($types) eq 'ARRAY') {
2163: if (!grep(/^\Q$status\E$/,@{$types})) {
2164: next;
2165: }
2166: } else {
2167: if ($status ne 'active') {
2168: next;
2169: }
2170: }
1.867 raeburn 2171: my ($rolecode,$username,$domain,$section,$area);
2172: if ($context eq 'userroles') {
2173: ($area,$rolecode) = split(/_/,$entry);
2174: (undef,$domain,$username,$section) = split(/\//,$area);
2175: } else {
2176: ($role,$username,$domain,$section) = split(/\:/,$entry);
2177: }
1.832 raeburn 2178: if (ref($roledoms) eq 'ARRAY') {
2179: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2180: next;
2181: }
2182: }
2183: if (ref($roles) eq 'ARRAY') {
2184: if (!grep(/^\Q$role\E$/,@{$roles})) {
2185: next;
2186: }
1.867 raeburn 2187: }
1.400 www 2188: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832 raeburn 2189: }
1.373 www 2190: return %returnhash;
1.399 www 2191: }
2192:
2193: # ----------------------------------------------------- Frontpage Announcements
2194: #
2195: #
2196:
2197: sub postannounce {
2198: my ($server,$text)=@_;
1.844 albertel 2199: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 2200: unless ($text=~/\w/) { $text=''; }
2201: return &reply('setannounce:'.&escape($text),$server);
2202: }
2203:
2204: sub getannounce {
1.448 albertel 2205:
2206: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 2207: my $announcement='';
1.800 albertel 2208: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 2209: close($fh);
1.399 www 2210: if ($announcement=~/\w/) {
2211: return
2212: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 2213: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 2214: } else {
2215: return '';
2216: }
2217: } else {
2218: return '';
2219: }
1.351 www 2220: }
1.353 www 2221:
2222: # ---------------------------------------------------------- Course ID routines
2223: # Deal with domain's nohist_courseid.db files
2224: #
2225:
2226: sub courseidput {
2227: my ($domain,$what,$coursehome)=@_;
2228: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2229: }
2230:
2231: sub courseiddump {
1.791 raeburn 2232: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353 www 2233: my %returnhash=();
1.355 www 2234: unless ($domfilter) { $domfilter=''; }
1.845 albertel 2235: my %libserv = &all_library();
2236: foreach my $tryserver (keys(%libserv)) {
2237: if ( ( $hostidflag == 1
2238: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2239: || (!defined($hostidflag)) ) {
2240:
2241: if ($domfilter eq ''
2242: || (&host_domain($tryserver) eq $domfilter)) {
1.800 albertel 2243: foreach my $line (
1.844 albertel 2244: split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571 raeburn 2245: $sincefilter.':'.&escape($descfilter).':'.
1.791 raeburn 2246: &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354 www 2247: $tryserver))) {
1.800 albertel 2248: my ($key,$value)=split(/\=/,$line,2);
1.506 raeburn 2249: if (($key) && ($value)) {
1.516 raeburn 2250: $returnhash{&unescape($key)}=$value;
1.506 raeburn 2251: }
1.353 www 2252: }
2253: }
2254: }
2255: }
2256: return %returnhash;
2257: }
2258:
1.658 raeburn 2259: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 2260:
2261: sub dcmailput {
1.685 raeburn 2262: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 2263: my $status = &Apache::lonnet::critical(
1.740 www 2264: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2265: &escape($message),$server);
1.662 raeburn 2266: return $status;
2267: }
2268:
1.658 raeburn 2269: sub dcmaildump {
2270: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 2271: my %returnhash=();
1.846 albertel 2272:
2273: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 2274: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2275: &escape($enddate).':';
2276: my @esc_senders=map { &escape($_)} @$senders;
2277: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 2278: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 2279: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 2280: if (($key) && ($value)) {
2281: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 2282: }
2283: }
2284: }
2285: return %returnhash;
2286: }
1.662 raeburn 2287: # ---------------------------------------------------------- Domain roles
2288:
2289: sub get_domain_roles {
2290: my ($dom,$roles,$startdate,$enddate)=@_;
2291: if (undef($startdate) || $startdate eq '') {
2292: $startdate = '.';
2293: }
2294: if (undef($enddate) || $enddate eq '') {
2295: $enddate = '.';
2296: }
2297: my $rolelist = join(':',@{$roles});
2298: my %personnel = ();
1.841 albertel 2299:
2300: my %servers = &get_servers($dom,'library');
2301: foreach my $tryserver (keys(%servers)) {
2302: %{$personnel{$tryserver}}=();
2303: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2304: &escape($startdate).':'.
2305: &escape($enddate).':'.
2306: &escape($rolelist), $tryserver))) {
2307: my ($key,$value) = split(/\=/,$line,2);
2308: if (($key) && ($value)) {
2309: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2310: }
2311: }
1.662 raeburn 2312: }
2313: return %personnel;
2314: }
1.658 raeburn 2315:
1.149 www 2316: # ----------------------------------------------------------- Check out an item
2317:
1.504 albertel 2318: sub get_first_access {
2319: my ($type,$argsymb)=@_;
1.790 albertel 2320: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2321: if ($argsymb) { $symb=$argsymb; }
2322: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2323: if ($type eq 'map') {
2324: $res=&symbread($map);
2325: } else {
2326: $res=$symb;
2327: }
2328: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2329: return $times{"$courseid\0$res"};
1.504 albertel 2330: }
2331:
2332: sub set_first_access {
2333: my ($type)=@_;
1.790 albertel 2334: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 2335: my ($map,$id,$res)=&decode_symb($symb);
1.588 albertel 2336: if ($type eq 'map') {
2337: $res=&symbread($map);
2338: } else {
2339: $res=$symb;
2340: }
2341: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 2342: if (!$firstaccess) {
1.588 albertel 2343: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 2344: }
2345: return 'already_set';
1.504 albertel 2346: }
2347:
1.149 www 2348: sub checkout {
2349: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2350: my $now=time;
2351: my $lonhost=$perlvar{'lonHostID'};
2352: my $infostr=&escape(
1.234 www 2353: 'CHECKOUTTOKEN&'.
1.149 www 2354: $tuname.'&'.
2355: $tudom.'&'.
2356: $tcrsid.'&'.
2357: $symb.'&'.
2358: $now.'&'.$ENV{'REMOTE_ADDR'});
2359: my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151 www 2360: if ($token=~/^error\:/) {
1.672 albertel 2361: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2362: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2363: "</font>");
2364: return '';
2365: }
2366:
1.149 www 2367: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2368: $token=~tr/a-z/A-Z/;
2369:
1.153 www 2370: my %infohash=('resource.0.outtoken' => $token,
2371: 'resource.0.checkouttime' => $now,
2372: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149 www 2373:
2374: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2375: return '';
1.151 www 2376: } else {
1.672 albertel 2377: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2378: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2379: "</font>");
1.149 www 2380: }
2381:
2382: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2383: &escape('Checkout '.$infostr.' - '.
2384: $token)) ne 'ok') {
2385: return '';
1.151 www 2386: } else {
1.672 albertel 2387: &logthis("<font color=\"blue\">WARNING: ".
1.151 www 2388: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2389: "</font>");
1.149 www 2390: }
1.151 www 2391: return $token;
1.149 www 2392: }
2393:
2394: # ------------------------------------------------------------ Check in an item
2395:
2396: sub checkin {
2397: my $token=shift;
1.150 www 2398: my $now=time;
2399: my ($ta,$tb,$lonhost)=split(/\*/,$token);
2400: $lonhost=~tr/A-Z/a-z/;
1.838 albertel 2401: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150 www 2402: $dtoken=~s/\W/\_/g;
1.234 www 2403: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150 www 2404: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
2405:
1.154 www 2406: unless (($tuname) && ($tudom)) {
2407: &logthis('Check in '.$token.' ('.$dtoken.') failed');
2408: return '';
2409: }
2410:
2411: unless (&allowed('mgr',$tcrsid)) {
2412: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620 albertel 2413: $env{'user.name'}.' - '.$env{'user.domain'});
1.154 www 2414: return '';
2415: }
2416:
1.153 www 2417: my %infohash=('resource.0.intoken' => $token,
2418: 'resource.0.checkintime' => $now,
2419: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150 www 2420:
2421: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2422: return '';
2423: }
2424:
2425: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2426: &escape('Checkin - '.$token)) ne 'ok') {
2427: return '';
2428: }
2429:
2430: return ($symb,$tuname,$tudom,$tcrsid);
1.110 www 2431: }
2432:
2433: # --------------------------------------------- Set Expire Date for Spreadsheet
2434:
2435: sub expirespread {
2436: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 2437: my $cid=$env{'request.course.id'};
1.110 www 2438: if ($cid) {
2439: my $now=time;
2440: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 2441: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
2442: $env{'course.'.$cid.'.num'}.
1.110 www 2443: ':nohist_expirationdates:'.
2444: &escape($key).'='.$now,
1.620 albertel 2445: $env{'course.'.$cid.'.home'})
1.110 www 2446: }
2447: return 'ok';
1.14 www 2448: }
2449:
1.109 www 2450: # ----------------------------------------------------- Devalidate Spreadsheets
2451:
2452: sub devalidate {
1.325 www 2453: my ($symb,$uname,$udom)=@_;
1.620 albertel 2454: my $cid=$env{'request.course.id'};
1.109 www 2455: if ($cid) {
1.391 matthew 2456: # delete the stored spreadsheets for
2457: # - the student level sheet of this user in course's homespace
2458: # - the assessment level sheet for this resource
2459: # for this user in user's homespace
1.553 albertel 2460: # - current conditional state info
1.325 www 2461: my $key=$uname.':'.$udom.':';
1.109 www 2462: my $status=
1.299 matthew 2463: &del('nohist_calculatedsheets',
1.391 matthew 2464: [$key.'studentcalc:'],
1.620 albertel 2465: $env{'course.'.$cid.'.domain'},
2466: $env{'course.'.$cid.'.num'})
1.133 albertel 2467: .' '.
2468: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 2469: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 2470: unless ($status eq 'ok ok') {
2471: &logthis('Could not devalidate spreadsheet '.
1.325 www 2472: $uname.' at '.$udom.' for '.
1.109 www 2473: $symb.': '.$status);
1.133 albertel 2474: }
1.553 albertel 2475: &delenv('user.state.'.$cid);
1.109 www 2476: }
2477: }
2478:
1.265 albertel 2479: sub get_scalar {
2480: my ($string,$end) = @_;
2481: my $value;
2482: if ($$string =~ s/^([^&]*?)($end)/$2/) {
2483: $value = $1;
2484: } elsif ($$string =~ s/^([^&]*?)&//) {
2485: $value = $1;
2486: }
2487: return &unescape($value);
2488: }
2489:
2490: sub array2str {
2491: my (@array) = @_;
2492: my $result=&arrayref2str(\@array);
2493: $result=~s/^__ARRAY_REF__//;
2494: $result=~s/__END_ARRAY_REF__$//;
2495: return $result;
2496: }
2497:
1.204 albertel 2498: sub arrayref2str {
2499: my ($arrayref) = @_;
1.265 albertel 2500: my $result='__ARRAY_REF__';
1.204 albertel 2501: foreach my $elem (@$arrayref) {
1.265 albertel 2502: if(ref($elem) eq 'ARRAY') {
2503: $result.=&arrayref2str($elem).'&';
2504: } elsif(ref($elem) eq 'HASH') {
2505: $result.=&hashref2str($elem).'&';
2506: } elsif(ref($elem)) {
2507: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 2508: } else {
2509: $result.=&escape($elem).'&';
2510: }
2511: }
2512: $result=~s/\&$//;
1.265 albertel 2513: $result .= '__END_ARRAY_REF__';
1.204 albertel 2514: return $result;
2515: }
2516:
1.168 albertel 2517: sub hash2str {
1.204 albertel 2518: my (%hash) = @_;
2519: my $result=&hashref2str(\%hash);
1.265 albertel 2520: $result=~s/^__HASH_REF__//;
2521: $result=~s/__END_HASH_REF__$//;
1.204 albertel 2522: return $result;
2523: }
2524:
2525: sub hashref2str {
2526: my ($hashref)=@_;
1.265 albertel 2527: my $result='__HASH_REF__';
1.800 albertel 2528: foreach my $key (sort(keys(%$hashref))) {
2529: if (ref($key) eq 'ARRAY') {
2530: $result.=&arrayref2str($key).'=';
2531: } elsif (ref($key) eq 'HASH') {
2532: $result.=&hashref2str($key).'=';
2533: } elsif (ref($key)) {
1.265 albertel 2534: $result.='=';
1.800 albertel 2535: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 2536: } else {
1.800 albertel 2537: if ($key) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 2538: }
2539:
1.800 albertel 2540: if(ref($hashref->{$key}) eq 'ARRAY') {
2541: $result.=&arrayref2str($hashref->{$key}).'&';
2542: } elsif(ref($hashref->{$key}) eq 'HASH') {
2543: $result.=&hashref2str($hashref->{$key}).'&';
2544: } elsif(ref($hashref->{$key})) {
1.265 albertel 2545: $result.='&';
1.800 albertel 2546: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 2547: } else {
1.800 albertel 2548: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 2549: }
2550: }
1.168 albertel 2551: $result=~s/\&$//;
1.265 albertel 2552: $result .= '__END_HASH_REF__';
1.168 albertel 2553: return $result;
2554: }
2555:
2556: sub str2hash {
1.265 albertel 2557: my ($string)=@_;
2558: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
2559: return %$hash;
2560: }
2561:
2562: sub str2hashref {
1.168 albertel 2563: my ($string) = @_;
1.265 albertel 2564:
2565: my %hash;
2566:
2567: if($string !~ /^__HASH_REF__/) {
2568: if (! ($string eq '' || !defined($string))) {
2569: $hash{'error'}='Not hash reference';
2570: }
2571: return (\%hash, $string);
2572: }
2573:
2574: $string =~ s/^__HASH_REF__//;
2575:
2576: while($string !~ /^__END_HASH_REF__/) {
2577: #key
2578: my $key='';
2579: if($string =~ /^__HASH_REF__/) {
2580: ($key, $string)=&str2hashref($string);
2581: if(defined($key->{'error'})) {
2582: $hash{'error'}='Bad data';
2583: return (\%hash, $string);
2584: }
2585: } elsif($string =~ /^__ARRAY_REF__/) {
2586: ($key, $string)=&str2arrayref($string);
2587: if($key->[0] eq 'Array reference error') {
2588: $hash{'error'}='Bad data';
2589: return (\%hash, $string);
2590: }
2591: } else {
2592: $string =~ s/^(.*?)=//;
1.267 albertel 2593: $key=&unescape($1);
1.265 albertel 2594: }
2595: $string =~ s/^=//;
2596:
2597: #value
2598: my $value='';
2599: if($string =~ /^__HASH_REF__/) {
2600: ($value, $string)=&str2hashref($string);
2601: if(defined($value->{'error'})) {
2602: $hash{'error'}='Bad data';
2603: return (\%hash, $string);
2604: }
2605: } elsif($string =~ /^__ARRAY_REF__/) {
2606: ($value, $string)=&str2arrayref($string);
2607: if($value->[0] eq 'Array reference error') {
2608: $hash{'error'}='Bad data';
2609: return (\%hash, $string);
2610: }
2611: } else {
2612: $value=&get_scalar(\$string,'__END_HASH_REF__');
2613: }
2614: $string =~ s/^&//;
2615:
2616: $hash{$key}=$value;
1.204 albertel 2617: }
1.265 albertel 2618:
2619: $string =~ s/^__END_HASH_REF__//;
2620:
2621: return (\%hash, $string);
1.204 albertel 2622: }
2623:
2624: sub str2array {
1.265 albertel 2625: my ($string)=@_;
2626: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
2627: return @$array;
2628: }
2629:
2630: sub str2arrayref {
1.204 albertel 2631: my ($string) = @_;
1.265 albertel 2632: my @array;
2633:
2634: if($string !~ /^__ARRAY_REF__/) {
2635: if (! ($string eq '' || !defined($string))) {
2636: $array[0]='Array reference error';
2637: }
2638: return (\@array, $string);
2639: }
2640:
2641: $string =~ s/^__ARRAY_REF__//;
2642:
2643: while($string !~ /^__END_ARRAY_REF__/) {
2644: my $value='';
2645: if($string =~ /^__HASH_REF__/) {
2646: ($value, $string)=&str2hashref($string);
2647: if(defined($value->{'error'})) {
2648: $array[0] ='Array reference error';
2649: return (\@array, $string);
2650: }
2651: } elsif($string =~ /^__ARRAY_REF__/) {
2652: ($value, $string)=&str2arrayref($string);
2653: if($value->[0] eq 'Array reference error') {
2654: $array[0] ='Array reference error';
2655: return (\@array, $string);
2656: }
2657: } else {
2658: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
2659: }
2660: $string =~ s/^&//;
2661:
2662: push(@array, $value);
1.191 harris41 2663: }
1.265 albertel 2664:
2665: $string =~ s/^__END_ARRAY_REF__//;
2666:
2667: return (\@array, $string);
1.168 albertel 2668: }
2669:
1.167 albertel 2670: # -------------------------------------------------------------------Temp Store
2671:
1.168 albertel 2672: sub tmpreset {
2673: my ($symb,$namespace,$domain,$stuname) = @_;
2674: if (!$symb) {
2675: $symb=&symbread();
1.620 albertel 2676: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2677: }
2678: $symb=escape($symb);
2679:
1.620 albertel 2680: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 2681: $namespace=~s/\//\_/g;
2682: $namespace=~s/\W//g;
2683:
1.620 albertel 2684: if (!$domain) { $domain=$env{'user.domain'}; }
2685: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2686: if ($domain eq 'public' && $stuname eq 'public') {
2687: $stuname=$ENV{'REMOTE_ADDR'};
2688: }
1.168 albertel 2689: my $path=$perlvar{'lonDaemons'}.'/tmp';
2690: my %hash;
2691: if (tie(%hash,'GDBM_File',
2692: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2693: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2694: foreach my $key (keys %hash) {
1.180 albertel 2695: if ($key=~ /:$symb/) {
1.168 albertel 2696: delete($hash{$key});
2697: }
2698: }
2699: }
2700: }
2701:
1.167 albertel 2702: sub tmpstore {
1.168 albertel 2703: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2704:
2705: if (!$symb) {
2706: $symb=&symbread();
1.620 albertel 2707: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2708: }
2709: $symb=escape($symb);
2710:
2711: if (!$namespace) {
2712: # I don't think we would ever want to store this for a course.
2713: # it seems this will only be used if we don't have a course.
1.620 albertel 2714: #$namespace=$env{'request.course.id'};
1.168 albertel 2715: #if (!$namespace) {
1.620 albertel 2716: $namespace=$env{'request.state'};
1.168 albertel 2717: #}
2718: }
2719: $namespace=~s/\//\_/g;
2720: $namespace=~s/\W//g;
1.620 albertel 2721: if (!$domain) { $domain=$env{'user.domain'}; }
2722: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2723: if ($domain eq 'public' && $stuname eq 'public') {
2724: $stuname=$ENV{'REMOTE_ADDR'};
2725: }
1.168 albertel 2726: my $now=time;
2727: my %hash;
2728: my $path=$perlvar{'lonDaemons'}.'/tmp';
2729: if (tie(%hash,'GDBM_File',
2730: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2731: &GDBM_WRCREAT(),0640)) {
1.168 albertel 2732: $hash{"version:$symb"}++;
2733: my $version=$hash{"version:$symb"};
2734: my $allkeys='';
2735: foreach my $key (keys(%$storehash)) {
2736: $allkeys.=$key.':';
1.591 albertel 2737: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 2738: }
2739: $hash{"$version:$symb:timestamp"}=$now;
2740: $allkeys.='timestamp';
2741: $hash{"$version:keys:$symb"}=$allkeys;
2742: if (untie(%hash)) {
2743: return 'ok';
2744: } else {
2745: return "error:$!";
2746: }
2747: } else {
2748: return "error:$!";
2749: }
2750: }
1.167 albertel 2751:
1.168 albertel 2752: # -----------------------------------------------------------------Temp Restore
1.167 albertel 2753:
1.168 albertel 2754: sub tmprestore {
2755: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 2756:
1.168 albertel 2757: if (!$symb) {
2758: $symb=&symbread();
1.620 albertel 2759: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 2760: }
2761: $symb=escape($symb);
2762:
1.620 albertel 2763: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 2764:
1.620 albertel 2765: if (!$domain) { $domain=$env{'user.domain'}; }
2766: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 2767: if ($domain eq 'public' && $stuname eq 'public') {
2768: $stuname=$ENV{'REMOTE_ADDR'};
2769: }
1.168 albertel 2770: my %returnhash;
2771: $namespace=~s/\//\_/g;
2772: $namespace=~s/\W//g;
2773: my %hash;
2774: my $path=$perlvar{'lonDaemons'}.'/tmp';
2775: if (tie(%hash,'GDBM_File',
2776: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 2777: &GDBM_READER(),0640)) {
1.168 albertel 2778: my $version=$hash{"version:$symb"};
2779: $returnhash{'version'}=$version;
2780: my $scope;
2781: for ($scope=1;$scope<=$version;$scope++) {
2782: my $vkeys=$hash{"$scope:keys:$symb"};
2783: my @keys=split(/:/,$vkeys);
2784: my $key;
2785: $returnhash{"$scope:keys"}=$vkeys;
2786: foreach $key (@keys) {
1.591 albertel 2787: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
2788: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 2789: }
2790: }
1.168 albertel 2791: if (!(untie(%hash))) {
2792: return "error:$!";
2793: }
2794: } else {
2795: return "error:$!";
2796: }
2797: return %returnhash;
1.167 albertel 2798: }
2799:
1.9 www 2800: # ----------------------------------------------------------------------- Store
2801:
2802: sub store {
1.124 www 2803: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2804: my $home='';
2805:
1.168 albertel 2806: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2807:
1.213 www 2808: $symb=&symbclean($symb);
1.122 albertel 2809: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2810:
1.620 albertel 2811: if (!$domain) { $domain=$env{'user.domain'}; }
2812: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2813:
2814: &devalidate($symb,$stuname,$domain);
1.109 www 2815:
2816: $symb=escape($symb);
1.187 www 2817: if (!$namespace) {
1.620 albertel 2818: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2819: return '';
2820: }
2821: }
1.620 albertel 2822: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2823:
2824: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2825: $$storehash{'host'}=$perlvar{'lonHostID'};
2826:
1.12 www 2827: my $namevalue='';
1.800 albertel 2828: foreach my $key (keys(%$storehash)) {
2829: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2830: }
1.12 www 2831: $namevalue=~s/\&$//;
1.187 www 2832: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 2833: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 2834: }
2835:
1.47 www 2836: # -------------------------------------------------------------- Critical Store
2837:
2838: sub cstore {
1.124 www 2839: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
2840: my $home='';
2841:
1.168 albertel 2842: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2843:
1.213 www 2844: $symb=&symbclean($symb);
1.122 albertel 2845: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 2846:
1.620 albertel 2847: if (!$domain) { $domain=$env{'user.domain'}; }
2848: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 2849:
2850: &devalidate($symb,$stuname,$domain);
1.109 www 2851:
2852: $symb=escape($symb);
1.187 www 2853: if (!$namespace) {
1.620 albertel 2854: unless ($namespace=$env{'request.course.id'}) {
1.187 www 2855: return '';
2856: }
2857: }
1.620 albertel 2858: if (!$home) { $home=$env{'user.home'}; }
1.447 www 2859:
2860: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
2861: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 2862:
1.47 www 2863: my $namevalue='';
1.800 albertel 2864: foreach my $key (keys(%$storehash)) {
2865: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 2866: }
1.47 www 2867: $namevalue=~s/\&$//;
1.187 www 2868: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 2869: return critical
2870: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 2871: }
2872:
1.9 www 2873: # --------------------------------------------------------------------- Restore
2874:
2875: sub restore {
1.124 www 2876: my ($symb,$namespace,$domain,$stuname) = @_;
2877: my $home='';
2878:
1.168 albertel 2879: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 2880:
1.122 albertel 2881: if (!$symb) {
2882: unless ($symb=escape(&symbread())) { return ''; }
2883: } else {
1.213 www 2884: $symb=&escape(&symbclean($symb));
1.122 albertel 2885: }
1.188 www 2886: if (!$namespace) {
1.620 albertel 2887: unless ($namespace=$env{'request.course.id'}) {
1.188 www 2888: return '';
2889: }
2890: }
1.620 albertel 2891: if (!$domain) { $domain=$env{'user.domain'}; }
2892: if (!$stuname) { $stuname=$env{'user.name'}; }
2893: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 2894: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
2895:
1.12 www 2896: my %returnhash=();
1.800 albertel 2897: foreach my $line (split(/\&/,$answer)) {
2898: my ($name,$value)=split(/\=/,$line);
1.591 albertel 2899: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 2900: }
1.75 www 2901: my $version;
2902: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 2903: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
2904: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 2905: }
1.75 www 2906: }
1.13 www 2907: return %returnhash;
1.34 www 2908: }
2909:
2910: # ---------------------------------------------------------- Course Description
2911:
2912: sub coursedescription {
1.731 albertel 2913: my ($courseid,$args)=@_;
1.34 www 2914: $courseid=~s/^\///;
1.49 www 2915: $courseid=~s/\_/\//g;
1.34 www 2916: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 2917: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 2918: my $normalid=$cdomain.'_'.$cnum;
2919: # need to always cache even if we get errors otherwise we keep
2920: # trying and trying and trying to get the course description.
2921: my %envhash=();
2922: my %returnhash=();
1.731 albertel 2923:
2924: my $expiretime=600;
2925: if ($env{'request.course.id'} eq $normalid) {
2926: $expiretime=120;
2927: }
2928:
2929: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
2930: if (!$args->{'freshen_cache'}
2931: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
2932: foreach my $key (keys(%env)) {
2933: next if ($key !~ /^\Q$prefix\E(.*)/);
2934: my ($setting) = $1;
2935: $returnhash{$setting} = $env{$key};
2936: }
2937: return %returnhash;
2938: }
2939:
2940: # get the data agin
2941: if (!$args->{'one_time'}) {
2942: $envhash{'course.'.$normalid.'.last_cache'}=time;
2943: }
1.811 albertel 2944:
1.34 www 2945: if ($chome ne 'no_host') {
1.302 albertel 2946: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 2947: if (!exists($returnhash{'con_lost'})) {
2948: $returnhash{'home'}= $chome;
2949: $returnhash{'domain'} = $cdomain;
2950: $returnhash{'num'} = $cnum;
1.741 raeburn 2951: if (!defined($returnhash{'type'})) {
2952: $returnhash{'type'} = 'Course';
2953: }
1.130 albertel 2954: while (my ($name,$value) = each %returnhash) {
1.53 www 2955: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 2956: }
1.270 www 2957: $returnhash{'url'}=&clutter($returnhash{'url'});
1.34 www 2958: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620 albertel 2959: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60 www 2960: $envhash{'course.'.$normalid.'.home'}=$chome;
2961: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
2962: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 2963: }
2964: }
1.731 albertel 2965: if (!$args->{'one_time'}) {
2966: &appenv(%envhash);
2967: }
1.302 albertel 2968: return %returnhash;
1.461 www 2969: }
2970:
2971: # -------------------------------------------------See if a user is privileged
2972:
2973: sub privileged {
2974: my ($username,$domain)=@_;
2975: my $rolesdump=&reply("dump:$domain:$username:roles",
2976: &homeserver($username,$domain));
2977: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
2978: my $now=time;
2979: if ($rolesdump ne '') {
1.800 albertel 2980: foreach my $entry (split(/&/,$rolesdump)) {
2981: if ($entry!~/^rolesdef_/) {
2982: my ($area,$role)=split(/=/,$entry);
1.461 www 2983: $area=~s/\_\w\w$//;
2984: my ($trole,$tend,$tstart)=split(/_/,$role);
2985: if (($trole eq 'dc') || ($trole eq 'su')) {
2986: my $active=1;
2987: if ($tend) {
2988: if ($tend<$now) { $active=0; }
2989: }
2990: if ($tstart) {
2991: if ($tstart>$now) { $active=0; }
2992: }
2993: if ($active) { return 1; }
2994: }
2995: }
2996: }
2997: }
2998: return 0;
1.9 www 2999: }
1.1 albertel 3000:
1.103 harris41 3001: # -------------------------------------------------------- Get user privileges
1.11 www 3002:
3003: sub rolesinit {
3004: my ($domain,$username,$authhost)=@_;
3005: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12 www 3006: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11 www 3007: my %allroles=();
1.678 raeburn 3008: my %allgroups=();
1.11 www 3009: my $now=time;
1.743 albertel 3010: my %userroles = ('user.login.time' => $now);
1.678 raeburn 3011: my $group_privs;
1.11 www 3012:
3013: if ($rolesdump ne '') {
1.800 albertel 3014: foreach my $entry (split(/&/,$rolesdump)) {
3015: if ($entry!~/^rolesdef_/) {
3016: my ($area,$role)=split(/=/,$entry);
1.587 albertel 3017: $area=~s/\_\w\w$//;
1.678 raeburn 3018: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 3019: if ($role=~/^cr/) {
1.807 albertel 3020: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3021: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 3022: ($tend,$tstart)=split('_',$trest);
3023: } else {
3024: $trole=$role;
3025: }
1.678 raeburn 3026: } elsif ($role =~ m|^gr/|) {
3027: ($trole,$tend,$tstart) = split(/_/,$role);
3028: ($trole,$group_privs) = split(/\//,$trole);
3029: $group_privs = &unescape($group_privs);
1.587 albertel 3030: } else {
3031: ($trole,$tend,$tstart)=split(/_/,$role);
3032: }
1.743 albertel 3033: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3034: $username);
3035: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 3036: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3037: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 3038: if (($area ne '') && ($trole ne '')) {
1.347 albertel 3039: my $spec=$trole.'.'.$area;
3040: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3041: if ($trole =~ /^cr\//) {
1.567 raeburn 3042: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 3043: } elsif ($trole eq 'gr') {
3044: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 3045: } else {
1.567 raeburn 3046: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 3047: }
1.12 www 3048: }
1.662 raeburn 3049: }
1.191 harris41 3050: }
1.743 albertel 3051: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3052: $userroles{'user.adv'} = $adv;
3053: $userroles{'user.author'} = $author;
1.620 albertel 3054: $env{'user.adv'}=$adv;
1.11 www 3055: }
1.743 albertel 3056: return \%userroles;
1.11 www 3057: }
3058:
1.567 raeburn 3059: sub set_arearole {
3060: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3061: # log the associated role with the area
3062: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 3063: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 3064: }
3065:
3066: sub custom_roleprivs {
3067: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3068: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3069: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 3070: if (&hostname($homsvr) ne '') {
1.567 raeburn 3071: my ($rdummy,$roledef)=
3072: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3073: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3074: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3075: if (defined($syspriv)) {
3076: $$allroles{'cm./'}.=':'.$syspriv;
3077: $$allroles{$spec.'./'}.=':'.$syspriv;
3078: }
3079: if ($tdomain ne '') {
3080: if (defined($dompriv)) {
3081: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3082: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3083: }
3084: if (($trest ne '') && (defined($coursepriv))) {
3085: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3086: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3087: }
3088: }
3089: }
3090: }
3091: }
3092:
1.678 raeburn 3093: sub group_roleprivs {
3094: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3095: my $access = 1;
3096: my $now = time;
3097: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3098: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3099: if ($access) {
1.811 albertel 3100: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 3101: $$allgroups{$course}{$group} .=':'.$group_privs;
3102: }
3103: }
1.567 raeburn 3104:
3105: sub standard_roleprivs {
3106: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3107: if (defined($pr{$trole.':s'})) {
3108: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3109: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3110: }
3111: if ($tdomain ne '') {
3112: if (defined($pr{$trole.':d'})) {
3113: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3114: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3115: }
3116: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3117: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3118: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3119: }
3120: }
3121: }
3122:
3123: sub set_userprivs {
1.678 raeburn 3124: my ($userroles,$allroles,$allgroups) = @_;
1.567 raeburn 3125: my $author=0;
3126: my $adv=0;
1.678 raeburn 3127: my %grouproles = ();
3128: if (keys(%{$allgroups}) > 0) {
3129: foreach my $role (keys %{$allroles}) {
1.681 raeburn 3130: my ($trole,$area,$sec,$extendedarea);
1.811 albertel 3131: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678 raeburn 3132: $trole = $1;
3133: $area = $2;
1.681 raeburn 3134: $sec = $3;
3135: $extendedarea = $area.$sec;
3136: if (exists($$allgroups{$area})) {
3137: foreach my $group (keys(%{$$allgroups{$area}})) {
3138: my $spec = $trole.'.'.$extendedarea;
3139: $grouproles{$spec.'.'.$area.'/'.$group} =
3140: $$allgroups{$area}{$group};
1.678 raeburn 3141: }
3142: }
3143: }
3144: }
3145: }
1.800 albertel 3146: foreach my $group (keys(%grouproles)) {
3147: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 3148: }
1.800 albertel 3149: foreach my $role (keys(%{$allroles})) {
3150: my %thesepriv;
3151: if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
3152: foreach my $item (split(/:/,$$allroles{$role})) {
3153: if ($item ne '') {
3154: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 3155: if ($restrictions eq '') {
3156: $thesepriv{$privilege}='F';
3157: } elsif ($thesepriv{$privilege} ne 'F') {
3158: $thesepriv{$privilege}.=$restrictions;
3159: }
3160: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3161: }
3162: }
3163: my $thesestr='';
1.800 albertel 3164: foreach my $priv (keys(%thesepriv)) {
3165: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3166: }
3167: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 3168: }
3169: return ($author,$adv);
3170: }
3171:
1.12 www 3172: # --------------------------------------------------------------- get interface
3173:
3174: sub get {
1.131 albertel 3175: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3176: my $items='';
1.800 albertel 3177: foreach my $item (@$storearr) {
3178: $items.=&escape($item).'&';
1.191 harris41 3179: }
1.12 www 3180: $items=~s/\&$//;
1.620 albertel 3181: if (!$udomain) { $udomain=$env{'user.domain'}; }
3182: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 3183: my $uhome=&homeserver($uname,$udomain);
3184:
1.133 albertel 3185: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3186: my @pairs=split(/\&/,$rep);
1.273 albertel 3187: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3188: return @pairs;
3189: }
1.15 www 3190: my %returnhash=();
1.42 www 3191: my $i=0;
1.800 albertel 3192: foreach my $item (@$storearr) {
3193: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3194: $i++;
1.191 harris41 3195: }
1.15 www 3196: return %returnhash;
1.27 www 3197: }
3198:
3199: # --------------------------------------------------------------- del interface
3200:
3201: sub del {
1.133 albertel 3202: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 3203: my $items='';
1.800 albertel 3204: foreach my $item (@$storearr) {
3205: $items.=&escape($item).'&';
1.191 harris41 3206: }
1.27 www 3207: $items=~s/\&$//;
1.620 albertel 3208: if (!$udomain) { $udomain=$env{'user.domain'}; }
3209: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3210: my $uhome=&homeserver($uname,$udomain);
3211:
3212: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 3213: }
3214:
3215: # -------------------------------------------------------------- dump interface
3216:
3217: sub dump {
1.755 albertel 3218: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3219: if (!$udomain) { $udomain=$env{'user.domain'}; }
3220: if (!$uname) { $uname=$env{'user.name'}; }
3221: my $uhome=&homeserver($uname,$udomain);
3222: if ($regexp) {
3223: $regexp=&escape($regexp);
3224: } else {
3225: $regexp='.';
3226: }
3227: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3228: my @pairs=split(/\&/,$rep);
3229: my %returnhash=();
3230: foreach my $item (@pairs) {
3231: my ($key,$value)=split(/=/,$item,2);
3232: $key = &unescape($key);
3233: next if ($key =~ /^error: 2 /);
3234: $returnhash{$key}=&thaw_unescape($value);
3235: }
3236: return %returnhash;
1.407 www 3237: }
3238:
1.717 albertel 3239: # --------------------------------------------------------- dumpstore interface
3240:
3241: sub dumpstore {
3242: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 3243: if (!$udomain) { $udomain=$env{'user.domain'}; }
3244: if (!$uname) { $uname=$env{'user.name'}; }
3245: my $uhome=&homeserver($uname,$udomain);
3246: if ($regexp) {
3247: $regexp=&escape($regexp);
3248: } else {
3249: $regexp='.';
3250: }
3251: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3252: my @pairs=split(/\&/,$rep);
3253: my %returnhash=();
3254: foreach my $item (@pairs) {
3255: my ($key,$value)=split(/=/,$item,2);
3256: next if ($key =~ /^error: 2 /);
3257: $returnhash{$key}=&thaw_unescape($value);
3258: }
3259: return %returnhash;
1.717 albertel 3260: }
3261:
1.407 www 3262: # -------------------------------------------------------------- keys interface
3263:
3264: sub getkeys {
3265: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 3266: if (!$udomain) { $udomain=$env{'user.domain'}; }
3267: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 3268: my $uhome=&homeserver($uname,$udomain);
3269: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3270: my @keyarray=();
1.800 albertel 3271: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 3272: next if ($key =~ /^error: 2 /);
1.800 albertel 3273: push(@keyarray,&unescape($key));
1.407 www 3274: }
3275: return @keyarray;
1.318 matthew 3276: }
3277:
1.319 matthew 3278: # --------------------------------------------------------------- currentdump
3279: sub currentdump {
1.328 matthew 3280: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 3281: $courseid = $env{'request.course.id'} if (! defined($courseid));
3282: $sdom = $env{'user.domain'} if (! defined($sdom));
3283: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 3284: my $uhome = &homeserver($sname,$sdom);
3285: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 3286: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 3287: #
1.318 matthew 3288: my %returnhash=();
1.319 matthew 3289: #
3290: if ($rep eq "unknown_cmd") {
3291: # an old lond will not know currentdump
3292: # Do a dump and make it look like a currentdump
1.822 albertel 3293: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 3294: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3295: my %hash = @tmp;
3296: @tmp=();
1.424 matthew 3297: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 3298: } else {
3299: my @pairs=split(/\&/,$rep);
1.800 albertel 3300: foreach my $pair (@pairs) {
3301: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 3302: my ($symb,$param) = split(/:/,$key);
3303: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 3304: &thaw_unescape($value);
1.319 matthew 3305: }
1.191 harris41 3306: }
1.12 www 3307: return %returnhash;
1.424 matthew 3308: }
3309:
3310: sub convert_dump_to_currentdump{
3311: my %hash = %{shift()};
3312: my %returnhash;
3313: # Code ripped from lond, essentially. The only difference
3314: # here is the unescaping done by lonnet::dump(). Conceivably
3315: # we might run in to problems with parameter names =~ /^v\./
3316: while (my ($key,$value) = each(%hash)) {
3317: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 3318: $symb = &unescape($symb);
3319: $param = &unescape($param);
1.424 matthew 3320: next if ($v eq 'version' || $symb eq 'keys');
3321: next if (exists($returnhash{$symb}) &&
3322: exists($returnhash{$symb}->{$param}) &&
3323: $returnhash{$symb}->{'v.'.$param} > $v);
3324: $returnhash{$symb}->{$param}=$value;
3325: $returnhash{$symb}->{'v.'.$param}=$v;
3326: }
3327: #
3328: # Remove all of the keys in the hashes which keep track of
3329: # the version of the parameter.
3330: while (my ($symb,$param_hash) = each(%returnhash)) {
3331: # use a foreach because we are going to delete from the hash.
3332: foreach my $key (keys(%$param_hash)) {
3333: delete($param_hash->{$key}) if ($key =~ /^v\./);
3334: }
3335: }
3336: return \%returnhash;
1.12 www 3337: }
3338:
1.627 albertel 3339: # ------------------------------------------------------ critical inc interface
3340:
3341: sub cinc {
3342: return &inc(@_,'critical');
3343: }
3344:
1.449 matthew 3345: # --------------------------------------------------------------- inc interface
3346:
3347: sub inc {
1.627 albertel 3348: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 3349: if (!$udomain) { $udomain=$env{'user.domain'}; }
3350: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 3351: my $uhome=&homeserver($uname,$udomain);
3352: my $items='';
3353: if (! ref($store)) {
3354: # got a single value, so use that instead
3355: $items = &escape($store).'=&';
3356: } elsif (ref($store) eq 'SCALAR') {
3357: $items = &escape($$store).'=&';
3358: } elsif (ref($store) eq 'ARRAY') {
3359: $items = join('=&',map {&escape($_);} @{$store});
3360: } elsif (ref($store) eq 'HASH') {
3361: while (my($key,$value) = each(%{$store})) {
3362: $items.= &escape($key).'='.&escape($value).'&';
3363: }
3364: }
3365: $items=~s/\&$//;
1.627 albertel 3366: if ($critical) {
3367: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3368: } else {
3369: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3370: }
1.449 matthew 3371: }
3372:
1.12 www 3373: # --------------------------------------------------------------- put interface
3374:
3375: sub put {
1.134 albertel 3376: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3377: if (!$udomain) { $udomain=$env{'user.domain'}; }
3378: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3379: my $uhome=&homeserver($uname,$udomain);
1.12 www 3380: my $items='';
1.800 albertel 3381: foreach my $item (keys(%$storehash)) {
3382: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3383: }
1.12 www 3384: $items=~s/\&$//;
1.134 albertel 3385: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 3386: }
3387:
1.631 albertel 3388: # ------------------------------------------------------------ newput interface
3389:
3390: sub newput {
3391: my ($namespace,$storehash,$udomain,$uname)=@_;
3392: if (!$udomain) { $udomain=$env{'user.domain'}; }
3393: if (!$uname) { $uname=$env{'user.name'}; }
3394: my $uhome=&homeserver($uname,$udomain);
3395: my $items='';
3396: foreach my $key (keys(%$storehash)) {
3397: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3398: }
3399: $items=~s/\&$//;
3400: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
3401: }
3402:
3403: # --------------------------------------------------------- putstore interface
3404:
1.524 raeburn 3405: sub putstore {
1.715 albertel 3406: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 3407: if (!$udomain) { $udomain=$env{'user.domain'}; }
3408: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 3409: my $uhome=&homeserver($uname,$udomain);
3410: my $items='';
1.715 albertel 3411: foreach my $key (keys(%$storehash)) {
3412: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 3413: }
1.715 albertel 3414: $items=~s/\&$//;
1.716 albertel 3415: my $esc_symb=&escape($symb);
3416: my $esc_v=&escape($version);
1.715 albertel 3417: my $reply =
1.716 albertel 3418: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 3419: $uhome);
3420: if ($reply eq 'unknown_cmd') {
1.716 albertel 3421: # gfall back to way things use to be done
1.715 albertel 3422: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
3423: $uname);
1.524 raeburn 3424: }
1.715 albertel 3425: return $reply;
3426: }
3427:
3428: sub old_putstore {
1.716 albertel 3429: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
3430: if (!$udomain) { $udomain=$env{'user.domain'}; }
3431: if (!$uname) { $uname=$env{'user.name'}; }
3432: my $uhome=&homeserver($uname,$udomain);
3433: my %newstorehash;
1.800 albertel 3434: foreach my $item (keys(%$storehash)) {
3435: my $key = $version.':'.&escape($symb).':'.$item;
3436: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 3437: }
3438: my $items='';
3439: my %allitems = ();
1.800 albertel 3440: foreach my $item (keys(%newstorehash)) {
3441: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 3442: my $key = $1.':keys:'.$2;
3443: $allitems{$key} .= $3.':';
3444: }
1.800 albertel 3445: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 3446: }
1.800 albertel 3447: foreach my $item (keys(%allitems)) {
3448: $allitems{$item} =~ s/\:$//;
3449: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 3450: }
3451: $items=~s/\&$//;
3452: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 3453: }
3454:
1.47 www 3455: # ------------------------------------------------------ critical put interface
3456:
3457: sub cput {
1.134 albertel 3458: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 3459: if (!$udomain) { $udomain=$env{'user.domain'}; }
3460: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 3461: my $uhome=&homeserver($uname,$udomain);
1.47 www 3462: my $items='';
1.800 albertel 3463: foreach my $item (keys(%$storehash)) {
3464: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 3465: }
1.47 www 3466: $items=~s/\&$//;
1.134 albertel 3467: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3468: }
3469:
3470: # -------------------------------------------------------------- eget interface
3471:
3472: sub eget {
1.133 albertel 3473: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 3474: my $items='';
1.800 albertel 3475: foreach my $item (@$storearr) {
3476: $items.=&escape($item).'&';
1.191 harris41 3477: }
1.12 www 3478: $items=~s/\&$//;
1.620 albertel 3479: if (!$udomain) { $udomain=$env{'user.domain'}; }
3480: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 3481: my $uhome=&homeserver($uname,$udomain);
3482: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 3483: my @pairs=split(/\&/,$rep);
3484: my %returnhash=();
1.42 www 3485: my $i=0;
1.800 albertel 3486: foreach my $item (@$storearr) {
3487: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 3488: $i++;
1.191 harris41 3489: }
1.12 www 3490: return %returnhash;
3491: }
3492:
1.667 albertel 3493: # ------------------------------------------------------------ tmpput interface
3494: sub tmpput {
1.802 raeburn 3495: my ($storehash,$server,$context)=@_;
1.667 albertel 3496: my $items='';
1.800 albertel 3497: foreach my $item (keys(%$storehash)) {
3498: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 3499: }
3500: $items=~s/\&$//;
1.802 raeburn 3501: if (defined($context)) {
3502: $items .= ':'.&escape($context);
3503: }
1.667 albertel 3504: return &reply("tmpput:$items",$server);
3505: }
3506:
3507: # ------------------------------------------------------------ tmpget interface
3508: sub tmpget {
1.688 albertel 3509: my ($token,$server)=@_;
3510: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3511: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 3512: my %returnhash;
3513: foreach my $item (split(/\&/,$rep)) {
3514: my ($key,$value)=split(/=/,$item);
3515: $returnhash{&unescape($key)}=&thaw_unescape($value);
3516: }
3517: return %returnhash;
3518: }
3519:
1.688 albertel 3520: # ------------------------------------------------------------ tmpget interface
3521: sub tmpdel {
3522: my ($token,$server)=@_;
3523: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
3524: return &reply("tmpdel:$token",$server);
3525: }
3526:
1.765 albertel 3527: # -------------------------------------------------- portfolio access checking
3528:
3529: sub portfolio_access {
1.766 albertel 3530: my ($requrl) = @_;
1.765 albertel 3531: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
3532: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 3533: if ($result) {
3534: my %setters;
3535: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3536: my ($startblock,$endblock) =
3537: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
3538: if ($startblock && $endblock) {
3539: return 'B';
3540: }
3541: } else {
3542: my ($startblock,$endblock) =
3543: &Apache::loncommon::blockcheck(\%setters,'port');
3544: if ($startblock && $endblock) {
3545: return 'B';
3546: }
3547: }
3548: }
1.765 albertel 3549: if ($result eq 'ok') {
1.766 albertel 3550: return 'F';
1.765 albertel 3551: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 3552: return 'A';
1.765 albertel 3553: }
1.766 albertel 3554: return '';
1.765 albertel 3555: }
3556:
3557: sub get_portfolio_access {
1.767 albertel 3558: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
3559:
3560: if (!ref($access_hash)) {
3561: my $current_perms = &get_portfile_permissions($udom,$unum);
3562: my %access_controls = &get_access_controls($current_perms,$group,
3563: $file_name);
3564: $access_hash = $access_controls{$file_name};
3565: }
3566:
1.765 albertel 3567: my ($public,$guest,@domains,@users,@courses,@groups);
3568: my $now = time;
3569: if (ref($access_hash) eq 'HASH') {
3570: foreach my $key (keys(%{$access_hash})) {
3571: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
3572: if ($start > $now) {
3573: next;
3574: }
3575: if ($end && $end<$now) {
3576: next;
3577: }
3578: if ($scope eq 'public') {
3579: $public = $key;
3580: last;
3581: } elsif ($scope eq 'guest') {
3582: $guest = $key;
3583: } elsif ($scope eq 'domains') {
3584: push(@domains,$key);
3585: } elsif ($scope eq 'users') {
3586: push(@users,$key);
3587: } elsif ($scope eq 'course') {
3588: push(@courses,$key);
3589: } elsif ($scope eq 'group') {
3590: push(@groups,$key);
3591: }
3592: }
3593: if ($public) {
3594: return 'ok';
3595: }
3596: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
3597: if ($guest) {
3598: return $guest;
3599: }
3600: } else {
3601: if (@domains > 0) {
3602: foreach my $domkey (@domains) {
3603: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
3604: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
3605: return 'ok';
3606: }
3607: }
3608: }
3609: }
3610: if (@users > 0) {
3611: foreach my $userkey (@users) {
1.865 raeburn 3612: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
3613: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
3614: if (ref($item) eq 'HASH') {
3615: if (($item->{'uname'} eq $env{'user.name'}) &&
3616: ($item->{'udom'} eq $env{'user.domain'})) {
3617: return 'ok';
3618: }
3619: }
3620: }
3621: }
1.765 albertel 3622: }
3623: }
3624: my %roleshash;
3625: my @courses_and_groups = @courses;
3626: push(@courses_and_groups,@groups);
3627: if (@courses_and_groups > 0) {
3628: my (%allgroups,%allroles);
3629: my ($start,$end,$role,$sec,$group);
3630: foreach my $envkey (%env) {
1.811 albertel 3631: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3632: my $cid = $2.'_'.$3;
3633: if ($1 eq 'gr') {
3634: $group = $4;
3635: $allgroups{$cid}{$group} = $env{$envkey};
3636: } else {
3637: if ($4 eq '') {
3638: $sec = 'none';
3639: } else {
3640: $sec = $4;
3641: }
3642: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3643: }
1.811 albertel 3644: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 3645: my $cid = $2.'_'.$3;
3646: if ($4 eq '') {
3647: $sec = 'none';
3648: } else {
3649: $sec = $4;
3650: }
3651: $allroles{$cid}{$1}{$sec} = $env{$envkey};
3652: }
3653: }
3654: if (keys(%allroles) == 0) {
3655: return;
3656: }
3657: foreach my $key (@courses_and_groups) {
3658: my %content = %{$$access_hash{$key}};
3659: my $cnum = $content{'number'};
3660: my $cdom = $content{'domain'};
3661: my $cid = $cdom.'_'.$cnum;
3662: if (!exists($allroles{$cid})) {
3663: next;
3664: }
3665: foreach my $role_id (keys(%{$content{'roles'}})) {
3666: my @sections = @{$content{'roles'}{$role_id}{'section'}};
3667: my @groups = @{$content{'roles'}{$role_id}{'group'}};
3668: my @status = @{$content{'roles'}{$role_id}{'access'}};
3669: my @roles = @{$content{'roles'}{$role_id}{'role'}};
3670: foreach my $role (keys(%{$allroles{$cid}})) {
3671: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
3672: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
3673: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
3674: if (grep/^all$/,@sections) {
3675: return 'ok';
3676: } else {
3677: if (grep/^$sec$/,@sections) {
3678: return 'ok';
3679: }
3680: }
3681: }
3682: }
3683: if (keys(%{$allgroups{$cid}}) == 0) {
3684: if (grep/^none$/,@groups) {
3685: return 'ok';
3686: }
3687: } else {
3688: if (grep/^all$/,@groups) {
3689: return 'ok';
3690: }
3691: foreach my $group (keys(%{$allgroups{$cid}})) {
3692: if (grep/^$group$/,@groups) {
3693: return 'ok';
3694: }
3695: }
3696: }
3697: }
3698: }
3699: }
3700: }
3701: }
3702: if ($guest) {
3703: return $guest;
3704: }
3705: }
3706: }
3707: return;
3708: }
3709:
3710: sub course_group_datechecker {
3711: my ($dates,$now,$status) = @_;
3712: my ($start,$end) = split(/\./,$dates);
3713: if (!$start && !$end) {
3714: return 'ok';
3715: }
3716: if (grep/^active$/,@{$status}) {
3717: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
3718: return 'ok';
3719: }
3720: }
3721: if (grep/^previous$/,@{$status}) {
3722: if ($end > $now ) {
3723: return 'ok';
3724: }
3725: }
3726: if (grep/^future$/,@{$status}) {
3727: if ($start > $now) {
3728: return 'ok';
3729: }
3730: }
3731: return;
3732: }
3733:
3734: sub parse_portfolio_url {
3735: my ($url) = @_;
3736:
3737: my ($type,$udom,$unum,$group,$file_name);
3738:
1.823 albertel 3739: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 3740: $type = 1;
3741: $udom = $1;
3742: $unum = $2;
3743: $file_name = $3;
1.823 albertel 3744: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 3745: $type = 2;
3746: $udom = $1;
3747: $unum = $2;
3748: $group = $3;
3749: $file_name = $3.'/'.$4;
3750: }
3751: if (wantarray) {
3752: return ($type,$udom,$unum,$file_name,$group);
3753: }
3754: return $type;
3755: }
3756:
3757: sub is_portfolio_url {
3758: my ($url) = @_;
3759: return scalar(&parse_portfolio_url($url));
3760: }
3761:
1.798 raeburn 3762: sub is_portfolio_file {
3763: my ($file) = @_;
1.820 raeburn 3764: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 3765: return 1;
3766: }
3767: return;
3768: }
3769:
3770:
1.341 www 3771: # ---------------------------------------------- Custom access rule evaluation
3772:
3773: sub customaccess {
3774: my ($priv,$uri)=@_;
1.807 albertel 3775: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 3776: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 3777: $udom = &LONCAPA::clean_domain($udom);
3778: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 3779: my $access=0;
1.800 albertel 3780: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
3781: my ($effect,$realm,$role)=split(/\:/,$right);
1.343 www 3782: if ($role) {
3783: if ($role ne $urole) { next; }
3784: }
1.800 albertel 3785: foreach my $scope (split(/\s*\,\s*/,$realm)) {
3786: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343 www 3787: if ($tdom) {
3788: if ($tdom ne $udom) { next; }
3789: }
3790: if ($tcrs) {
3791: if ($tcrs ne $ucrs) { next; }
3792: }
3793: if ($tsec) {
3794: if ($tsec ne $usec) { next; }
3795: }
3796: $access=($effect eq 'allow');
3797: last;
1.342 www 3798: }
1.402 bowersj2 3799: if ($realm eq '' && $role eq '') {
3800: $access=($effect eq 'allow');
3801: }
1.341 www 3802: }
3803: return $access;
3804: }
3805:
1.103 harris41 3806: # ------------------------------------------------- Check for a user privilege
1.12 www 3807:
3808: sub allowed {
1.810 raeburn 3809: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 3810: my $ver_orguri=$uri;
1.439 www 3811: $uri=&deversion($uri);
1.152 www 3812: my $orguri=$uri;
1.52 www 3813: $uri=&declutter($uri);
1.809 raeburn 3814:
1.810 raeburn 3815: if ($priv eq 'evb') {
3816: # Evade communication block restrictions for specified role in a course
3817: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
3818: return $1;
3819: } else {
3820: return;
3821: }
3822: }
3823:
1.620 albertel 3824: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 3825: # Free bre access to adm and meta resources
1.775 albertel 3826: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 3827: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
3828: && ($priv eq 'bre')) {
1.14 www 3829: return 'F';
1.159 www 3830: }
3831:
1.545 banghart 3832: # Free bre access to user's own portfolio contents
1.714 raeburn 3833: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 3834: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 3835: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 3836: my %setters;
3837: my ($startblock,$endblock) =
3838: &Apache::loncommon::blockcheck(\%setters,'port');
3839: if ($startblock && $endblock) {
3840: return 'B';
3841: } else {
3842: return 'F';
3843: }
1.545 banghart 3844: }
3845:
1.762 raeburn 3846: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 3847: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
3848: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
3849: if (exists($env{'request.course.id'})) {
3850: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3851: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3852: if (($domain eq $cdom) && ($name eq $cnum)) {
3853: my $courseprivid=$env{'request.course.id'};
3854: $courseprivid=~s/\_/\//;
3855: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
3856: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
3857: return $1;
1.762 raeburn 3858: } else {
3859: if ($env{'request.course.sec'}) {
3860: $courseprivid.='/'.$env{'request.course.sec'};
3861: }
3862: if ($env{'user.priv.'.$env{'request.role'}.'./'.
3863: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
3864: return $2;
3865: }
1.714 raeburn 3866: }
3867: }
3868: }
3869: }
3870:
1.159 www 3871: # Free bre to public access
3872:
3873: if ($priv eq 'bre') {
1.238 www 3874: my $copyright=&metadata($uri,'copyright');
1.620 albertel 3875: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 3876: return 'F';
3877: }
1.238 www 3878: if ($copyright eq 'priv') {
3879: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3880: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 3881: return '';
3882: }
3883: }
3884: if ($copyright eq 'domain') {
3885: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 3886: unless (($env{'user.domain'} eq $1) ||
3887: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 3888: return '';
3889: }
1.262 matthew 3890: }
1.620 albertel 3891: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 3892: # Library role, so allow browsing of resources in this domain.
3893: return 'F';
1.238 www 3894: }
1.341 www 3895: if ($copyright eq 'custom') {
3896: unless (&customaccess($priv,$uri)) { return ''; }
3897: }
1.14 www 3898: }
1.264 matthew 3899: # Domain coordinator is trying to create a course
1.620 albertel 3900: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 3901: # uri is the requested domain in this case.
3902: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 3903: # a role of dc for the domain in question.
1.620 albertel 3904: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 3905: }
1.29 www 3906:
1.52 www 3907: my $thisallowed='';
3908: my $statecond=0;
3909: my $courseprivid='';
3910:
3911: # Course
3912:
1.620 albertel 3913: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52 www 3914: $thisallowed.=$1;
3915: }
1.29 www 3916:
1.52 www 3917: # Domain
3918:
1.620 albertel 3919: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 3920: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3921: $thisallowed.=$1;
3922: }
1.52 www 3923:
3924: # Course: uri itself is a course
1.66 www 3925: my $courseuri=$uri;
3926: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 3927: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 3928:
1.620 albertel 3929: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 3930: =~/\Q$priv\E\&([^\:]*)/) {
1.12 www 3931: $thisallowed.=$1;
3932: }
1.29 www 3933:
1.665 albertel 3934: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 3935: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 3936: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 3937: $thisallowed='';
1.671 raeburn 3938: my ($match)=&is_on_map($uri);
3939: if ($match) {
3940: if ($env{'user.priv.'.$env{'request.role'}.'./'}
3941: =~/\Q$priv\E\&([^\:]*)/) {
3942: $thisallowed.=$1;
3943: }
3944: } else {
1.705 albertel 3945: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 3946: if ($refuri) {
3947: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 3948: $thisallowed='F';
1.671 raeburn 3949: } else {
3950: $refuri=&declutter($refuri);
3951: my ($match) = &is_on_map($refuri);
3952: if ($match) {
3953: $thisallowed='F';
3954: }
1.669 raeburn 3955: }
1.671 raeburn 3956: }
3957: }
1.314 www 3958: }
1.492 albertel 3959:
1.766 albertel 3960: if ($priv eq 'bre'
3961: && $thisallowed ne 'F'
3962: && $thisallowed ne '2'
3963: && &is_portfolio_url($uri)) {
3964: $thisallowed = &portfolio_access($uri);
3965: }
3966:
1.52 www 3967: # Full access at system, domain or course-wide level? Exit.
1.29 www 3968:
3969: if ($thisallowed=~/F/) {
3970: return 'F';
3971: }
3972:
1.52 www 3973: # If this is generating or modifying users, exit with special codes
1.29 www 3974:
1.643 www 3975: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
3976: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 3977: my ($audom,$auname)=split('/',$uri);
1.643 www 3978: # no author name given, so this just checks on the general right to make a co-author in this domain
3979: unless ($auname) { return $thisallowed; }
3980: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 3981: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
3982: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
3983: ($audom ne $env{'request.role.domain'}))) { return ''; }
3984: }
1.52 www 3985: return $thisallowed;
3986: }
3987: #
1.103 harris41 3988: # Gathered so far: system, domain and course wide privileges
1.52 www 3989: #
3990: # Course: See if uri or referer is an individual resource that is part of
3991: # the course
3992:
1.620 albertel 3993: if ($env{'request.course.id'}) {
1.232 www 3994:
1.620 albertel 3995: $courseprivid=$env{'request.course.id'};
3996: if ($env{'request.course.sec'}) {
3997: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 3998: }
3999: $courseprivid=~s/\_/\//;
4000: my $checkreferer=1;
1.232 www 4001: my ($match,$cond)=&is_on_map($uri);
4002: if ($match) {
4003: $statecond=$cond;
1.620 albertel 4004: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4005: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4006: $thisallowed.=$1;
4007: $checkreferer=0;
4008: }
1.29 www 4009: }
1.83 www 4010:
1.148 www 4011: if ($checkreferer) {
1.620 albertel 4012: my $refuri=$env{'httpref.'.$orguri};
1.148 www 4013: unless ($refuri) {
1.800 albertel 4014: foreach my $key (keys(%env)) {
4015: if ($key=~/^httpref\..*\*/) {
4016: my $pattern=$key;
1.156 www 4017: $pattern=~s/^httpref\.\/res\///;
1.148 www 4018: $pattern=~s/\*/\[\^\/\]\+/g;
4019: $pattern=~s/\//\\\//g;
1.152 www 4020: if ($orguri=~/$pattern/) {
1.800 albertel 4021: $refuri=$env{$key};
1.148 www 4022: }
4023: }
1.191 harris41 4024: }
1.148 www 4025: }
1.232 www 4026:
1.148 www 4027: if ($refuri) {
1.152 www 4028: $refuri=&declutter($refuri);
1.232 www 4029: my ($match,$cond)=&is_on_map($refuri);
4030: if ($match) {
4031: my $refstatecond=$cond;
1.620 albertel 4032: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 4033: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 4034: $thisallowed.=$1;
1.53 www 4035: $uri=$refuri;
4036: $statecond=$refstatecond;
1.52 www 4037: }
4038: }
1.148 www 4039: }
1.29 www 4040: }
1.52 www 4041: }
1.29 www 4042:
1.52 www 4043: #
1.103 harris41 4044: # Gathered now: all privileges that could apply, and condition number
1.52 www 4045: #
4046: #
4047: # Full or no access?
4048: #
1.29 www 4049:
1.52 www 4050: if ($thisallowed=~/F/) {
4051: return 'F';
4052: }
1.29 www 4053:
1.52 www 4054: unless ($thisallowed) {
4055: return '';
4056: }
1.29 www 4057:
1.52 www 4058: # Restrictions exist, deal with them
4059: #
4060: # C:according to course preferences
4061: # R:according to resource settings
4062: # L:unless locked
4063: # X:according to user session state
4064: #
4065:
4066: # Possibly locked functionality, check all courses
1.54 www 4067: # Locks might take effect only after 10 minutes cache expiration for other
4068: # courses, and 2 minutes for current course
1.52 www 4069:
4070: my $envkey;
4071: if ($thisallowed=~/L/) {
1.620 albertel 4072: foreach $envkey (keys %env) {
1.54 www 4073: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4074: my $courseid=$2;
4075: my $roleid=$1.'.'.$2;
1.92 www 4076: $courseid=~s/^\///;
1.54 www 4077: my $expiretime=600;
1.620 albertel 4078: if ($env{'request.role'} eq $roleid) {
1.54 www 4079: $expiretime=120;
4080: }
4081: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4082: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 4083: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 4084: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 4085: }
1.620 albertel 4086: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4087: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4088: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4089: &log($env{'user.domain'},$env{'user.name'},
4090: $env{'user.home'},
1.57 www 4091: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 4092: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4093: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4094: return '';
4095: }
4096: }
1.620 albertel 4097: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4098: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4099: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4100: &log($env{'user.domain'},$env{'user.name'},
4101: $env{'user.home'},
1.57 www 4102: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 4103: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 4104: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 4105: return '';
4106: }
4107: }
4108: }
1.29 www 4109: }
1.52 www 4110: }
4111:
4112: #
4113: # Rest of the restrictions depend on selected course
4114: #
4115:
1.620 albertel 4116: unless ($env{'request.course.id'}) {
1.766 albertel 4117: if ($thisallowed eq 'A') {
4118: return 'A';
1.814 raeburn 4119: } elsif ($thisallowed eq 'B') {
4120: return 'B';
1.766 albertel 4121: } else {
4122: return '1';
4123: }
1.52 www 4124: }
1.29 www 4125:
1.52 www 4126: #
4127: # Now user is definitely in a course
4128: #
1.53 www 4129:
4130:
4131: # Course preferences
4132:
4133: if ($thisallowed=~/C/) {
1.620 albertel 4134: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4135: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4136: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 4137: =~/\Q$rolecode\E/) {
1.689 albertel 4138: if ($priv ne 'pch') {
4139: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4140: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4141: $env{'request.course.id'});
4142: }
1.237 www 4143: return '';
4144: }
4145:
1.620 albertel 4146: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 4147: =~/\Q$unamedom\E/) {
1.689 albertel 4148: if ($priv ne 'pch') {
4149: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4150: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4151: $env{'request.course.id'});
4152: }
1.54 www 4153: return '';
4154: }
1.53 www 4155: }
4156:
4157: # Resource preferences
4158:
4159: if ($thisallowed=~/R/) {
1.620 albertel 4160: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 4161: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689 albertel 4162: if ($priv ne 'pch') {
4163: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4164: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4165: }
4166: return '';
1.54 www 4167: }
1.53 www 4168: }
1.30 www 4169:
1.246 www 4170: # Restricted by state or randomout?
1.30 www 4171:
1.52 www 4172: if ($thisallowed=~/X/) {
1.620 albertel 4173: if ($env{'acc.randomout'}) {
1.579 albertel 4174: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 4175: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 4176: return '';
4177: }
1.247 www 4178: }
4179: if (&condval($statecond)) {
1.52 www 4180: return '2';
4181: } else {
4182: return '';
4183: }
4184: }
1.30 www 4185:
1.766 albertel 4186: if ($thisallowed eq 'A') {
4187: return 'A';
1.814 raeburn 4188: } elsif ($thisallowed eq 'B') {
4189: return 'B';
1.766 albertel 4190: }
1.52 www 4191: return 'F';
1.232 www 4192: }
4193:
1.710 albertel 4194: sub split_uri_for_cond {
4195: my $uri=&deversion(&declutter(shift));
4196: my @uriparts=split(/\//,$uri);
4197: my $filename=pop(@uriparts);
4198: my $pathname=join('/',@uriparts);
4199: return ($pathname,$filename);
4200: }
1.232 www 4201: # --------------------------------------------------- Is a resource on the map?
4202:
4203: sub is_on_map {
1.710 albertel 4204: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 4205: #Trying to find the conditional for the file
1.620 albertel 4206: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 4207: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 4208: if ($match) {
1.289 bowersj2 4209: return (1,$1);
4210: } else {
1.434 www 4211: return (0,0);
1.289 bowersj2 4212: }
1.12 www 4213: }
4214:
1.427 www 4215: # --------------------------------------------------------- Get symb from alias
4216:
4217: sub get_symb_from_alias {
4218: my $symb=shift;
4219: my ($map,$resid,$url)=&decode_symb($symb);
4220: # Already is a symb
4221: if ($url) { return $symb; }
4222: # Must be an alias
4223: my $aliassymb='';
4224: my %bighash;
1.620 albertel 4225: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 4226: &GDBM_READER(),0640)) {
4227: my $rid=$bighash{'mapalias_'.$symb};
4228: if ($rid) {
4229: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 4230: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4231: $resid,$bighash{'src_'.$rid});
1.427 www 4232: }
4233: untie %bighash;
4234: }
4235: return $aliassymb;
4236: }
4237:
1.12 www 4238: # ----------------------------------------------------------------- Define Role
4239:
4240: sub definerole {
4241: if (allowed('mcr','/')) {
4242: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 4243: foreach my $role (split(':',$sysrole)) {
4244: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4245: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4246: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4247: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4248: return "refused:s:$crole&$cqual";
4249: }
4250: }
1.191 harris41 4251: }
1.800 albertel 4252: foreach my $role (split(':',$domrole)) {
4253: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4254: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4255: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4256: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 4257: return "refused:d:$crole&$cqual";
4258: }
4259: }
1.191 harris41 4260: }
1.800 albertel 4261: foreach my $role (split(':',$courole)) {
4262: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 4263: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
4264: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
4265: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 4266: return "refused:c:$crole&$cqual";
4267: }
4268: }
1.191 harris41 4269: }
1.620 albertel 4270: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
4271: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4272: "rolesdef_$rolename=".
4273: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 4274: return reply($command,$env{'user.home'});
1.12 www 4275: } else {
4276: return 'refused';
4277: }
1.105 harris41 4278: }
4279:
4280: # ---------------- Make a metadata query against the network of library servers
4281:
4282: sub metadata_query {
1.244 matthew 4283: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 4284: my %rhash;
1.845 albertel 4285: my %libserv = &all_library();
1.244 matthew 4286: my @server_list = (defined($server_array) ? @$server_array
4287: : keys(%libserv) );
4288: for my $server (@server_list) {
1.118 harris41 4289: unless ($custom or $customshow) {
4290: my $reply=&reply("querysend:".&escape($query),$server);
4291: $rhash{$server}=$reply;
4292: }
4293: else {
4294: my $reply=&reply("querysend:".&escape($query).':'.
4295: &escape($custom).':'.&escape($customshow),
4296: $server);
4297: $rhash{$server}=$reply;
4298: }
1.112 harris41 4299: }
1.118 harris41 4300: return \%rhash;
1.240 www 4301: }
4302:
4303: # ----------------------------------------- Send log queries and wait for reply
4304:
4305: sub log_query {
4306: my ($uname,$udom,$query,%filters)=@_;
4307: my $uhome=&homeserver($uname,$udom);
4308: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 4309: my $uhost=&hostname($uhome);
1.800 albertel 4310: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 4311: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
4312: $uhome);
1.479 albertel 4313: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 4314: return get_query_reply($queryid);
4315: }
4316:
1.818 raeburn 4317: # -------------------------- Update MySQL table for portfolio file
4318:
4319: sub update_portfolio_table {
1.821 raeburn 4320: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818 raeburn 4321: my $homeserver = &homeserver($uname,$udom);
4322: my $queryid=
1.821 raeburn 4323: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
4324: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 4325: my $reply = &get_query_reply($queryid);
4326: return $reply;
4327: }
4328:
1.508 raeburn 4329: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 4330:
4331: sub fetch_enrollment_query {
1.511 raeburn 4332: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 4333: my $homeserver;
1.547 raeburn 4334: my $maxtries = 1;
1.508 raeburn 4335: if ($context eq 'automated') {
4336: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 4337: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 4338: } else {
4339: $homeserver = &homeserver($cnum,$dom);
4340: }
1.838 albertel 4341: my $host=&hostname($homeserver);
1.506 raeburn 4342: my $cmd = '';
1.800 albertel 4343: foreach my $affiliate (keys %{$affiliatesref}) {
4344: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 4345: }
4346: $cmd =~ s/%%$//;
4347: $cmd = &escape($cmd);
4348: my $query = 'fetchenrollment';
1.620 albertel 4349: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 4350: unless ($queryid=~/^\Q$host\E\_/) {
4351: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
4352: return 'error: '.$queryid;
4353: }
1.506 raeburn 4354: my $reply = &get_query_reply($queryid);
1.547 raeburn 4355: my $tries = 1;
4356: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4357: $reply = &get_query_reply($queryid);
4358: $tries ++;
4359: }
1.526 raeburn 4360: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 4361: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 4362: } else {
1.515 raeburn 4363: my @responses = split/:/,$reply;
4364: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 4365: foreach my $line (@responses) {
4366: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 4367: $$replyref{$key} = $value;
4368: }
4369: } else {
1.506 raeburn 4370: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800 albertel 4371: foreach my $line (@responses) {
4372: my ($key,$value) = split(/=/,$line);
1.506 raeburn 4373: $$replyref{$key} = $value;
4374: if ($value > 0) {
1.800 albertel 4375: foreach my $item (@{$$affiliatesref{$key}}) {
4376: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 4377: my $destname = $pathname.'/'.$filename;
4378: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 4379: if ($xml_classlist =~ /^error/) {
4380: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
4381: } else {
1.506 raeburn 4382: if ( open(FILE,">$destname") ) {
4383: print FILE &unescape($xml_classlist);
4384: close(FILE);
1.526 raeburn 4385: } else {
4386: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 4387: }
4388: }
4389: }
4390: }
4391: }
4392: }
4393: return 'ok';
4394: }
4395: return 'error';
4396: }
4397:
1.242 www 4398: sub get_query_reply {
4399: my $queryid=shift;
1.240 www 4400: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
4401: my $reply='';
4402: for (1..100) {
4403: sleep 2;
4404: if (-e $replyfile.'.end') {
1.448 albertel 4405: if (open(my $fh,$replyfile)) {
1.240 www 4406: $reply.=<$fh>;
1.448 albertel 4407: close($fh);
1.240 www 4408: } else { return 'error: reply_file_error'; }
1.242 www 4409: return &unescape($reply);
4410: }
1.240 www 4411: }
1.242 www 4412: return 'timeout:'.$queryid;
1.240 www 4413: }
4414:
4415: sub courselog_query {
1.241 www 4416: #
4417: # possible filters:
4418: # url: url or symb
4419: # username
4420: # domain
4421: # action: view, submit, grade
4422: # start: timestamp
4423: # end: timestamp
4424: #
1.240 www 4425: my (%filters)=@_;
1.620 albertel 4426: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 4427: if ($filters{'url'}) {
4428: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
4429: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
4430: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
4431: }
1.620 albertel 4432: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
4433: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 4434: return &log_query($cname,$cdom,'courselog',%filters);
4435: }
4436:
4437: sub userlog_query {
1.858 raeburn 4438: #
4439: # possible filters:
4440: # action: log check role
4441: # start: timestamp
4442: # end: timestamp
4443: #
1.240 www 4444: my ($uname,$udom,%filters)=@_;
4445: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 4446: }
4447:
1.506 raeburn 4448: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
4449:
4450: sub auto_run {
1.508 raeburn 4451: my ($cnum,$cdom) = @_;
4452: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4453: my $response = &reply('autorun:'.$cdom,$homeserver);
1.506 raeburn 4454: return $response;
4455: }
1.776 albertel 4456:
1.506 raeburn 4457: sub auto_get_sections {
1.508 raeburn 4458: my ($cnum,$cdom,$inst_coursecode) = @_;
4459: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4460: my @secs = ();
1.511 raeburn 4461: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506 raeburn 4462: unless ($response eq 'refused') {
4463: @secs = split/:/,$response;
4464: }
4465: return @secs;
4466: }
1.776 albertel 4467:
1.506 raeburn 4468: sub auto_new_course {
1.508 raeburn 4469: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
4470: my $homeserver = &homeserver($cnum,$cdom);
1.515 raeburn 4471: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506 raeburn 4472: return $response;
4473: }
1.776 albertel 4474:
1.506 raeburn 4475: sub auto_validate_courseID {
1.508 raeburn 4476: my ($cnum,$cdom,$inst_course_id) = @_;
4477: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 4478: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 4479: return $response;
4480: }
1.776 albertel 4481:
1.506 raeburn 4482: sub auto_create_password {
1.508 raeburn 4483: my ($cnum,$cdom,$authparam) = @_;
4484: my $homeserver = &homeserver($cnum,$cdom);
1.506 raeburn 4485: my $create_passwd = 0;
4486: my $authchk = '';
1.511 raeburn 4487: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506 raeburn 4488: if ($response eq 'refused') {
4489: $authchk = 'refused';
4490: } else {
4491: ($authparam,$create_passwd,$authchk) = split/:/,$response;
4492: }
4493: return ($authparam,$create_passwd,$authchk);
4494: }
4495:
1.706 raeburn 4496: sub auto_photo_permission {
4497: my ($cnum,$cdom,$students) = @_;
4498: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 4499: my ($outcome,$perm_reqd,$conditions) =
4500: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 4501: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4502: return (undef,undef);
4503: }
1.706 raeburn 4504: return ($outcome,$perm_reqd,$conditions);
4505: }
4506:
4507: sub auto_checkphotos {
4508: my ($uname,$udom,$pid) = @_;
4509: my $homeserver = &homeserver($uname,$udom);
4510: my ($result,$resulttype);
4511: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 4512: &escape($uname).':'.&escape($pid),
4513: $homeserver));
1.709 albertel 4514: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4515: return (undef,undef);
4516: }
1.706 raeburn 4517: if ($outcome) {
4518: ($result,$resulttype) = split(/:/,$outcome);
4519: }
4520: return ($result,$resulttype);
4521: }
4522:
4523: sub auto_photochoice {
4524: my ($cnum,$cdom) = @_;
4525: my $homeserver = &homeserver($cnum,$cdom);
4526: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 4527: &escape($cdom),
4528: $homeserver)));
1.709 albertel 4529: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
4530: return (undef,undef);
4531: }
1.706 raeburn 4532: return ($update,$comment);
4533: }
4534:
4535: sub auto_photoupdate {
4536: my ($affiliatesref,$dom,$cnum,$photo) = @_;
4537: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 4538: my $host=&hostname($homeserver);
1.706 raeburn 4539: my $cmd = '';
4540: my $maxtries = 1;
1.800 albertel 4541: foreach my $affiliate (keys(%{$affiliatesref})) {
4542: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 4543: }
4544: $cmd =~ s/%%$//;
4545: $cmd = &escape($cmd);
4546: my $query = 'institutionalphotos';
4547: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
4548: unless ($queryid=~/^\Q$host\E\_/) {
4549: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
4550: return 'error: '.$queryid;
4551: }
4552: my $reply = &get_query_reply($queryid);
4553: my $tries = 1;
4554: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
4555: $reply = &get_query_reply($queryid);
4556: $tries ++;
4557: }
4558: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
4559: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
4560: } else {
4561: my @responses = split(/:/,$reply);
4562: my $outcome = shift(@responses);
4563: foreach my $item (@responses) {
4564: my ($key,$value) = split(/=/,$item);
4565: $$photo{$key} = $value;
4566: }
4567: return $outcome;
4568: }
4569: return 'error';
4570: }
4571:
1.521 raeburn 4572: sub auto_instcode_format {
1.793 albertel 4573: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
4574: $cat_order) = @_;
1.521 raeburn 4575: my $courses = '';
1.772 raeburn 4576: my @homeservers;
1.521 raeburn 4577: if ($caller eq 'global') {
1.841 albertel 4578: my %servers = &get_servers($codedom,'library');
4579: foreach my $tryserver (keys(%servers)) {
4580: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4581: push(@homeservers,$tryserver);
4582: }
1.584 raeburn 4583: }
1.521 raeburn 4584: } else {
1.772 raeburn 4585: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 4586: }
1.793 albertel 4587: foreach my $code (keys(%{$instcodes})) {
4588: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 4589: }
4590: chop($courses);
1.772 raeburn 4591: my $ok_response = 0;
4592: my $response;
4593: while (@homeservers > 0 && $ok_response == 0) {
4594: my $server = shift(@homeservers);
4595: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
4596: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
4597: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.793 albertel 4598: split/:/,$response;
1.772 raeburn 4599: %{$codes} = (%{$codes},&str2hash($codes_str));
4600: push(@{$codetitles},&str2array($codetitles_str));
4601: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
4602: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
4603: $ok_response = 1;
4604: }
4605: }
4606: if ($ok_response) {
1.521 raeburn 4607: return 'ok';
1.772 raeburn 4608: } else {
4609: return $response;
1.521 raeburn 4610: }
4611: }
4612:
1.792 raeburn 4613: sub auto_instcode_defaults {
4614: my ($domain,$returnhash,$code_order) = @_;
4615: my @homeservers;
1.841 albertel 4616:
4617: my %servers = &get_servers($domain,'library');
4618: foreach my $tryserver (keys(%servers)) {
4619: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
4620: push(@homeservers,$tryserver);
4621: }
1.792 raeburn 4622: }
1.841 albertel 4623:
1.792 raeburn 4624: my $response;
1.841 albertel 4625: foreach my $server (@homeservers) {
1.792 raeburn 4626: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 4627: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
4628:
4629: foreach my $pair (split(/\&/,$response)) {
4630: my ($name,$value)=split(/\=/,$pair);
4631: if ($name eq 'code_order') {
4632: @{$code_order} = split(/\&/,&unescape($value));
4633: } else {
4634: $returnhash->{&unescape($name)}=&unescape($value);
4635: }
4636: }
4637: return 'ok';
1.792 raeburn 4638: }
1.841 albertel 4639:
4640: return $response;
1.792 raeburn 4641: }
4642:
1.777 albertel 4643: sub auto_validate_class_sec {
1.773 raeburn 4644: my ($cdom,$cnum,$owner,$inst_class) = @_;
4645: my $homeserver = &homeserver($cnum,$cdom);
4646: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774 banghart 4647: &escape($owner).':'.$cdom,$homeserver);
1.773 raeburn 4648: return $response;
4649: }
4650:
1.679 raeburn 4651: # ------------------------------------------------------- Course Group routines
4652:
4653: sub get_coursegroups {
1.809 raeburn 4654: my ($cdom,$cnum,$group,$namespace) = @_;
4655: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 4656: }
4657:
1.679 raeburn 4658: sub modify_coursegroup {
4659: my ($cdom,$cnum,$groupsettings) = @_;
4660: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
4661: }
4662:
1.809 raeburn 4663: sub toggle_coursegroup_status {
4664: my ($cdom,$cnum,$group,$action) = @_;
4665: my ($from_namespace,$to_namespace);
4666: if ($action eq 'delete') {
4667: $from_namespace = 'coursegroups';
4668: $to_namespace = 'deleted_groups';
4669: } else {
4670: $from_namespace = 'deleted_groups';
4671: $to_namespace = 'coursegroups';
4672: }
4673: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 4674: if (my $tmp = &error(%curr_group)) {
4675: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
4676: return ('read error',$tmp);
4677: } else {
4678: my %savedsettings = %curr_group;
1.809 raeburn 4679: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 4680: my $deloutcome;
4681: if ($result eq 'ok') {
1.809 raeburn 4682: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 4683: } else {
4684: return ('write error',$result);
4685: }
4686: if ($deloutcome eq 'ok') {
4687: return 'ok';
4688: } else {
4689: return ('delete error',$deloutcome);
4690: }
4691: }
4692: }
4693:
1.679 raeburn 4694: sub modify_group_roles {
4695: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
4696: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
4697: my $role = 'gr/'.&escape($userprivs);
4698: my ($uname,$udom) = split(/:/,$user);
4699: my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684 raeburn 4700: if ($result eq 'ok') {
4701: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
4702: }
1.679 raeburn 4703: return $result;
4704: }
4705:
4706: sub modify_coursegroup_membership {
4707: my ($cdom,$cnum,$membership) = @_;
4708: my $result = &put('groupmembership',$membership,$cdom,$cnum);
4709: return $result;
4710: }
4711:
1.682 raeburn 4712: sub get_active_groups {
4713: my ($udom,$uname,$cdom,$cnum) = @_;
4714: my $now = time;
4715: my %groups = ();
4716: foreach my $key (keys(%env)) {
1.811 albertel 4717: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 4718: my ($start,$end) = split(/\./,$env{$key});
4719: if (($end!=0) && ($end<$now)) { next; }
4720: if (($start!=0) && ($start>$now)) { next; }
4721: if ($1 eq $cdom && $2 eq $cnum) {
4722: $groups{$3} = $env{$key} ;
4723: }
4724: }
4725: }
4726: return %groups;
4727: }
4728:
1.683 raeburn 4729: sub get_group_membership {
4730: my ($cdom,$cnum,$group) = @_;
4731: return(&dump('groupmembership',$cdom,$cnum,$group));
4732: }
4733:
4734: sub get_users_groups {
4735: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 4736: my @usersgroups;
1.683 raeburn 4737: my $cachetime=1800;
4738:
4739: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 4740: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
4741: if (defined($cached)) {
1.734 albertel 4742: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 4743: } else {
4744: $grouplist = '';
1.816 raeburn 4745: my $courseurl = &courseid_to_courseurl($courseid);
4746: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 4747: my $access_end = $env{'course.'.$courseid.
4748: '.default_enrollment_end_date'};
4749: my $now = time;
4750: foreach my $key (keys(%roleshash)) {
4751: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
4752: my $group = $1;
4753: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
4754: my $start = $2;
4755: my $end = $1;
4756: if ($start == -1) { next; } # deleted from group
4757: if (($start!=0) && ($start>$now)) { next; }
4758: if (($end!=0) && ($end<$now)) {
4759: if ($access_end && $access_end < $now) {
4760: if ($access_end - $end < 86400) {
4761: push(@usersgroups,$group);
1.733 raeburn 4762: }
4763: }
1.817 raeburn 4764: next;
1.733 raeburn 4765: }
1.817 raeburn 4766: push(@usersgroups,$group);
1.683 raeburn 4767: }
4768: }
4769: }
1.817 raeburn 4770: @usersgroups = &sort_course_groups($courseid,@usersgroups);
4771: $grouplist = join(':',@usersgroups);
4772: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 4773: }
1.733 raeburn 4774: return @usersgroups;
1.683 raeburn 4775: }
4776:
4777: sub devalidate_getgroups_cache {
4778: my ($udom,$uname,$cdom,$cnum)=@_;
4779: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 4780:
1.683 raeburn 4781: my $hashid="$udom:$uname:$courseid";
4782: &devalidate_cache_new('getgroups',$hashid);
4783: }
4784:
1.12 www 4785: # ------------------------------------------------------------------ Plain Text
4786:
4787: sub plaintext {
1.742 raeburn 4788: my ($short,$type,$cid) = @_;
1.758 albertel 4789: if ($short =~ /^cr/) {
4790: return (split('/',$short))[-1];
4791: }
1.742 raeburn 4792: if (!defined($cid)) {
4793: $cid = $env{'request.course.id'};
4794: }
4795: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
4796: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
4797: '.plaintext'});
4798: }
4799: my %rolenames = (
4800: Course => 'std',
4801: Group => 'alt1',
4802: );
4803: if (defined($type) &&
4804: defined($rolenames{$type}) &&
4805: defined($prp{$short}{$rolenames{$type}})) {
4806: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
4807: } else {
4808: return &Apache::lonlocal::mt($prp{$short}{'std'});
4809: }
1.12 www 4810: }
4811:
4812: # ----------------------------------------------------------------- Assign Role
4813:
4814: sub assignrole {
1.357 www 4815: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21 www 4816: my $mrole;
4817: if ($role =~ /^cr\//) {
1.393 www 4818: my $cwosec=$url;
1.811 albertel 4819: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 4820: unless (&allowed('ccr',$cwosec)) {
1.104 www 4821: &logthis('Refused custom assignrole: '.
4822: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4823: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4824: return 'refused';
4825: }
1.21 www 4826: $mrole='cr';
1.678 raeburn 4827: } elsif ($role =~ /^gr\//) {
4828: my $cwogrp=$url;
1.811 albertel 4829: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 4830: unless (&allowed('mdg',$cwogrp)) {
4831: &logthis('Refused group assignrole: '.
4832: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
4833: $env{'user.name'}.' at '.$env{'user.domain'});
4834: return 'refused';
4835: }
4836: $mrole='gr';
1.21 www 4837: } else {
1.82 www 4838: my $cwosec=$url;
1.811 albertel 4839: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373 www 4840: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) {
1.104 www 4841: &logthis('Refused assignrole: '.
4842: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620 albertel 4843: $env{'user.name'}.' at '.$env{'user.domain'});
1.104 www 4844: return 'refused';
4845: }
1.21 www 4846: $mrole=$role;
4847: }
1.620 albertel 4848: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 4849: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 4850: if ($end) { $command.='_'.$end; }
1.21 www 4851: if ($start) {
4852: if ($end) {
1.81 www 4853: $command.='_'.$start;
1.21 www 4854: } else {
1.81 www 4855: $command.='_0_'.$start;
1.21 www 4856: }
4857: }
1.739 raeburn 4858: my $origstart = $start;
4859: my $origend = $end;
1.357 www 4860: # actually delete
4861: if ($deleteflag) {
1.373 www 4862: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 4863: # modify command to delete the role
1.620 albertel 4864: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 4865: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 4866: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 4867: # set start and finish to negative values for userrolelog
4868: $start=-1;
4869: $end=-1;
4870: }
4871: }
4872: # send command
1.349 www 4873: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 4874: # log new user role if status is ok
1.349 www 4875: if ($answer eq 'ok') {
1.663 raeburn 4876: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 4877: # for course roles, perform group memberships changes triggered by role change.
4878: unless ($role =~ /^gr/) {
4879: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
4880: $origstart);
4881: }
1.349 www 4882: }
4883: return $answer;
1.169 harris41 4884: }
4885:
4886: # -------------------------------------------------- Modify user authentication
1.197 www 4887: # Overrides without validation
4888:
1.169 harris41 4889: sub modifyuserauth {
4890: my ($udom,$uname,$umode,$upass)=@_;
4891: my $uhome=&homeserver($uname,$udom);
1.197 www 4892: unless (&allowed('mau',$udom)) { return 'refused'; }
4893: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 4894: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4895: ' in domain '.$env{'request.role.domain'});
1.169 harris41 4896: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
4897: &escape($upass),$uhome);
1.620 albertel 4898: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 4899: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
4900: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
4901: &log($udom,,$uname,$uhome,
1.620 albertel 4902: 'Authentication changed by '.$env{'user.domain'}.', '.
4903: $env{'user.name'}.', '.$umode.
1.197 www 4904: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 4905: unless ($reply eq 'ok') {
1.197 www 4906: &logthis('Authentication mode error: '.$reply);
1.169 harris41 4907: return 'error: '.$reply;
4908: }
1.170 harris41 4909: return 'ok';
1.80 www 4910: }
4911:
1.81 www 4912: # --------------------------------------------------------------- Modify a user
1.80 www 4913:
1.81 www 4914: sub modifyuser {
1.206 matthew 4915: my ($udom, $uname, $uid,
4916: $umode, $upass, $first,
4917: $middle, $last, $gene,
1.387 www 4918: $forceid, $desiredhome, $email)=@_;
1.807 albertel 4919: $udom= &LONCAPA::clean_domain($udom);
4920: $uname=&LONCAPA::clean_username($uname);
1.81 www 4921: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 4922: $umode.', '.$first.', '.$middle.', '.
1.206 matthew 4923: $last.', '.$gene.'(forceid: '.$forceid.')'.
4924: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
4925: ' desiredhome not specified').
1.620 albertel 4926: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
4927: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 4928: my $uhome=&homeserver($uname,$udom,'true');
1.80 www 4929: # ----------------------------------------------------------------- Create User
1.406 albertel 4930: if (($uhome eq 'no_host') &&
4931: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 4932: my $unhome='';
1.844 albertel 4933: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 4934: $unhome = $desiredhome;
1.620 albertel 4935: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
4936: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 4937: } else { # load balancing routine for determining $unhome
1.81 www 4938: my $loadm=10000000;
1.841 albertel 4939: my %servers = &get_servers($udom,'library');
4940: foreach my $tryserver (keys(%servers)) {
4941: my $answer=reply('load',$tryserver);
4942: if (($answer=~/\d+/) && ($answer<$loadm)) {
4943: $loadm=$answer;
4944: $unhome=$tryserver;
4945: }
1.80 www 4946: }
4947: }
4948: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 4949: return 'error: unable to find a home server for '.$uname.
4950: ' in domain '.$udom;
1.80 www 4951: }
4952: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
4953: &escape($upass),$unhome);
4954: unless ($reply eq 'ok') {
4955: return 'error: '.$reply;
4956: }
1.230 stredwic 4957: $uhome=&homeserver($uname,$udom,'true');
1.80 www 4958: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 4959: return 'error: unable verify users home machine.';
1.80 www 4960: }
1.209 matthew 4961: } # End of creation of new user
1.80 www 4962: # ---------------------------------------------------------------------- Add ID
4963: if ($uid) {
4964: $uid=~tr/A-Z/a-z/;
4965: my %uidhash=&idrget($udom,$uname);
1.196 www 4966: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
4967: && (!$forceid)) {
1.80 www 4968: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 4969: return 'error: user id "'.$uid.'" does not match '.
4970: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 4971: }
4972: } else {
4973: &idput($udom,($uname => $uid));
4974: }
4975: }
4976: # -------------------------------------------------------------- Add names, etc
1.313 matthew 4977: my @tmp=&get('environment',
1.134 albertel 4978: ['firstname','middlename','lastname','generation'],
4979: $udom,$uname);
1.313 matthew 4980: my %names;
4981: if ($tmp[0] =~ m/^error:.*/) {
4982: %names=();
4983: } else {
4984: %names = @tmp;
4985: }
1.388 www 4986: #
4987: # Make sure to not trash student environment if instructor does not bother
4988: # to supply name and email information
4989: #
4990: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 4991: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 4992: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 4993: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 4994: if ($email) {
4995: $email=~s/[^\w\@\.\-\,]//gs;
4996: if ($email=~/\@/) { $names{'notification'} = $email;
4997: $names{'critnotification'} = $email;
4998: $names{'permanentemail'} = $email; }
4999: }
1.134 albertel 5000: my $reply = &put('environment', \%names, $udom,$uname);
5001: if ($reply ne 'ok') { return 'error: '.$reply; }
1.680 www 5002: &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81 www 5003: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 5004: $umode.', '.$first.', '.$middle.', '.
5005: $last.', '.$gene.' by '.
1.620 albertel 5006: $env{'user.name'}.' at '.$env{'user.domain'});
1.134 albertel 5007: return 'ok';
1.80 www 5008: }
5009:
1.81 www 5010: # -------------------------------------------------------------- Modify student
1.80 www 5011:
1.81 www 5012: sub modifystudent {
5013: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515 raeburn 5014: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455 albertel 5015: if (!$cid) {
1.620 albertel 5016: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5017: return 'not_in_class';
5018: }
1.80 www 5019: }
5020: # --------------------------------------------------------------- Make the user
1.81 www 5021: my $reply=&modifyuser
1.209 matthew 5022: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387 www 5023: $desiredhome,$email);
1.80 www 5024: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 5025: # This will cause &modify_student_enrollment to get the uid from the
5026: # students environment
5027: $uid = undef if (!$forceid);
1.455 albertel 5028: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515 raeburn 5029: $gene,$usec,$end,$start,$type,$locktype,$cid);
1.297 matthew 5030: return $reply;
5031: }
5032:
5033: sub modify_student_enrollment {
1.515 raeburn 5034: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455 albertel 5035: my ($cdom,$cnum,$chome);
5036: if (!$cid) {
1.620 albertel 5037: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 5038: return 'not_in_class';
5039: }
1.620 albertel 5040: $cdom=$env{'course.'.$cid.'.domain'};
5041: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 5042: } else {
5043: ($cdom,$cnum)=split(/_/,$cid);
5044: }
1.620 albertel 5045: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 5046: if (!$chome) {
1.457 raeburn 5047: $chome=&homeserver($cnum,$cdom);
1.297 matthew 5048: }
1.455 albertel 5049: if (!$chome) { return 'unknown_course'; }
1.297 matthew 5050: # Make sure the user exists
1.81 www 5051: my $uhome=&homeserver($uname,$udom);
5052: if (($uhome eq '') || ($uhome eq 'no_host')) {
5053: return 'error: no such user';
5054: }
1.297 matthew 5055: # Get student data if we were not given enough information
5056: if (!defined($first) || $first eq '' ||
5057: !defined($last) || $last eq '' ||
5058: !defined($uid) || $uid eq '' ||
5059: !defined($middle) || $middle eq '' ||
5060: !defined($gene) || $gene eq '') {
1.294 matthew 5061: # They did not supply us with enough data to enroll the student, so
5062: # we need to pick up more information.
1.297 matthew 5063: my %tmp = &get('environment',
1.294 matthew 5064: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 5065: ,$udom,$uname);
5066:
1.800 albertel 5067: #foreach my $key (keys(%tmp)) {
5068: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 5069: #}
1.294 matthew 5070: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5071: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5072: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 5073: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 5074: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5075: }
1.556 albertel 5076: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 5077: my $reply=cput('classlist',
5078: {"$uname:$udom" =>
1.515 raeburn 5079: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 5080: $cdom,$cnum);
1.81 www 5081: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5082: return 'error: '.$reply;
1.652 albertel 5083: } else {
5084: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 5085: }
1.297 matthew 5086: # Add student role to user
1.83 www 5087: my $uurl='/'.$cid;
1.81 www 5088: $uurl=~s/\_/\//g;
5089: if ($usec) {
5090: $uurl.='/'.$usec;
5091: }
5092: return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21 www 5093: }
5094:
1.556 albertel 5095: sub format_name {
5096: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5097: my $name;
5098: if ($first ne 'lastname') {
5099: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5100: } else {
5101: if ($lastname=~/\S/) {
5102: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5103: $name=~s/\s+,/,/;
5104: } else {
5105: $name.= $firstname.' '.$middlename.' '.$generation;
5106: }
5107: }
5108: $name=~s/^\s+//;
5109: $name=~s/\s+$//;
5110: $name=~s/\s+/ /g;
5111: return $name;
5112: }
5113:
1.84 www 5114: # ------------------------------------------------- Write to course preferences
5115:
5116: sub writecoursepref {
5117: my ($courseid,%prefs)=@_;
5118: $courseid=~s/^\///;
5119: $courseid=~s/\_/\//g;
5120: my ($cdomain,$cnum)=split(/\//,$courseid);
5121: my $chome=homeserver($cnum,$cdomain);
5122: if (($chome eq '') || ($chome eq 'no_host')) {
5123: return 'error: no such course';
5124: }
5125: my $cstring='';
1.800 albertel 5126: foreach my $pref (keys(%prefs)) {
5127: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 5128: }
1.84 www 5129: $cstring=~s/\&$//;
5130: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5131: }
5132:
5133: # ---------------------------------------------------------- Make/modify course
5134:
5135: sub createcourse {
1.741 raeburn 5136: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5137: $course_owner,$crstype)=@_;
1.84 www 5138: $url=&declutter($url);
5139: my $cid='';
1.264 matthew 5140: unless (&allowed('ccc',$udom)) {
1.84 www 5141: return 'refused';
5142: }
5143: # ------------------------------------------------------------------- Create ID
1.674 www 5144: my $uname=int(1+rand(9)).
5145: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5146: substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84 www 5147: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5148: # ----------------------------------------------- Make sure that does not exist
1.230 stredwic 5149: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 5150: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5151: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5152: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230 stredwic 5153: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5154: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5155: return 'error: unable to generate unique course-ID';
5156: }
5157: }
1.264 matthew 5158: # ------------------------------------------------ Check supplied server name
1.620 albertel 5159: $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845 albertel 5160: if (! &is_library($course_server)) {
1.264 matthew 5161: return 'error:bad server name '.$course_server;
5162: }
1.84 www 5163: # ------------------------------------------------------------- Make the course
5164: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 5165: $course_server);
1.84 www 5166: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230 stredwic 5167: $uhome=&homeserver($uname,$udom,'true');
1.84 www 5168: if (($uhome eq '') || ($uhome eq 'no_host')) {
5169: return 'error: no such course';
5170: }
1.271 www 5171: # ----------------------------------------------------------------- Course made
1.516 raeburn 5172: # log existence
5173: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741 raeburn 5174: ':'.&escape($inst_code).':'.&escape($course_owner).':'.
5175: &escape($crstype),$uhome);
1.358 www 5176: &flushcourselogs();
5177: # set toplevel url
1.271 www 5178: my $topurl=$url;
5179: unless ($nonstandard) {
5180: # ------------------------------------------ For standard courses, make top url
5181: my $mapurl=&clutter($url);
1.278 www 5182: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 5183: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 5184: <map>
5185: <resource id="1" type="start"></resource>
5186: <resource id="2" src="$mapurl"></resource>
5187: <resource id="3" type="finish"></resource>
5188: <link index="1" from="1" to="2"></link>
5189: <link index="2" from="2" to="3"></link>
5190: </map>
5191: ENDINITMAP
5192: $topurl=&declutter(
1.638 albertel 5193: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 5194: );
5195: }
5196: # ----------------------------------------------------------- Write preferences
1.84 www 5197: &writecoursepref($udom.'_'.$uname,
5198: ('description' => $description,
1.271 www 5199: 'url' => $topurl));
1.84 www 5200: return '/'.$udom.'/'.$uname;
5201: }
5202:
1.813 albertel 5203: sub is_course {
5204: my ($cdom,$cnum) = @_;
5205: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
5206: undef,'.');
5207: if (exists($courses{$cdom.'_'.$cnum})) {
5208: return 1;
5209: }
5210: return 0;
5211: }
5212:
1.21 www 5213: # ---------------------------------------------------------- Assign Custom Role
5214:
5215: sub assigncustomrole {
1.357 www 5216: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21 www 5217: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357 www 5218: $end,$start,$deleteflag);
1.21 www 5219: }
5220:
5221: # ----------------------------------------------------------------- Revoke Role
5222:
5223: sub revokerole {
1.357 www 5224: my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21 www 5225: my $now=time;
1.357 www 5226: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21 www 5227: }
5228:
5229: # ---------------------------------------------------------- Revoke Custom Role
5230:
5231: sub revokecustomrole {
1.357 www 5232: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21 www 5233: my $now=time;
1.357 www 5234: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
5235: $deleteflag);
1.17 www 5236: }
5237:
1.533 banghart 5238: # ------------------------------------------------------------ Disk usage
1.535 albertel 5239: sub diskusage {
1.533 banghart 5240: my ($udom,$uname,$directoryRoot)=@_;
5241: $directoryRoot =~ s/\/$//;
1.535 albertel 5242: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514 albertel 5243: return $listing;
1.512 banghart 5244: }
5245:
1.566 banghart 5246: sub is_locked {
5247: my ($file_name, $domain, $user) = @_;
5248: my @check;
5249: my $is_locked;
5250: push @check, $file_name;
1.613 albertel 5251: my %locked = &get('file_permissions',\@check,
1.620 albertel 5252: $env{'user.domain'},$env{'user.name'});
1.615 albertel 5253: my ($tmp)=keys(%locked);
5254: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 5255:
1.566 banghart 5256: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 5257: $is_locked = 'false';
5258: foreach my $entry (@{$locked{$file_name}}) {
5259: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 5260: $is_locked = 'true';
5261: last;
1.745 raeburn 5262: }
5263: }
1.566 banghart 5264: } else {
5265: $is_locked = 'false';
5266: }
5267: }
5268:
1.759 albertel 5269: sub declutter_portfile {
5270: my ($file) = @_;
1.833 albertel 5271: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 5272: return $file;
5273: }
5274:
1.559 banghart 5275: # ------------------------------------------------------------- Mark as Read Only
5276:
5277: sub mark_as_readonly {
5278: my ($domain,$user,$files,$what) = @_;
1.613 albertel 5279: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5280: my ($tmp)=keys(%current_permissions);
5281: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 5282: foreach my $file (@{$files}) {
1.759 albertel 5283: $file = &declutter_portfile($file);
1.561 banghart 5284: push(@{$current_permissions{$file}},$what);
1.559 banghart 5285: }
1.613 albertel 5286: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5287: return;
5288: }
5289:
1.572 banghart 5290: # ------------------------------------------------------------Save Selected Files
5291:
5292: sub save_selected_files {
5293: my ($user, $path, @files) = @_;
5294: my $filename = $user."savedfiles";
1.573 banghart 5295: my @other_files = &files_not_in_path($user, $path);
1.574 banghart 5296: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5297: foreach my $file (@files) {
1.620 albertel 5298: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 5299: }
5300: foreach my $file (@other_files) {
1.574 banghart 5301: print (OUT $file."\n");
1.572 banghart 5302: }
1.574 banghart 5303: close (OUT);
1.572 banghart 5304: return 'ok';
5305: }
5306:
1.574 banghart 5307: sub clear_selected_files {
5308: my ($user) = @_;
5309: my $filename = $user."savedfiles";
5310: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5311: print (OUT undef);
5312: close (OUT);
5313: return ("ok");
5314: }
5315:
1.572 banghart 5316: sub files_in_path {
5317: my ($user, $path) = @_;
5318: my $filename = $user."savedfiles";
5319: my %return_files;
1.574 banghart 5320: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573 banghart 5321: while (my $line_in = <IN>) {
1.574 banghart 5322: chomp ($line_in);
5323: my @paths_and_file = split (m!/!, $line_in);
5324: my $file_part = pop (@paths_and_file);
5325: my $path_part = join ('/', @paths_and_file);
1.573 banghart 5326: $path_part.='/';
5327: my $path_and_file = $path_part.$file_part;
5328: if ($path_part eq $path) {
5329: $return_files{$file_part}= 'selected';
5330: }
5331: }
1.574 banghart 5332: close (IN);
5333: return (\%return_files);
1.572 banghart 5334: }
5335:
5336: # called in portfolio select mode, to show files selected NOT in current directory
5337: sub files_not_in_path {
5338: my ($user, $path) = @_;
5339: my $filename = $user."savedfiles";
5340: my @return_files;
5341: my $path_part;
1.800 albertel 5342: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
5343: while (my $line = <IN>) {
1.572 banghart 5344: #ok, I know it's clunky, but I want it to work
1.800 albertel 5345: my @paths_and_file = split(m|/|, $line);
5346: my $file_part = pop(@paths_and_file);
5347: chomp($file_part);
5348: my $path_part = join('/', @paths_and_file);
1.572 banghart 5349: $path_part .= '/';
5350: my $path_and_file = $path_part.$file_part;
5351: if ($path_part ne $path) {
1.800 albertel 5352: push(@return_files, ($path_and_file));
1.572 banghart 5353: }
5354: }
1.800 albertel 5355: close(OUT);
1.574 banghart 5356: return (@return_files);
1.572 banghart 5357: }
5358:
1.745 raeburn 5359: #----------------------------------------------Get portfolio file permissions
1.629 banghart 5360:
1.745 raeburn 5361: sub get_portfile_permissions {
5362: my ($domain,$user) = @_;
1.613 albertel 5363: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 5364: my ($tmp)=keys(%current_permissions);
5365: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5366: return \%current_permissions;
5367: }
5368:
5369: #---------------------------------------------Get portfolio file access controls
5370:
1.749 raeburn 5371: sub get_access_controls {
1.745 raeburn 5372: my ($current_permissions,$group,$file) = @_;
1.769 albertel 5373: my %access;
5374: my $real_file = $file;
5375: $file =~ s/\.meta$//;
1.745 raeburn 5376: if (defined($file)) {
1.749 raeburn 5377: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
5378: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 5379: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 5380: }
5381: }
1.745 raeburn 5382: } else {
1.749 raeburn 5383: foreach my $key (keys(%{$current_permissions})) {
5384: if ($key =~ /\0accesscontrol$/) {
5385: if (defined($group)) {
5386: if ($key !~ m-^\Q$group\E/-) {
5387: next;
5388: }
5389: }
5390: my ($fullpath) = split(/\0/,$key);
5391: if (ref($$current_permissions{$key}) eq 'HASH') {
5392: foreach my $control (keys(%{$$current_permissions{$key}})) {
5393: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
5394: }
5395: }
5396: }
5397: }
5398: }
5399: return %access;
5400: }
5401:
5402: sub modify_access_controls {
5403: my ($file_name,$changes,$domain,$user)=@_;
5404: my ($outcome,$deloutcome);
5405: my %store_permissions;
5406: my %new_values;
5407: my %new_control;
5408: my %translation;
5409: my @deletions = ();
5410: my $now = time;
5411: if (exists($$changes{'activate'})) {
5412: if (ref($$changes{'activate'}) eq 'HASH') {
5413: my @newitems = sort(keys(%{$$changes{'activate'}}));
5414: my $numnew = scalar(@newitems);
5415: for (my $i=0; $i<$numnew; $i++) {
5416: my $newkey = $newitems[$i];
5417: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 5418: if ($newkey =~ /^\d+:/) {
5419: $newkey =~ s/^(\d+)/$newid/;
5420: $translation{$1} = $newid;
5421: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
5422: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
5423: $translation{$1} = $newid;
5424: }
1.749 raeburn 5425: $new_values{$file_name."\0".$newkey} =
5426: $$changes{'activate'}{$newitems[$i]};
5427: $new_control{$newkey} = $now;
5428: }
5429: }
5430: }
5431: my %todelete;
5432: my %changed_items;
5433: foreach my $action ('delete','update') {
5434: if (exists($$changes{$action})) {
5435: if (ref($$changes{$action}) eq 'HASH') {
5436: foreach my $key (keys(%{$$changes{$action}})) {
5437: my ($itemnum) = ($key =~ /^([^:]+):/);
5438: if ($action eq 'delete') {
5439: $todelete{$itemnum} = 1;
5440: } else {
5441: $changed_items{$itemnum} = $key;
5442: }
5443: }
1.745 raeburn 5444: }
5445: }
1.749 raeburn 5446: }
5447: # get lock on access controls for file.
5448: my $lockhash = {
5449: $file_name."\0".'locked_access_records' => $env{'user.name'}.
5450: ':'.$env{'user.domain'},
5451: };
5452: my $tries = 0;
5453: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5454:
5455: while (($gotlock ne 'ok') && $tries <3) {
5456: $tries ++;
5457: sleep 1;
5458: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
5459: }
5460: if ($gotlock eq 'ok') {
5461: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
5462: my ($tmp)=keys(%curr_permissions);
5463: if ($tmp=~/^error:/) { undef(%curr_permissions); }
5464: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
5465: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
5466: if (ref($curr_controls) eq 'HASH') {
5467: foreach my $control_item (keys(%{$curr_controls})) {
5468: my ($itemnum) = ($control_item =~ /^([^:]+):/);
5469: if (defined($todelete{$itemnum})) {
5470: push(@deletions,$file_name."\0".$control_item);
5471: } else {
5472: if (defined($changed_items{$itemnum})) {
5473: $new_control{$changed_items{$itemnum}} = $now;
5474: push(@deletions,$file_name."\0".$control_item);
5475: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
5476: } else {
5477: $new_control{$control_item} = $$curr_controls{$control_item};
5478: }
5479: }
1.745 raeburn 5480: }
5481: }
5482: }
1.749 raeburn 5483: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
5484: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
5485: $outcome = &put('file_permissions',\%new_values,$domain,$user);
5486: # remove lock
5487: my @del_lock = ($file_name."\0".'locked_access_records');
5488: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 5489: my ($file,$group);
5490: if (&is_course($domain,$user)) {
5491: ($group,$file) = split(/\//,$file_name,2);
5492: } else {
5493: $file = $file_name;
5494: }
5495: my $sqlresult =
5496: &update_portfolio_table($user,$domain,$file,'portfolio_access',
5497: $group);
1.749 raeburn 5498: } else {
5499: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 5500: }
1.749 raeburn 5501: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 5502: }
5503:
1.827 raeburn 5504: sub make_public_indefinitely {
5505: my ($requrl) = @_;
5506: my $now = time;
5507: my $action = 'activate';
5508: my $aclnum = 0;
5509: if (&is_portfolio_url($requrl)) {
5510: my (undef,$udom,$unum,$file_name,$group) =
5511: &parse_portfolio_url($requrl);
5512: my $current_perms = &get_portfile_permissions($udom,$unum);
5513: my %access_controls = &get_access_controls($current_perms,
5514: $group,$file_name);
5515: foreach my $key (keys(%{$access_controls{$file_name}})) {
5516: my ($num,$scope,$end,$start) =
5517: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5518: if ($scope eq 'public') {
5519: if ($start <= $now && $end == 0) {
5520: $action = 'none';
5521: } else {
5522: $action = 'update';
5523: $aclnum = $num;
5524: }
5525: last;
5526: }
5527: }
5528: if ($action eq 'none') {
5529: return 'ok';
5530: } else {
5531: my %changes;
5532: my $newend = 0;
5533: my $newstart = $now;
5534: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
5535: $changes{$action}{$newkey} = {
5536: type => 'public',
5537: time => {
5538: start => $newstart,
5539: end => $newend,
5540: },
5541: };
5542: my ($outcome,$deloutcome,$new_values,$translation) =
5543: &modify_access_controls($file_name,\%changes,$udom,$unum);
5544: return $outcome;
5545: }
5546: } else {
5547: return 'invalid';
5548: }
5549: }
5550:
1.745 raeburn 5551: #------------------------------------------------------Get Marked as Read Only
5552:
5553: sub get_marked_as_readonly {
5554: my ($domain,$user,$what,$group) = @_;
5555: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 5556: my @readonly_files;
1.629 banghart 5557: my $cmp1=$what;
5558: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 5559: while (my ($file_name,$value) = each(%{$current_permissions})) {
5560: if (defined($group)) {
5561: if ($file_name !~ m-^\Q$group\E/-) {
5562: next;
5563: }
5564: }
1.561 banghart 5565: if (ref($value) eq "ARRAY"){
5566: foreach my $stored_what (@{$value}) {
1.629 banghart 5567: my $cmp2=$stored_what;
1.759 albertel 5568: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 5569: $cmp2=join('',@{$stored_what});
1.745 raeburn 5570: }
1.629 banghart 5571: if ($cmp1 eq $cmp2) {
1.561 banghart 5572: push(@readonly_files, $file_name);
1.745 raeburn 5573: last;
1.563 banghart 5574: } elsif (!defined($what)) {
5575: push(@readonly_files, $file_name);
1.745 raeburn 5576: last;
1.561 banghart 5577: }
5578: }
1.745 raeburn 5579: }
1.561 banghart 5580: }
5581: return @readonly_files;
5582: }
1.577 banghart 5583: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 5584:
1.577 banghart 5585: sub get_marked_as_readonly_hash {
1.745 raeburn 5586: my ($current_permissions,$group,$what) = @_;
1.577 banghart 5587: my %readonly_files;
1.745 raeburn 5588: while (my ($file_name,$value) = each(%{$current_permissions})) {
5589: if (defined($group)) {
5590: if ($file_name !~ m-^\Q$group\E/-) {
5591: next;
5592: }
5593: }
1.577 banghart 5594: if (ref($value) eq "ARRAY"){
5595: foreach my $stored_what (@{$value}) {
1.745 raeburn 5596: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 5597: foreach my $lock_descriptor(@{$stored_what}) {
5598: if ($lock_descriptor eq 'graded') {
5599: $readonly_files{$file_name} = 'graded';
5600: } elsif ($lock_descriptor eq 'handback') {
5601: $readonly_files{$file_name} = 'handback';
5602: } else {
5603: if (!exists($readonly_files{$file_name})) {
5604: $readonly_files{$file_name} = 'locked';
5605: }
5606: }
1.745 raeburn 5607: }
1.750 banghart 5608: }
1.577 banghart 5609: }
5610: }
5611: }
5612: return %readonly_files;
5613: }
1.559 banghart 5614: # ------------------------------------------------------------ Unmark as Read Only
5615:
5616: sub unmark_as_readonly {
1.629 banghart 5617: # unmarks $file_name (if $file_name is defined), or all files locked by $what
5618: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 5619: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 5620: $file_name = &declutter_portfile($file_name);
1.634 albertel 5621: my $symb_crs = $what;
5622: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 5623: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 5624: my ($tmp)=keys(%current_permissions);
5625: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 5626: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 5627: foreach my $file (@readonly_files) {
1.759 albertel 5628: my $clean_file = &declutter_portfile($file);
5629: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 5630: my $current_locks = $current_permissions{$file};
1.563 banghart 5631: my @new_locks;
5632: my @del_keys;
5633: if (ref($current_locks) eq "ARRAY"){
5634: foreach my $locker (@{$current_locks}) {
1.632 albertel 5635: my $compare=$locker;
1.749 raeburn 5636: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 5637: $compare=join('',@{$locker});
1.746 raeburn 5638: if ($compare ne $symb_crs) {
5639: push(@new_locks, $locker);
5640: }
1.563 banghart 5641: }
5642: }
1.650 albertel 5643: if (scalar(@new_locks) > 0) {
1.563 banghart 5644: $current_permissions{$file} = \@new_locks;
5645: } else {
5646: push(@del_keys, $file);
1.613 albertel 5647: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 5648: delete($current_permissions{$file});
1.563 banghart 5649: }
5650: }
1.561 banghart 5651: }
1.613 albertel 5652: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 5653: return;
5654: }
1.512 banghart 5655:
1.17 www 5656: # ------------------------------------------------------------ Directory lister
5657:
5658: sub dirlist {
1.253 stredwic 5659: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
5660:
1.18 www 5661: $uri=~s/^\///;
5662: $uri=~s/\/$//;
1.253 stredwic 5663: my ($udom, $uname);
5664: (undef,$udom,$uname)=split(/\//,$uri);
5665: if(defined($userdomain)) {
5666: $udom = $userdomain;
5667: }
5668: if(defined($username)) {
5669: $uname = $username;
5670: }
5671:
5672: my $dirRoot = $perlvar{'lonDocRoot'};
5673: if(defined($alternateDirectoryRoot)) {
5674: $dirRoot = $alternateDirectoryRoot;
5675: $dirRoot =~ s/\/$//;
1.751 banghart 5676: }
1.253 stredwic 5677:
5678: if($udom) {
5679: if($uname) {
1.800 albertel 5680: my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
5681: &homeserver($uname,$udom));
1.605 matthew 5682: my @listing_results;
5683: if ($listing eq 'unknown_cmd') {
1.800 albertel 5684: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
5685: &homeserver($uname,$udom));
1.605 matthew 5686: @listing_results = split(/:/,$listing);
5687: } else {
5688: @listing_results = map { &unescape($_); } split(/:/,$listing);
5689: }
5690: return @listing_results;
1.253 stredwic 5691: } elsif(!defined($alternateDirectoryRoot)) {
1.800 albertel 5692: my %allusers;
1.841 albertel 5693: my %servers = &get_servers($udom,'library');
5694: foreach my $tryserver (keys(%servers)) {
5695: my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
5696: $udom, $tryserver);
5697: my @listing_results;
5698: if ($listing eq 'unknown_cmd') {
5699: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
5700: $udom, $tryserver);
5701: @listing_results = split(/:/,$listing);
5702: } else {
5703: @listing_results =
5704: map { &unescape($_); } split(/:/,$listing);
5705: }
5706: if ($listing_results[0] ne 'no_such_dir' &&
5707: $listing_results[0] ne 'empty' &&
5708: $listing_results[0] ne 'con_lost') {
5709: foreach my $line (@listing_results) {
5710: my ($entry) = split(/&/,$line,2);
5711: $allusers{$entry} = 1;
5712: }
5713: }
1.253 stredwic 5714: }
5715: my $alluserstr='';
1.800 albertel 5716: foreach my $user (sort(keys(%allusers))) {
5717: $alluserstr.=$user.'&user:';
1.253 stredwic 5718: }
5719: $alluserstr=~s/:$//;
5720: return split(/:/,$alluserstr);
5721: } else {
1.800 albertel 5722: return ('missing user name');
1.253 stredwic 5723: }
5724: } elsif(!defined($alternateDirectoryRoot)) {
1.841 albertel 5725: my @all_domains = sort(&all_domains());
5726: foreach my $domain (@all_domains) {
5727: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
5728: }
5729: return @all_domains;
5730: } else {
1.800 albertel 5731: return ('missing domain');
1.275 stredwic 5732: }
5733: }
5734:
5735: # --------------------------------------------- GetFileTimestamp
5736: # This function utilizes dirlist and returns the date stamp for
5737: # when it was last modified. It will also return an error of -1
5738: # if an error occurs
5739:
1.410 matthew 5740: ##
5741: ## FIXME: This subroutine assumes its caller knows something about the
5742: ## directory structure of the home server for the student ($root).
5743: ## Not a good assumption to make. Since this is for looking up files
5744: ## in user directories, the full path should be constructed by lond, not
5745: ## whatever machine we request data from.
5746: ##
1.275 stredwic 5747: sub GetFileTimestamp {
5748: my ($studentDomain,$studentName,$filename,$root)=@_;
1.807 albertel 5749: $studentDomain = &LONCAPA::clean_domain($studentDomain);
5750: $studentName = &LONCAPA::clean_username($studentName);
1.275 stredwic 5751: my $subdir=$studentName.'__';
5752: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5753: my $proname="$studentDomain/$subdir/$studentName";
5754: $proname .= '/'.$filename;
1.375 matthew 5755: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain,
5756: $studentName, $root);
1.275 stredwic 5757: my @stats = split('&', $fileStat);
5758: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 5759: # @stats contains first the filename, then the stat output
5760: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 5761: } else {
5762: return -1;
1.253 stredwic 5763: }
1.26 www 5764: }
5765:
1.712 albertel 5766: sub stat_file {
5767: my ($uri) = @_;
1.787 albertel 5768: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 5769:
1.712 albertel 5770: my ($udom,$uname,$file,$dir);
5771: if ($uri =~ m-^/(uploaded|editupload)/-) {
5772: ($udom,$uname,$file) =
1.811 albertel 5773: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 5774: $file = 'userfiles/'.$file;
1.740 www 5775: $dir = &propath($udom,$uname);
1.712 albertel 5776: }
5777: if ($uri =~ m-^/res/-) {
5778: ($udom,$uname) =
1.807 albertel 5779: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 5780: $file = $uri;
5781: }
5782:
5783: if (!$udom || !$uname || !$file) {
5784: # unable to handle the uri
5785: return ();
5786: }
5787:
5788: my ($result) = &dirlist($file,$udom,$uname,$dir);
5789: my @stats = split('&', $result);
1.721 banghart 5790:
1.712 albertel 5791: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
5792: shift(@stats); #filename is first
5793: return @stats;
5794: }
5795: return ();
5796: }
5797:
1.26 www 5798: # -------------------------------------------------------- Value of a Condition
5799:
1.713 albertel 5800: # gets the value of a specific preevaluated condition
5801: # stored in the string $env{user.state.<cid>}
5802: # or looks up a condition reference in the bighash and if if hasn't
5803: # already been evaluated recurses into docondval to get the value of
5804: # the condition, then memoizing it to
5805: # $env{user.state.<cid>.<condition>}
1.40 www 5806: sub directcondval {
5807: my $number=shift;
1.620 albertel 5808: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 5809: &Apache::lonuserstate::evalstate();
5810: }
1.713 albertel 5811: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
5812: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
5813: } elsif ($number =~ /^_/) {
5814: my $sub_condition;
5815: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5816: &GDBM_READER(),0640)) {
5817: $sub_condition=$bighash{'conditions'.$number};
5818: untie(%bighash);
5819: }
5820: my $value = &docondval($sub_condition);
5821: &appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
5822: return $value;
5823: }
1.620 albertel 5824: if ($env{'user.state.'.$env{'request.course.id'}}) {
5825: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 5826: } else {
5827: return 2;
5828: }
5829: }
5830:
1.713 albertel 5831: # get the collection of conditions for this resource
1.26 www 5832: sub condval {
5833: my $condidx=shift;
1.54 www 5834: my $allpathcond='';
1.713 albertel 5835: foreach my $cond (split(/\|/,$condidx)) {
5836: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
5837: $allpathcond.=
5838: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
5839: }
1.191 harris41 5840: }
1.54 www 5841: $allpathcond=~s/\|$//;
1.713 albertel 5842: return &docondval($allpathcond);
5843: }
5844:
5845: #evaluates an expression of conditions
5846: sub docondval {
5847: my ($allpathcond) = @_;
5848: my $result=0;
5849: if ($env{'request.course.id'}
5850: && defined($allpathcond)) {
5851: my $operand='|';
5852: my @stack;
5853: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
5854: if ($chunk eq '(') {
5855: push @stack,($operand,$result);
5856: } elsif ($chunk eq ')') {
5857: my $before=pop @stack;
5858: if (pop @stack eq '&') {
5859: $result=$result>$before?$before:$result;
5860: } else {
5861: $result=$result>$before?$result:$before;
5862: }
5863: } elsif (($chunk eq '&') || ($chunk eq '|')) {
5864: $operand=$chunk;
5865: } else {
5866: my $new=directcondval($chunk);
5867: if ($operand eq '&') {
5868: $result=$result>$new?$new:$result;
5869: } else {
5870: $result=$result>$new?$result:$new;
5871: }
5872: }
5873: }
1.26 www 5874: }
5875: return $result;
1.421 albertel 5876: }
5877:
5878: # ---------------------------------------------------- Devalidate courseresdata
5879:
5880: sub devalidatecourseresdata {
5881: my ($coursenum,$coursedomain)=@_;
5882: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5883: &devalidate_cache_new('courseres',$hashid);
1.28 www 5884: }
5885:
1.763 www 5886:
1.200 www 5887: # --------------------------------------------------- Course Resourcedata Query
5888:
1.624 albertel 5889: sub get_courseresdata {
5890: my ($coursenum,$coursedomain)=@_;
1.200 www 5891: my $coursehom=&homeserver($coursenum,$coursedomain);
5892: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 5893: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 5894: my %dumpreply;
1.417 albertel 5895: unless (defined($cached)) {
1.624 albertel 5896: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 5897: $result=\%dumpreply;
1.251 albertel 5898: my ($tmp) = keys(%dumpreply);
5899: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 5900: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 5901: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
5902: return $tmp;
1.416 albertel 5903: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 5904: $result=undef;
1.599 albertel 5905: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 5906: }
5907: }
1.624 albertel 5908: return $result;
5909: }
5910:
1.633 albertel 5911: sub devalidateuserresdata {
5912: my ($uname,$udom)=@_;
5913: my $hashid="$udom:$uname";
5914: &devalidate_cache_new('userres',$hashid);
5915: }
5916:
1.624 albertel 5917: sub get_userresdata {
5918: my ($uname,$udom)=@_;
5919: #most student don\'t have any data set, check if there is some data
5920: if (&EXT_cache_status($udom,$uname)) { return undef; }
5921:
5922: my $hashid="$udom:$uname";
5923: my ($result,$cached)=&is_cached_new('userres',$hashid);
5924: if (!defined($cached)) {
5925: my %resourcedata=&dump('resourcedata',$udom,$uname);
5926: $result=\%resourcedata;
5927: &do_cache_new('userres',$hashid,$result,600);
5928: }
5929: my ($tmp)=keys(%$result);
5930: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
5931: return $result;
5932: }
5933: #error 2 occurs when the .db doesn't exist
5934: if ($tmp!~/error: 2 /) {
1.672 albertel 5935: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 5936: " Trying to get resource data for ".
5937: $uname." at ".$udom.": ".
5938: $tmp."</font>");
5939: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 5940: #&EXT_cache_set($udom,$uname);
5941: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 5942: undef($tmp); # not really an error so don't send it back
1.624 albertel 5943: }
5944: return $tmp;
5945: }
5946:
5947: sub resdata {
5948: my ($name,$domain,$type,@which)=@_;
5949: my $result;
5950: if ($type eq 'course') {
5951: $result=&get_courseresdata($name,$domain);
5952: } elsif ($type eq 'user') {
5953: $result=&get_userresdata($name,$domain);
5954: }
5955: if (!ref($result)) { return $result; }
1.251 albertel 5956: foreach my $item (@which) {
1.417 albertel 5957: if (defined($result->{$item})) {
5958: return $result->{$item};
1.251 albertel 5959: }
1.250 albertel 5960: }
1.291 albertel 5961: return undef;
1.200 www 5962: }
5963:
1.379 matthew 5964: #
5965: # EXT resource caching routines
5966: #
5967:
5968: sub clear_EXT_cache_status {
1.383 albertel 5969: &delenv('cache.EXT.');
1.379 matthew 5970: }
5971:
5972: sub EXT_cache_status {
5973: my ($target_domain,$target_user) = @_;
1.383 albertel 5974: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 5975: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 5976: # We know already the user has no data
5977: return 1;
5978: } else {
5979: return 0;
5980: }
5981: }
5982:
5983: sub EXT_cache_set {
5984: my ($target_domain,$target_user) = @_;
1.383 albertel 5985: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633 albertel 5986: #&appenv($cachename => time);
1.379 matthew 5987: }
5988:
1.28 www 5989: # --------------------------------------------------------- Value of a Variable
1.58 www 5990: sub EXT {
1.715 albertel 5991:
1.395 albertel 5992: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 5993: unless ($varname) { return ''; }
1.218 albertel 5994: #get real user name/domain, courseid and symb
5995: my $courseid;
1.359 albertel 5996: my $publicuser;
1.427 www 5997: if ($symbparm) {
5998: $symbparm=&get_symb_from_alias($symbparm);
5999: }
1.218 albertel 6000: if (!($uname && $udom)) {
1.790 albertel 6001: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 6002: if (!$symbparm) { $symbparm=$cursymb; }
6003: } else {
1.620 albertel 6004: $courseid=$env{'request.course.id'};
1.218 albertel 6005: }
1.48 www 6006: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6007: my $rest;
1.320 albertel 6008: if (defined($therest[0])) {
1.48 www 6009: $rest=join('.',@therest);
6010: } else {
6011: $rest='';
6012: }
1.320 albertel 6013:
1.57 www 6014: my $qualifierrest=$qualifier;
6015: if ($rest) { $qualifierrest.='.'.$rest; }
6016: my $spacequalifierrest=$space;
6017: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 6018: if ($realm eq 'user') {
1.48 www 6019: # --------------------------------------------------------------- user.resource
6020: if ($space eq 'resource') {
1.651 albertel 6021: if ( (defined($Apache::lonhomework::parsing_a_problem)
6022: || defined($Apache::lonhomework::parsing_a_task))
6023: &&
1.744 albertel 6024: ($symbparm eq &symbread()) ) {
6025: # if we are in the middle of processing the resource the
6026: # get the value we are planning on committing
6027: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6028: return $Apache::lonhomework::results{$qualifierrest};
6029: } else {
6030: return $Apache::lonhomework::history{$qualifierrest};
6031: }
1.335 albertel 6032: } else {
1.359 albertel 6033: my %restored;
1.620 albertel 6034: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 6035: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6036: } else {
6037: %restored=&restore($symbparm,$courseid,$udom,$uname);
6038: }
1.335 albertel 6039: return $restored{$qualifierrest};
6040: }
1.48 www 6041: # ----------------------------------------------------------------- user.access
6042: } elsif ($space eq 'access') {
1.218 albertel 6043: # FIXME - not supporting calls for a specific user
1.48 www 6044: return &allowed($qualifier,$rest);
6045: # ------------------------------------------ user.preferences, user.environment
6046: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 6047: if (($uname eq $env{'user.name'}) &&
6048: ($udom eq $env{'user.domain'})) {
6049: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 6050: } else {
1.359 albertel 6051: my %returnhash;
6052: if (!$publicuser) {
6053: %returnhash=&userenvironment($udom,$uname,
6054: $qualifierrest);
6055: }
1.218 albertel 6056: return $returnhash{$qualifierrest};
6057: }
1.48 www 6058: # ----------------------------------------------------------------- user.course
6059: } elsif ($space eq 'course') {
1.218 albertel 6060: # FIXME - not supporting calls for a specific user
1.620 albertel 6061: return $env{join('.',('request.course',$qualifier))};
1.48 www 6062: # ------------------------------------------------------------------- user.role
6063: } elsif ($space eq 'role') {
1.218 albertel 6064: # FIXME - not supporting calls for a specific user
1.620 albertel 6065: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 6066: if ($qualifier eq 'value') {
6067: return $role;
6068: } elsif ($qualifier eq 'extent') {
6069: return $where;
6070: }
6071: # ----------------------------------------------------------------- user.domain
6072: } elsif ($space eq 'domain') {
1.218 albertel 6073: return $udom;
1.48 www 6074: # ------------------------------------------------------------------- user.name
6075: } elsif ($space eq 'name') {
1.218 albertel 6076: return $uname;
1.48 www 6077: # ---------------------------------------------------- Any other user namespace
1.29 www 6078: } else {
1.359 albertel 6079: my %reply;
6080: if (!$publicuser) {
6081: %reply=&get($space,[$qualifierrest],$udom,$uname);
6082: }
6083: return $reply{$qualifierrest};
1.48 www 6084: }
1.236 www 6085: } elsif ($realm eq 'query') {
6086: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 6087: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6088: [$spacequalifierrest]);
1.620 albertel 6089: return $env{'form.'.$spacequalifierrest};
1.236 www 6090: } elsif ($realm eq 'request') {
1.48 www 6091: # ------------------------------------------------------------- request.browser
6092: if ($space eq 'browser') {
1.430 www 6093: if ($qualifier eq 'textremote') {
1.676 albertel 6094: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 6095: return 1;
6096: } else {
6097: return 0;
6098: }
6099: } else {
1.620 albertel 6100: return $env{'browser.'.$qualifier};
1.430 www 6101: }
1.57 www 6102: # ------------------------------------------------------------ request.filename
6103: } else {
1.620 albertel 6104: return $env{'request.'.$spacequalifierrest};
1.29 www 6105: }
1.28 www 6106: } elsif ($realm eq 'course') {
1.48 www 6107: # ---------------------------------------------------------- course.description
1.620 albertel 6108: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 6109: } elsif ($realm eq 'resource') {
1.165 www 6110:
1.620 albertel 6111: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 6112: if (!$symbparm) { $symbparm=&symbread(); }
6113: }
1.693 albertel 6114:
6115: if ($space eq 'title') {
6116: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6117: return &gettitle($symbparm);
6118: }
6119:
6120: if ($space eq 'map') {
6121: my ($map) = &decode_symb($symbparm);
6122: return &symbread($map);
6123: }
6124:
6125: my ($section, $group, @groups);
1.593 albertel 6126: my ($courselevelm,$courselevel);
1.539 albertel 6127: if ($symbparm && defined($courseid) &&
1.620 albertel 6128: $courseid eq $env{'request.course.id'}) {
1.165 www 6129:
1.218 albertel 6130: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 6131:
1.60 www 6132: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 6133: my $symbp=$symbparm;
1.735 albertel 6134: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 6135:
6136: my $symbparm=$symbp.'.'.$spacequalifierrest;
6137: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
6138:
1.620 albertel 6139: if (($env{'user.name'} eq $uname) &&
6140: ($env{'user.domain'} eq $udom)) {
6141: $section=$env{'request.course.sec'};
1.733 raeburn 6142: @groups = split(/:/,$env{'request.course.groups'});
6143: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 6144: } else {
1.539 albertel 6145: if (! defined($usection)) {
1.551 albertel 6146: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 6147: } else {
6148: $section = $usection;
6149: }
1.733 raeburn 6150: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 6151: }
6152:
6153: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
6154: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
6155: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
6156:
1.593 albertel 6157: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 6158: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 6159: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 6160:
1.60 www 6161: # ----------------------------------------------------------- first, check user
1.624 albertel 6162:
6163: my $userreply=&resdata($uname,$udom,'user',
6164: ($courselevelr,$courselevelm,
6165: $courselevel));
6166: if (defined($userreply)) { return $userreply; }
1.95 www 6167:
1.594 albertel 6168: # ------------------------------------------------ second, check some of course
1.684 raeburn 6169: my $coursereply;
1.691 raeburn 6170: if (@groups > 0) {
6171: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
6172: $mapparm,$spacequalifierrest);
1.684 raeburn 6173: if (defined($coursereply)) { return $coursereply; }
6174: }
1.96 www 6175:
1.684 raeburn 6176: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624 albertel 6177: $env{'course.'.$courseid.'.domain'},
6178: 'course',
6179: ($seclevelr,$seclevelm,$seclevel,
6180: $courselevelr));
1.287 albertel 6181: if (defined($coursereply)) { return $coursereply; }
1.200 www 6182:
1.60 www 6183: # ------------------------------------------------------ third, check map parms
1.218 albertel 6184: my %parmhash=();
6185: my $thisparm='';
6186: if (tie(%parmhash,'GDBM_File',
1.620 albertel 6187: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 6188: &GDBM_READER(),0640)) {
1.218 albertel 6189: $thisparm=$parmhash{$symbparm};
6190: untie(%parmhash);
6191: }
6192: if ($thisparm) { return $thisparm; }
6193: }
1.594 albertel 6194: # ------------------------------------------ fourth, look in resource metadata
1.71 www 6195:
1.218 albertel 6196: $spacequalifierrest=~s/\./\_/;
1.282 albertel 6197: my $filename;
6198: if (!$symbparm) { $symbparm=&symbread(); }
6199: if ($symbparm) {
1.409 www 6200: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 6201: } else {
1.620 albertel 6202: $filename=$env{'request.filename'};
1.282 albertel 6203: }
6204: my $metadata=&metadata($filename,$spacequalifierrest);
1.288 albertel 6205: if (defined($metadata)) { return $metadata; }
1.282 albertel 6206: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288 albertel 6207: if (defined($metadata)) { return $metadata; }
1.142 www 6208:
1.594 albertel 6209: # ---------------------------------------------- fourth, look in rest pf course
1.593 albertel 6210: if ($symbparm && defined($courseid) &&
1.620 albertel 6211: $courseid eq $env{'request.course.id'}) {
1.624 albertel 6212: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
6213: $env{'course.'.$courseid.'.domain'},
6214: 'course',
6215: ($courselevelm,$courselevel));
1.593 albertel 6216: if (defined($coursereply)) { return $coursereply; }
6217: }
1.145 www 6218: # ------------------------------------------------------------------ Cascade up
1.218 albertel 6219: unless ($space eq '0') {
1.336 albertel 6220: my @parts=split(/_/,$space);
6221: my $id=pop(@parts);
6222: my $part=join('_',@parts);
6223: if ($part eq '') { $part='0'; }
6224: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 6225: $symbparm,$udom,$uname,$section,1);
1.337 albertel 6226: if (defined($partgeneral)) { return $partgeneral; }
1.218 albertel 6227: }
1.395 albertel 6228: if ($recurse) { return undef; }
6229: my $pack_def=&packages_tab_default($filename,$varname);
6230: if (defined($pack_def)) { return $pack_def; }
1.71 www 6231:
1.48 www 6232: # ---------------------------------------------------- Any other user namespace
6233: } elsif ($realm eq 'environment') {
6234: # ----------------------------------------------------------------- environment
1.620 albertel 6235: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
6236: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 6237: } else {
1.770 albertel 6238: if ($uname eq 'anonymous' && $udom eq '') {
6239: return '';
6240: }
1.219 albertel 6241: my %returnhash=&userenvironment($udom,$uname,
6242: $spacequalifierrest);
6243: return $returnhash{$spacequalifierrest};
6244: }
1.28 www 6245: } elsif ($realm eq 'system') {
1.48 www 6246: # ----------------------------------------------------------------- system.time
6247: if ($space eq 'time') {
6248: return time;
6249: }
1.696 albertel 6250: } elsif ($realm eq 'server') {
6251: # ----------------------------------------------------------------- system.time
6252: if ($space eq 'name') {
6253: return $ENV{'SERVER_NAME'};
6254: }
1.28 www 6255: }
1.48 www 6256: return '';
1.61 www 6257: }
6258:
1.691 raeburn 6259: sub check_group_parms {
6260: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
6261: my @groupitems = ();
6262: my $resultitem;
6263: my @levels = ($symbparm,$mapparm,$what);
6264: foreach my $group (@{$groups}) {
6265: foreach my $level (@levels) {
6266: my $item = $courseid.'.['.$group.'].'.$level;
6267: push(@groupitems,$item);
6268: }
6269: }
6270: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
6271: $env{'course.'.$courseid.'.domain'},
6272: 'course',@groupitems);
6273: return $coursereply;
6274: }
6275:
6276: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 6277: my ($courseid,@groups) = @_;
6278: @groups = sort(@groups);
1.691 raeburn 6279: return @groups;
6280: }
6281:
1.395 albertel 6282: sub packages_tab_default {
6283: my ($uri,$varname)=@_;
6284: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 6285:
6286: my (@extension,@specifics,$do_default);
6287: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 6288: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 6289: if ($pack_type eq 'default') {
6290: $do_default=1;
6291: } elsif ($pack_type eq 'extension') {
6292: push(@extension,[$package,$pack_type,$pack_part]);
1.848 albertel 6293: } elsif ($pack_part eq $part) {
6294: # only look at packages defaults for packages that this id is
1.738 albertel 6295: push(@specifics,[$package,$pack_type,$pack_part]);
6296: }
6297: }
6298: # first look for a package that matches the requested part id
6299: foreach my $package (@specifics) {
6300: my (undef,$pack_type,$pack_part)=@{$package};
6301: next if ($pack_part ne $part);
6302: if (defined($packagetab{"$pack_type&$name&default"})) {
6303: return $packagetab{"$pack_type&$name&default"};
6304: }
6305: }
6306: # look for any possible matching non extension_ package
6307: foreach my $package (@specifics) {
6308: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 6309: if (defined($packagetab{"$pack_type&$name&default"})) {
6310: return $packagetab{"$pack_type&$name&default"};
6311: }
1.585 albertel 6312: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 6313: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
6314: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 6315: }
6316: }
1.738 albertel 6317: # look for any posible extension_ match
6318: foreach my $package (@extension) {
6319: my ($package,$pack_type)=@{$package};
6320: if (defined($packagetab{"$pack_type&$name&default"})) {
6321: return $packagetab{"$pack_type&$name&default"};
6322: }
6323: if (defined($packagetab{$package."&$name&default"})) {
6324: return $packagetab{$package."&$name&default"};
6325: }
6326: }
6327: # look for a global default setting
6328: if ($do_default && defined($packagetab{"default&$name&default"})) {
6329: return $packagetab{"default&$name&default"};
6330: }
1.395 albertel 6331: return undef;
6332: }
6333:
1.334 albertel 6334: sub add_prefix_and_part {
6335: my ($prefix,$part)=@_;
6336: my $keyroot;
6337: if (defined($prefix) && $prefix !~ /^__/) {
6338: # prefix that has a part already
6339: $keyroot=$prefix;
6340: } elsif (defined($prefix)) {
6341: # prefix that is missing a part
6342: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
6343: } else {
6344: # no prefix at all
6345: if (defined($part)) { $keyroot='_'.$part; }
6346: }
6347: return $keyroot;
6348: }
6349:
1.71 www 6350: # ---------------------------------------------------------------- Get metadata
6351:
1.599 albertel 6352: my %metaentry;
1.71 www 6353: sub metadata {
1.176 www 6354: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 6355: $uri=&declutter($uri);
1.288 albertel 6356: # if it is a non metadata possible uri return quickly
1.529 albertel 6357: if (($uri eq '') ||
6358: (($uri =~ m|^/*adm/|) &&
1.698 albertel 6359: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423 albertel 6360: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807 albertel 6361: ($uri =~ m|home/$match_username/public_html/|)) {
1.468 albertel 6362: return undef;
1.288 albertel 6363: }
1.73 www 6364: my $filename=$uri;
6365: $uri=~s/\.meta$//;
1.172 www 6366: #
6367: # Is the metadata already cached?
1.177 www 6368: # Look at timestamp of caching
1.172 www 6369: # Everything is cached by the main uri, libraries are never directly cached
6370: #
1.428 albertel 6371: if (!defined($liburi)) {
1.599 albertel 6372: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 6373: if (defined($cached)) { return $result->{':'.$what}; }
6374: }
6375: {
1.172 www 6376: #
6377: # Is this a recursive call for a library?
6378: #
1.599 albertel 6379: # if (! exists($metacache{$uri})) {
6380: # $metacache{$uri}={};
6381: # }
1.171 www 6382: if ($liburi) {
6383: $liburi=&declutter($liburi);
6384: $filename=$liburi;
1.401 bowersj2 6385: } else {
1.599 albertel 6386: &devalidate_cache_new('meta',$uri);
6387: undef(%metaentry);
1.401 bowersj2 6388: }
1.140 www 6389: my %metathesekeys=();
1.73 www 6390: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 6391: my $metastring;
1.768 albertel 6392: if ($uri !~ m -^(editupload)/-) {
1.543 albertel 6393: my $file=&filelocation('',&clutter($filename));
1.599 albertel 6394: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 6395: $metastring=&getfile($file);
1.489 albertel 6396: }
1.208 albertel 6397: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 6398: my $token;
1.140 www 6399: undef %metathesekeys;
1.71 www 6400: while ($token=$parser->get_token) {
1.339 albertel 6401: if ($token->[0] eq 'S') {
6402: if (defined($token->[2]->{'package'})) {
1.172 www 6403: #
6404: # This is a package - get package info
6405: #
1.339 albertel 6406: my $package=$token->[2]->{'package'};
6407: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6408: if (defined($token->[2]->{'id'})) {
6409: $keyroot.='_'.$token->[2]->{'id'};
6410: }
1.599 albertel 6411: if ($metaentry{':packages'}) {
6412: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 6413: } else {
1.599 albertel 6414: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 6415: }
1.736 albertel 6416: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 6417: my $part=$keyroot;
6418: $part=~s/^\_//;
1.736 albertel 6419: if ($pack_entry=~/^\Q$package\E\&/ ||
6420: $pack_entry=~/^\Q$package\E_0\&/) {
6421: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 6422: # ignore package.tab specified default values
6423: # here &package_tab_default() will fetch those
6424: if ($subp eq 'default') { next; }
1.736 albertel 6425: my $value=$packagetab{$pack_entry};
1.432 albertel 6426: my $unikey;
6427: if ($pack =~ /_0$/) {
6428: $unikey='parameter_0_'.$name;
6429: $part=0;
6430: } else {
6431: $unikey='parameter'.$keyroot.'_'.$name;
6432: }
1.339 albertel 6433: if ($subp eq 'display') {
6434: $value.=' [Part: '.$part.']';
6435: }
1.599 albertel 6436: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 6437: $metathesekeys{$unikey}=1;
1.599 albertel 6438: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6439: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 6440: }
1.599 albertel 6441: if (defined($metaentry{':'.$unikey.'.default'})) {
6442: $metaentry{':'.$unikey}=
6443: $metaentry{':'.$unikey.'.default'};
1.356 albertel 6444: }
1.339 albertel 6445: }
6446: }
6447: } else {
1.172 www 6448: #
6449: # This is not a package - some other kind of start tag
1.339 albertel 6450: #
6451: my $entry=$token->[1];
6452: my $unikey;
6453: if ($entry eq 'import') {
6454: $unikey='';
6455: } else {
6456: $unikey=$entry;
6457: }
6458: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
6459:
6460: if (defined($token->[2]->{'id'})) {
6461: $unikey.='_'.$token->[2]->{'id'};
6462: }
1.175 www 6463:
1.339 albertel 6464: if ($entry eq 'import') {
1.175 www 6465: #
6466: # Importing a library here
1.339 albertel 6467: #
6468: if ($depthcount<20) {
6469: my $location=$parser->get_text('/import');
6470: my $dir=$filename;
6471: $dir=~s|[^/]*$||;
6472: $location=&filelocation($dir,$location);
1.736 albertel 6473: my $metadata =
6474: &metadata($uri,'keys', $location,$unikey,
6475: $depthcount+1);
6476: foreach my $meta (split(',',$metadata)) {
6477: $metaentry{':'.$meta}=$metaentry{':'.$meta};
6478: $metathesekeys{$meta}=1;
1.339 albertel 6479: }
6480: }
6481: } else {
6482:
6483: if (defined($token->[2]->{'name'})) {
6484: $unikey.='_'.$token->[2]->{'name'};
6485: }
6486: $metathesekeys{$unikey}=1;
1.736 albertel 6487: foreach my $param (@{$token->[3]}) {
6488: $metaentry{':'.$unikey.'.'.$param} =
6489: $token->[2]->{$param};
1.339 albertel 6490: }
6491: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 6492: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 6493: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
6494: # only ws inside the tag, and not in default, so use default
6495: # as value
1.599 albertel 6496: $metaentry{':'.$unikey}=$default;
1.339 albertel 6497: } else {
1.321 albertel 6498: # either something interesting inside the tag or default
6499: # uninteresting
1.599 albertel 6500: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 6501: }
1.172 www 6502: # end of not-a-package not-a-library import
1.339 albertel 6503: }
1.172 www 6504: # end of not-a-package start tag
1.339 albertel 6505: }
1.172 www 6506: # the next is the end of "start tag"
1.339 albertel 6507: }
6508: }
1.483 albertel 6509: my ($extension) = ($uri =~ /\.(\w+)$/);
1.737 albertel 6510: foreach my $key (keys(%packagetab)) {
1.483 albertel 6511: #no specific packages #how's our extension
6512: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 6513: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 6514: \%metathesekeys);
6515: }
1.599 albertel 6516: if (!exists($metaentry{':packages'})) {
1.737 albertel 6517: foreach my $key (keys(%packagetab)) {
1.483 albertel 6518: #no specific packages well let's get default then
6519: if ($key!~/^default&/) { next; }
1.488 albertel 6520: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 6521: \%metathesekeys);
6522: }
6523: }
1.338 www 6524: # are there custom rights to evaluate
1.599 albertel 6525: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 6526:
1.338 www 6527: #
6528: # Importing a rights file here
1.339 albertel 6529: #
6530: unless ($depthcount) {
1.599 albertel 6531: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 6532: my $dir=$filename;
6533: $dir=~s|[^/]*$||;
6534: $location=&filelocation($dir,$location);
1.736 albertel 6535: my $rights_metadata =
6536: &metadata($uri,'keys',$location,'_rights',
6537: $depthcount+1);
6538: foreach my $rights (split(',',$rights_metadata)) {
6539: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
6540: $metathesekeys{$rights}=1;
1.339 albertel 6541: }
6542: }
6543: }
1.737 albertel 6544: # uniqifiy package listing
6545: my %seen;
6546: my @uniq_packages =
6547: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
6548: $metaentry{':packages'} = join(',',@uniq_packages);
6549:
6550: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 6551: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
6552: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699 albertel 6553: &do_cache_new('meta',$uri,\%metaentry,60*60);
1.177 www 6554: # this is the end of "was not already recently cached
1.71 www 6555: }
1.599 albertel 6556: return $metaentry{':'.$what};
1.261 albertel 6557: }
6558:
1.488 albertel 6559: sub metadata_create_package_def {
1.483 albertel 6560: my ($uri,$key,$package,$metathesekeys)=@_;
6561: my ($pack,$name,$subp)=split(/\&/,$key);
6562: if ($subp eq 'default') { next; }
6563:
1.599 albertel 6564: if (defined($metaentry{':packages'})) {
6565: $metaentry{':packages'}.=','.$package;
1.483 albertel 6566: } else {
1.599 albertel 6567: $metaentry{':packages'}=$package;
1.483 albertel 6568: }
6569: my $value=$packagetab{$key};
6570: my $unikey;
6571: $unikey='parameter_0_'.$name;
1.599 albertel 6572: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 6573: $$metathesekeys{$unikey}=1;
1.599 albertel 6574: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
6575: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 6576: }
1.599 albertel 6577: if (defined($metaentry{':'.$unikey.'.default'})) {
6578: $metaentry{':'.$unikey}=
6579: $metaentry{':'.$unikey.'.default'};
1.483 albertel 6580: }
6581: }
6582:
1.261 albertel 6583: sub metadata_generate_part0 {
6584: my ($metadata,$metacache,$uri) = @_;
6585: my %allnames;
1.737 albertel 6586: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 6587: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 6588: my $part=$$metacache{':'.$metakey.'.part'};
6589: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 6590: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 6591: $allnames{$name}=$part;
6592: }
6593: }
6594: }
6595: foreach my $name (keys(%allnames)) {
6596: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 6597: my $key=":parameter_0_$name";
1.261 albertel 6598: $$metacache{"$key.part"}='0';
6599: $$metacache{"$key.name"}=$name;
1.428 albertel 6600: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 6601: $allnames{$name}.'_'.$name.
6602: '.type'};
1.428 albertel 6603: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 6604: '.display'};
1.644 www 6605: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 6606: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 6607: $$metacache{"$key.display"}=$olddis;
6608: }
1.71 www 6609: }
6610:
1.764 albertel 6611: # ------------------------------------------------------ Devalidate title cache
6612:
6613: sub devalidate_title_cache {
6614: my ($url)=@_;
6615: if (!$env{'request.course.id'}) { return; }
6616: my $symb=&symbread($url);
6617: if (!$symb) { return; }
6618: my $key=$env{'request.course.id'}."\0".$symb;
6619: &devalidate_cache_new('title',$key);
6620: }
6621:
1.301 www 6622: # ------------------------------------------------- Get the title of a resource
6623:
6624: sub gettitle {
6625: my $urlsymb=shift;
6626: my $symb=&symbread($urlsymb);
1.534 albertel 6627: if ($symb) {
1.620 albertel 6628: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 6629: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 6630: if (defined($cached)) {
6631: return $result;
6632: }
1.534 albertel 6633: my ($map,$resid,$url)=&decode_symb($symb);
6634: my $title='';
6635: my %bighash;
1.620 albertel 6636: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534 albertel 6637: &GDBM_READER(),0640)) {
6638: my $mapid=$bighash{'map_pc_'.&clutter($map)};
6639: $title=$bighash{'title_'.$mapid.'.'.$resid};
6640: untie %bighash;
6641: }
6642: $title=~s/\&colon\;/\:/gs;
6643: if ($title) {
1.599 albertel 6644: return &do_cache_new('title',$key,$title,600);
1.534 albertel 6645: }
6646: $urlsymb=$url;
6647: }
6648: my $title=&metadata($urlsymb,'title');
6649: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
6650: return $title;
1.301 www 6651: }
1.613 albertel 6652:
1.614 albertel 6653: sub get_slot {
6654: my ($which,$cnum,$cdom)=@_;
6655: if (!$cnum || !$cdom) {
1.790 albertel 6656: (undef,my $courseid)=&whichuser();
1.620 albertel 6657: $cdom=$env{'course.'.$courseid.'.domain'};
6658: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 6659: }
1.703 albertel 6660: my $key=join("\0",'slots',$cdom,$cnum,$which);
6661: my %slotinfo;
6662: if (exists($remembered{$key})) {
6663: $slotinfo{$which} = $remembered{$key};
6664: } else {
6665: %slotinfo=&get('slots',[$which],$cdom,$cnum);
6666: &Apache::lonhomework::showhash(%slotinfo);
6667: my ($tmp)=keys(%slotinfo);
6668: if ($tmp=~/^error:/) { return (); }
6669: $remembered{$key} = $slotinfo{$which};
6670: }
1.616 albertel 6671: if (ref($slotinfo{$which}) eq 'HASH') {
6672: return %{$slotinfo{$which}};
6673: }
6674: return $slotinfo{$which};
1.614 albertel 6675: }
1.31 www 6676: # ------------------------------------------------- Update symbolic store links
6677:
6678: sub symblist {
6679: my ($mapname,%newhash)=@_;
1.438 www 6680: $mapname=&deversion(&declutter($mapname));
1.31 www 6681: my %hash;
1.620 albertel 6682: if (($env{'request.course.fn'}) && (%newhash)) {
6683: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6684: &GDBM_WRCREAT(),0640)) {
1.711 albertel 6685: foreach my $url (keys %newhash) {
6686: next if ($url eq 'last_known'
6687: && $env{'form.no_update_last_known'});
6688: $hash{declutter($url)}=&encode_symb($mapname,
6689: $newhash{$url}->[1],
6690: $newhash{$url}->[0]);
1.191 harris41 6691: }
1.31 www 6692: if (untie(%hash)) {
6693: return 'ok';
6694: }
6695: }
6696: }
6697: return 'error';
1.212 www 6698: }
6699:
6700: # --------------------------------------------------------------- Verify a symb
6701:
6702: sub symbverify {
1.510 www 6703: my ($symb,$thisurl)=@_;
6704: my $thisfn=$thisurl;
1.439 www 6705: $thisfn=&declutter($thisfn);
1.215 www 6706: # direct jump to resource in page or to a sequence - will construct own symbs
6707: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
6708: # check URL part
1.409 www 6709: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 6710:
1.431 www 6711: unless ($url eq $thisfn) { return 0; }
1.213 www 6712:
1.216 www 6713: $symb=&symbclean($symb);
1.510 www 6714: $thisurl=&deversion($thisurl);
1.439 www 6715: $thisfn=&deversion($thisfn);
1.213 www 6716:
6717: my %bighash;
6718: my $okay=0;
1.431 www 6719:
1.620 albertel 6720: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6721: &GDBM_READER(),0640)) {
1.510 www 6722: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216 www 6723: unless ($ids) {
1.510 www 6724: $ids=$bighash{'ids_/'.$thisurl};
1.216 www 6725: }
6726: if ($ids) {
6727: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 6728: foreach my $id (split(/\,/,$ids)) {
6729: my ($mapid,$resid)=split(/\./,$id);
1.216 www 6730: if (
6731: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
6732: eq $symb) {
1.620 albertel 6733: if (($env{'request.role.adv'}) ||
1.800 albertel 6734: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582 albertel 6735: $okay=1;
6736: }
6737: }
1.216 www 6738: }
6739: }
1.213 www 6740: untie(%bighash);
6741: }
6742: return $okay;
1.31 www 6743: }
6744:
1.210 www 6745: # --------------------------------------------------------------- Clean-up symb
6746:
6747: sub symbclean {
6748: my $symb=shift;
1.568 albertel 6749: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 6750: # remove version from map
6751: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 6752:
1.210 www 6753: # remove version from URL
6754: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 6755:
1.507 www 6756: # remove wrapper
6757:
1.510 www 6758: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 6759: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 6760: return $symb;
1.409 www 6761: }
6762:
6763: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 6764:
6765: sub encode_symb {
6766: my ($map,$resid,$url)=@_;
6767: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
6768: }
1.409 www 6769:
6770: sub decode_symb {
1.568 albertel 6771: my $symb=shift;
6772: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
6773: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 6774: return (&fixversion($map),$resid,&fixversion($url));
6775: }
6776:
6777: sub fixversion {
6778: my $fn=shift;
1.609 banghart 6779: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 6780: my %bighash;
6781: my $uri=&clutter($fn);
1.620 albertel 6782: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 6783: # is this cached?
1.599 albertel 6784: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 6785: if (defined($cached)) { return $result; }
6786: # unfortunately not cached, or expired
1.620 albertel 6787: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 6788: &GDBM_READER(),0640)) {
6789: if ($bighash{'version_'.$uri}) {
6790: my $version=$bighash{'version_'.$uri};
1.444 www 6791: unless (($version eq 'mostrecent') ||
6792: ($version==&getversion($uri))) {
1.440 www 6793: $uri=~s/\.(\w+)$/\.$version\.$1/;
6794: }
6795: }
6796: untie %bighash;
1.413 www 6797: }
1.599 albertel 6798: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 6799: }
6800:
6801: sub deversion {
6802: my $url=shift;
6803: $url=~s/\.\d+\.(\w+)$/\.$1/;
6804: return $url;
1.210 www 6805: }
6806:
1.31 www 6807: # ------------------------------------------------------ Return symb list entry
6808:
6809: sub symbread {
1.249 www 6810: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 6811: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 6812: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 6813: # no filename provided? try from environment
1.44 www 6814: unless ($thisfn) {
1.620 albertel 6815: if ($env{'request.symb'}) {
6816: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 6817: }
1.620 albertel 6818: $thisfn=$env{'request.filename'};
1.44 www 6819: }
1.569 albertel 6820: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 6821: # is that filename actually a symb? Verify, clean, and return
6822: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 6823: if (&symbverify($thisfn,$1)) {
1.620 albertel 6824: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 6825: }
1.242 www 6826: }
1.44 www 6827: $thisfn=declutter($thisfn);
1.31 www 6828: my %hash;
1.37 www 6829: my %bighash;
6830: my $syval='';
1.620 albertel 6831: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 6832: my $targetfn = $thisfn;
1.609 banghart 6833: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 6834: $targetfn = 'adm/wrapper/'.$thisfn;
6835: }
1.687 albertel 6836: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
6837: $targetfn=$1;
6838: }
1.620 albertel 6839: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 6840: &GDBM_READER(),0640)) {
1.481 raeburn 6841: $syval=$hash{$targetfn};
1.37 www 6842: untie(%hash);
6843: }
6844: # ---------------------------------------------------------- There was an entry
6845: if ($syval) {
1.601 albertel 6846: #unless ($syval=~/\_\d+$/) {
1.620 albertel 6847: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601 albertel 6848: #&appenv('request.ambiguous' => $thisfn);
1.620 albertel 6849: #return $env{$cache_str}='';
1.601 albertel 6850: #}
6851: #$syval.=$1;
6852: #}
1.37 www 6853: } else {
6854: # ------------------------------------------------------- Was not in symb table
1.620 albertel 6855: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 6856: &GDBM_READER(),0640)) {
1.37 www 6857: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 6858: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 6859: unless ($ids) {
6860: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 6861: }
6862: unless ($ids) {
6863: # alias?
6864: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 6865: }
1.37 www 6866: if ($ids) {
6867: # ------------------------------------------------------------------- Has ID(s)
6868: my @possibilities=split(/\,/,$ids);
1.39 www 6869: if ($#possibilities==0) {
6870: # ----------------------------------------------- There is only one possibility
1.37 www 6871: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 6872: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6873: $resid,$thisfn);
1.249 www 6874: } elsif (!$donotrecurse) {
1.39 www 6875: # ------------------------------------------ There is more than one possibility
6876: my $realpossible=0;
1.800 albertel 6877: foreach my $id (@possibilities) {
6878: my $file=$bighash{'src_'.$id};
1.39 www 6879: if (&allowed('bre',$file)) {
1.800 albertel 6880: my ($mapid,$resid)=split(/\./,$id);
1.39 www 6881: if ($bighash{'map_type_'.$mapid} ne 'page') {
6882: $realpossible++;
1.626 albertel 6883: $syval=&encode_symb($bighash{'map_id_'.$mapid},
6884: $resid,$thisfn);
1.39 www 6885: }
6886: }
1.191 harris41 6887: }
1.39 www 6888: if ($realpossible!=1) { $syval=''; }
1.249 www 6889: } else {
6890: $syval='';
1.37 www 6891: }
6892: }
6893: untie(%bighash)
1.481 raeburn 6894: }
1.31 www 6895: }
1.62 www 6896: if ($syval) {
1.620 albertel 6897: return $env{$cache_str}=$syval;
1.62 www 6898: }
1.31 www 6899: }
1.44 www 6900: &appenv('request.ambiguous' => $thisfn);
1.620 albertel 6901: return $env{$cache_str}='';
1.31 www 6902: }
6903:
6904: # ---------------------------------------------------------- Return random seed
6905:
1.32 www 6906: sub numval {
6907: my $txt=shift;
6908: $txt=~tr/A-J/0-9/;
6909: $txt=~tr/a-j/0-9/;
6910: $txt=~tr/K-T/0-9/;
6911: $txt=~tr/k-t/0-9/;
6912: $txt=~tr/U-Z/0-5/;
6913: $txt=~tr/u-z/0-5/;
6914: $txt=~s/\D//g;
1.564 albertel 6915: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 6916: return int($txt);
1.368 albertel 6917: }
6918:
1.484 albertel 6919: sub numval2 {
6920: my $txt=shift;
6921: $txt=~tr/A-J/0-9/;
6922: $txt=~tr/a-j/0-9/;
6923: $txt=~tr/K-T/0-9/;
6924: $txt=~tr/k-t/0-9/;
6925: $txt=~tr/U-Z/0-5/;
6926: $txt=~tr/u-z/0-5/;
6927: $txt=~s/\D//g;
6928: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6929: my $total;
6930: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 6931: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 6932: return int($total);
6933: }
6934:
1.575 albertel 6935: sub numval3 {
6936: use integer;
6937: my $txt=shift;
6938: $txt=~tr/A-J/0-9/;
6939: $txt=~tr/a-j/0-9/;
6940: $txt=~tr/K-T/0-9/;
6941: $txt=~tr/k-t/0-9/;
6942: $txt=~tr/U-Z/0-5/;
6943: $txt=~tr/u-z/0-5/;
6944: $txt=~s/\D//g;
6945: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
6946: my $total;
6947: foreach my $val (@txts) { $total+=$val; }
6948: if ($_64bit) { $total=(($total<<32)>>32); }
6949: return $total;
6950: }
6951:
1.675 albertel 6952: sub digest {
6953: my ($data)=@_;
6954: my $digest=&Digest::MD5::md5($data);
6955: my ($a,$b,$c,$d)=unpack("iiii",$digest);
6956: my ($e,$f);
6957: {
6958: use integer;
6959: $e=($a+$b);
6960: $f=($c+$d);
6961: if ($_64bit) {
6962: $e=(($e<<32)>>32);
6963: $f=(($f<<32)>>32);
6964: }
6965: }
6966: if (wantarray) {
6967: return ($e,$f);
6968: } else {
6969: my $g;
6970: {
6971: use integer;
6972: $g=($e+$f);
6973: if ($_64bit) {
6974: $g=(($g<<32)>>32);
6975: }
6976: }
6977: return $g;
6978: }
6979: }
6980:
1.368 albertel 6981: sub latest_rnd_algorithm_id {
1.675 albertel 6982: return '64bit5';
1.366 albertel 6983: }
1.32 www 6984:
1.503 albertel 6985: sub get_rand_alg {
6986: my ($courseid)=@_;
1.790 albertel 6987: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 6988: if ($courseid) {
1.620 albertel 6989: return $env{"course.$courseid.rndseed"};
1.503 albertel 6990: }
6991: return &latest_rnd_algorithm_id();
6992: }
6993:
1.562 albertel 6994: sub validCODE {
6995: my ($CODE)=@_;
6996: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
6997: return 0;
6998: }
6999:
1.491 albertel 7000: sub getCODE {
1.620 albertel 7001: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 7002: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7003: defined($Apache::lonhomework::parsing_a_task) ) &&
7004: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 7005: return $Apache::lonhomework::history{'resource.CODE'};
7006: }
7007: return undef;
7008: }
7009:
1.31 www 7010: sub rndseed {
1.155 albertel 7011: my ($symb,$courseid,$domain,$username)=@_;
1.790 albertel 7012: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155 albertel 7013: if (!$symb) {
1.366 albertel 7014: unless ($symb=$wsymb) { return time; }
7015: }
7016: if (!$courseid) { $courseid=$wcourseid; }
7017: if (!$domain) { $domain=$wdomain; }
7018: if (!$username) { $username=$wusername }
1.503 albertel 7019: my $which=&get_rand_alg();
1.803 albertel 7020:
1.491 albertel 7021: if (defined(&getCODE())) {
1.675 albertel 7022: if ($which eq '64bit5') {
7023: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7024: } elsif ($which eq '64bit4') {
1.575 albertel 7025: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7026: } else {
7027: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7028: }
1.675 albertel 7029: } elsif ($which eq '64bit5') {
7030: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 7031: } elsif ($which eq '64bit4') {
7032: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 7033: } elsif ($which eq '64bit3') {
7034: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 7035: } elsif ($which eq '64bit2') {
7036: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 7037: } elsif ($which eq '64bit') {
7038: return &rndseed_64bit($symb,$courseid,$domain,$username);
7039: }
7040: return &rndseed_32bit($symb,$courseid,$domain,$username);
7041: }
7042:
7043: sub rndseed_32bit {
7044: my ($symb,$courseid,$domain,$username)=@_;
7045: {
7046: use integer;
7047: my $symbchck=unpack("%32C*",$symb) << 27;
7048: my $symbseed=numval($symb) << 22;
7049: my $namechck=unpack("%32C*",$username) << 17;
7050: my $nameseed=numval($username) << 12;
7051: my $domainseed=unpack("%32C*",$domain) << 7;
7052: my $courseseed=unpack("%32C*",$courseid);
7053: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 7054: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7055: #&logthis("rndseed :$num:$symb");
1.564 albertel 7056: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 7057: return $num;
7058: }
7059: }
7060:
7061: sub rndseed_64bit {
7062: my ($symb,$courseid,$domain,$username)=@_;
7063: {
7064: use integer;
7065: my $symbchck=unpack("%32S*",$symb) << 21;
7066: my $symbseed=numval($symb) << 10;
7067: my $namechck=unpack("%32S*",$username);
7068:
7069: my $nameseed=numval($username) << 21;
7070: my $domainseed=unpack("%32S*",$domain) << 10;
7071: my $courseseed=unpack("%32S*",$courseid);
7072:
7073: my $num1=$symbchck+$symbseed+$namechck;
7074: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7075: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7076: #&logthis("rndseed :$num:$symb");
1.564 albertel 7077: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 7078: return "$num1,$num2";
1.155 albertel 7079: }
1.366 albertel 7080: }
7081:
1.443 albertel 7082: sub rndseed_64bit2 {
7083: my ($symb,$courseid,$domain,$username)=@_;
7084: {
7085: use integer;
7086: # strings need to be an even # of cahracters long, it it is odd the
7087: # last characters gets thrown away
7088: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7089: my $symbseed=numval($symb) << 10;
7090: my $namechck=unpack("%32S*",$username.' ');
7091:
7092: my $nameseed=numval($username) << 21;
1.501 albertel 7093: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7094: my $courseseed=unpack("%32S*",$courseid.' ');
7095:
7096: my $num1=$symbchck+$symbseed+$namechck;
7097: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7098: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7099: #&logthis("rndseed :$num:$symb");
1.803 albertel 7100: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 7101: return "$num1,$num2";
7102: }
7103: }
7104:
7105: sub rndseed_64bit3 {
7106: my ($symb,$courseid,$domain,$username)=@_;
7107: {
7108: use integer;
7109: # strings need to be an even # of cahracters long, it it is odd the
7110: # last characters gets thrown away
7111: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7112: my $symbseed=numval2($symb) << 10;
7113: my $namechck=unpack("%32S*",$username.' ');
7114:
7115: my $nameseed=numval2($username) << 21;
1.443 albertel 7116: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7117: my $courseseed=unpack("%32S*",$courseid.' ');
7118:
7119: my $num1=$symbchck+$symbseed+$namechck;
7120: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7121: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7122: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 7123: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7124:
1.503 albertel 7125: return "$num1:$num2";
1.443 albertel 7126: }
7127: }
7128:
1.575 albertel 7129: sub rndseed_64bit4 {
7130: my ($symb,$courseid,$domain,$username)=@_;
7131: {
7132: use integer;
7133: # strings need to be an even # of cahracters long, it it is odd the
7134: # last characters gets thrown away
7135: my $symbchck=unpack("%32S*",$symb.' ') << 21;
7136: my $symbseed=numval3($symb) << 10;
7137: my $namechck=unpack("%32S*",$username.' ');
7138:
7139: my $nameseed=numval3($username) << 21;
7140: my $domainseed=unpack("%32S*",$domain.' ') << 10;
7141: my $courseseed=unpack("%32S*",$courseid.' ');
7142:
7143: my $num1=$symbchck+$symbseed+$namechck;
7144: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 7145: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7146: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 7147: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7148:
7149: return "$num1:$num2";
7150: }
7151: }
7152:
1.675 albertel 7153: sub rndseed_64bit5 {
7154: my ($symb,$courseid,$domain,$username)=@_;
7155: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
7156: return "$num1:$num2";
7157: }
7158:
1.366 albertel 7159: sub rndseed_CODE_64bit {
7160: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 7161: {
1.366 albertel 7162: use integer;
1.443 albertel 7163: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 7164: my $symbseed=numval2($symb);
1.491 albertel 7165: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7166: my $CODEseed=numval(&getCODE());
1.443 albertel 7167: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 7168: my $num1=$symbseed+$CODEchck;
7169: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7170: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7171: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 7172: if ($_64bit) { $num1=(($num1<<32)>>32); }
7173: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 7174: return "$num1:$num2";
1.366 albertel 7175: }
7176: }
7177:
1.575 albertel 7178: sub rndseed_CODE_64bit4 {
7179: my ($symb,$courseid,$domain,$username)=@_;
7180: {
7181: use integer;
7182: my $symbchck=unpack("%32S*",$symb.' ') << 16;
7183: my $symbseed=numval3($symb);
7184: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
7185: my $CODEseed=numval3(&getCODE());
7186: my $courseseed=unpack("%32S*",$courseid.' ');
7187: my $num1=$symbseed+$CODEchck;
7188: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 7189: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
7190: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 7191: if ($_64bit) { $num1=(($num1<<32)>>32); }
7192: if ($_64bit) { $num2=(($num2<<32)>>32); }
7193: return "$num1:$num2";
7194: }
7195: }
7196:
1.675 albertel 7197: sub rndseed_CODE_64bit5 {
7198: my ($symb,$courseid,$domain,$username)=@_;
7199: my $code = &getCODE();
7200: my ($num1,$num2)=&digest("$symb,$courseid,$code");
7201: return "$num1:$num2";
7202: }
7203:
1.366 albertel 7204: sub setup_random_from_rndseed {
7205: my ($rndseed)=@_;
1.503 albertel 7206: if ($rndseed =~/([,:])/) {
7207: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 7208: &Math::Random::random_set_seed(abs($num1),abs($num2));
7209: } else {
7210: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 7211: }
1.36 albertel 7212: }
7213:
1.474 albertel 7214: sub latest_receipt_algorithm_id {
1.835 albertel 7215: return 'receipt3';
1.474 albertel 7216: }
7217:
1.480 www 7218: sub recunique {
7219: my $fucourseid=shift;
7220: my $unique;
1.835 albertel 7221: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
7222: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7223: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 7224: } else {
7225: $unique=$perlvar{'lonReceipt'};
7226: }
7227: return unpack("%32C*",$unique);
7228: }
7229:
7230: sub recprefix {
7231: my $fucourseid=shift;
7232: my $prefix;
1.835 albertel 7233: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
7234: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 7235: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 7236: } else {
7237: $prefix=$perlvar{'lonHostID'};
7238: }
7239: return unpack("%32C*",$prefix);
7240: }
7241:
1.76 www 7242: sub ireceipt {
1.474 albertel 7243: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 7244:
7245: my $return =&recprefix($fucourseid).'-';
7246:
7247: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
7248: $env{'request.state'} eq 'construct') {
7249: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
7250: return $return;
7251: }
7252:
1.76 www 7253: my $cuname=unpack("%32C*",$funame);
7254: my $cudom=unpack("%32C*",$fudom);
7255: my $cucourseid=unpack("%32C*",$fucourseid);
7256: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 7257: my $cunique=&recunique($fucourseid);
1.474 albertel 7258: my $cpart=unpack("%32S*",$part);
1.835 albertel 7259: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
7260:
1.790 albertel 7261: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 7262:
7263: $return.= ($cunique%$cuname+
7264: $cunique%$cudom+
7265: $cusymb%$cuname+
7266: $cusymb%$cudom+
7267: $cucourseid%$cuname+
7268: $cucourseid%$cudom+
7269: $cpart%$cuname+
7270: $cpart%$cudom);
7271: } else {
7272: $return.= ($cunique%$cuname+
7273: $cunique%$cudom+
7274: $cusymb%$cuname+
7275: $cusymb%$cudom+
7276: $cucourseid%$cuname+
7277: $cucourseid%$cudom);
7278: }
7279: return $return;
1.76 www 7280: }
7281:
7282: sub receipt {
1.474 albertel 7283: my ($part)=@_;
1.790 albertel 7284: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 7285: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 7286: }
1.260 ng 7287:
1.790 albertel 7288: sub whichuser {
7289: my ($passedsymb)=@_;
7290: my ($symb,$courseid,$domain,$name,$publicuser);
7291: if (defined($env{'form.grade_symb'})) {
7292: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
7293: my $allowed=&allowed('vgr',$tmp_courseid);
7294: if (!$allowed &&
7295: exists($env{'request.course.sec'}) &&
7296: $env{'request.course.sec'} !~ /^\s*$/) {
7297: $allowed=&allowed('vgr',$tmp_courseid.
7298: '/'.$env{'request.course.sec'});
7299: }
7300: if ($allowed) {
7301: ($symb)=&get_env_multiple('form.grade_symb');
7302: $courseid=$tmp_courseid;
7303: ($domain)=&get_env_multiple('form.grade_domain');
7304: ($name)=&get_env_multiple('form.grade_username');
7305: return ($symb,$courseid,$domain,$name,$publicuser);
7306: }
7307: }
7308: if (!$passedsymb) {
7309: $symb=&symbread();
7310: } else {
7311: $symb=$passedsymb;
7312: }
7313: $courseid=$env{'request.course.id'};
7314: $domain=$env{'user.domain'};
7315: $name=$env{'user.name'};
7316: if ($name eq 'public' && $domain eq 'public') {
7317: if (!defined($env{'form.username'})) {
7318: $env{'form.username'}.=time.rand(10000000);
7319: }
7320: $name.=$env{'form.username'};
7321: }
7322: return ($symb,$courseid,$domain,$name,$publicuser);
7323:
7324: }
7325:
1.36 albertel 7326: # ------------------------------------------------------------ Serves up a file
1.472 albertel 7327: # returns either the contents of the file or
7328: # -1 if the file doesn't exist
1.481 raeburn 7329: #
7330: # if the target is a file that was uploaded via DOCS,
7331: # a check will be made to see if a current copy exists on the local server,
7332: # if it does this will be served, otherwise a copy will be retrieved from
7333: # the home server for the course and stored in /home/httpd/html/userfiles on
7334: # the local server.
1.472 albertel 7335:
1.36 albertel 7336: sub getfile {
1.538 albertel 7337: my ($file) = @_;
1.609 banghart 7338: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 7339: &repcopy($file);
7340: return &readfile($file);
7341: }
7342:
7343: sub repcopy_userfile {
7344: my ($file)=@_;
1.609 banghart 7345: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 7346: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 7347: my ($cdom,$cnum,$filename) =
1.811 albertel 7348: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 7349: my $uri="/uploaded/$cdom/$cnum/$filename";
7350: if (-e "$file") {
1.828 www 7351: # we already have a local copy, check it out
1.538 albertel 7352: my @fileinfo = stat($file);
1.828 www 7353: my $rtncode;
7354: my $info;
1.538 albertel 7355: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 7356: if ($lwpresp ne 'ok') {
1.828 www 7357: # there is no such file anymore, even though we had a local copy
1.482 albertel 7358: if ($rtncode eq '404') {
1.538 albertel 7359: unlink($file);
1.482 albertel 7360: }
7361: return -1;
7362: }
7363: if ($info < $fileinfo[9]) {
1.828 www 7364: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 7365: return 'ok';
1.828 www 7366: } else {
7367: # the file is outdated, get rid of it
7368: unlink($file);
1.482 albertel 7369: }
1.828 www 7370: }
7371: # one way or the other, at this point, we don't have the file
7372: # construct the correct path for the file
7373: my @parts = ($cdom,$cnum);
7374: if ($filename =~ m|^(.+)/[^/]+$|) {
7375: push @parts, split(/\//,$1);
7376: }
7377: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
7378: foreach my $part (@parts) {
7379: $path .= '/'.$part;
7380: if (!-e $path) {
7381: mkdir($path,0770);
1.482 albertel 7382: }
7383: }
1.828 www 7384: # now the path exists for sure
7385: # get a user agent
7386: my $ua=new LWP::UserAgent;
7387: my $transferfile=$file.'.in.transfer';
7388: # FIXME: this should flock
7389: if (-e $transferfile) { return 'ok'; }
7390: my $request;
7391: $uri=~s/^\///;
1.838 albertel 7392: $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828 www 7393: my $response=$ua->request($request,$transferfile);
7394: # did it work?
7395: if ($response->is_error()) {
7396: unlink($transferfile);
7397: &logthis("Userfile repcopy failed for $uri");
7398: return -1;
7399: }
7400: # worked, rename the transfer file
7401: rename($transferfile,$file);
1.607 raeburn 7402: return 'ok';
1.481 raeburn 7403: }
7404:
1.517 albertel 7405: sub tokenwrapper {
7406: my $uri=shift;
1.552 albertel 7407: $uri=~s|^http\://([^/]+)||;
7408: $uri=~s|^/||;
1.620 albertel 7409: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 7410: my $token=$1;
1.552 albertel 7411: my (undef,$udom,$uname,$file)=split('/',$uri,4);
7412: if ($udom && $uname && $file) {
7413: $file=~s|(\?\.*)*$||;
1.620 albertel 7414: &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838 albertel 7415: return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517 albertel 7416: (($uri=~/\?/)?'&':'?').'token='.$token.
7417: '&tokenissued='.$perlvar{'lonHostID'};
7418: } else {
7419: return '/adm/notfound.html';
7420: }
7421: }
7422:
1.828 www 7423: # call with reqtype HEAD: get last modification time
7424: # call with reqtype GET: get the file contents
7425: # Do not call this with reqtype GET for large files! It loads everything into memory
7426: #
1.481 raeburn 7427: sub getuploaded {
7428: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
7429: $uri=~s/^\///;
1.838 albertel 7430: $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481 raeburn 7431: my $ua=new LWP::UserAgent;
7432: my $request=new HTTP::Request($reqtype,$uri);
7433: my $response=$ua->request($request);
7434: $$rtncode = $response->code;
1.482 albertel 7435: if (! $response->is_success()) {
7436: return 'failed';
7437: }
7438: if ($reqtype eq 'HEAD') {
1.486 www 7439: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 7440: } elsif ($reqtype eq 'GET') {
7441: $$info = $response->content;
1.472 albertel 7442: }
1.482 albertel 7443: return 'ok';
1.36 albertel 7444: }
7445:
1.481 raeburn 7446: sub readfile {
7447: my $file = shift;
7448: if ( (! -e $file ) || ($file eq '') ) { return -1; };
7449: my $fh;
7450: open($fh,"<$file");
7451: my $a='';
1.800 albertel 7452: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 7453: return $a;
7454: }
7455:
1.36 albertel 7456: sub filelocation {
1.590 banghart 7457: my ($dir,$file) = @_;
7458: my $location;
7459: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 7460:
7461: if ($file =~ m-^/adm/-) {
7462: $file=~s-^/adm/wrapper/-/-;
7463: $file=~s-^/adm/coursedocs/showdoc/-/-;
7464: }
1.590 banghart 7465: if ($file=~m:^/~:) { # is a contruction space reference
7466: $location = $file;
7467: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 7468: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 7469: # is a correct contruction space reference
7470: $location = $file;
1.609 banghart 7471: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 7472: my ($udom,$uname,$filename)=
1.811 albertel 7473: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 7474: my $home=&homeserver($uname,$udom);
7475: my $is_me=0;
7476: my @ids=¤t_machine_ids();
7477: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
7478: if ($is_me) {
1.740 www 7479: $location=&propath($udom,$uname).
1.590 banghart 7480: '/userfiles/'.$filename;
7481: } else {
7482: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
7483: $udom.'/'.$uname.'/'.$filename;
7484: }
7485: } else {
7486: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
7487: $file=~s:^/res/:/:;
7488: if ( !( $file =~ m:^/:) ) {
7489: $location = $dir. '/'.$file;
7490: } else {
7491: $location = '/home/httpd/html/res'.$file;
7492: }
1.59 albertel 7493: }
1.590 banghart 7494: $location=~s://+:/:g; # remove duplicate /
7495: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
7496: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
7497: return $location;
1.46 www 7498: }
1.36 albertel 7499:
1.46 www 7500: sub hreflocation {
7501: my ($dir,$file)=@_;
1.460 albertel 7502: unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666 albertel 7503: $file=filelocation($dir,$file);
1.700 albertel 7504: } elsif ($file=~m-^/adm/-) {
7505: $file=~s-^/adm/wrapper/-/-;
7506: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 7507: }
7508: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
7509: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 7510: } elsif ($file=~m-/home/($match_username)/public_html/-) {
7511: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 7512: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 7513: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 7514: -/uploaded/$1/$2/-x;
1.46 www 7515: }
1.462 albertel 7516: return $file;
1.465 albertel 7517: }
7518:
7519: sub current_machine_domains {
1.853 albertel 7520: return &machine_domains(&hostname($perlvar{'lonHostID'}));
7521: }
7522:
7523: sub machine_domains {
7524: my ($hostname) = @_;
1.465 albertel 7525: my @domains;
1.838 albertel 7526: my %hostname = &all_hostnames();
1.465 albertel 7527: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7528: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7529: if ($hostname eq $name) {
1.844 albertel 7530: push(@domains,&host_domain($id));
1.465 albertel 7531: }
7532: }
7533: return @domains;
7534: }
7535:
7536: sub current_machine_ids {
1.853 albertel 7537: return &machine_ids(&hostname($perlvar{'lonHostID'}));
7538: }
7539:
7540: sub machine_ids {
7541: my ($hostname) = @_;
7542: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 7543: my @ids;
1.838 albertel 7544: my %hostname = &all_hostnames();
1.465 albertel 7545: while( my($id, $name) = each(%hostname)) {
1.467 matthew 7546: # &logthis("-$id-$name-$hostname-");
1.465 albertel 7547: if ($hostname eq $name) {
7548: push(@ids,$id);
7549: }
7550: }
7551: return @ids;
1.31 www 7552: }
7553:
1.824 raeburn 7554: sub additional_machine_domains {
7555: my @domains;
7556: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
7557: while( my $line = <$fh>) {
7558: $line =~ s/\s//g;
7559: push(@domains,$line);
7560: }
7561: return @domains;
7562: }
7563:
7564: sub default_login_domain {
7565: my $domain = $perlvar{'lonDefDomain'};
7566: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
7567: foreach my $posdom (¤t_machine_domains(),
7568: &additional_machine_domains()) {
7569: if (lc($posdom) eq lc($testdomain)) {
7570: $domain=$posdom;
7571: last;
7572: }
7573: }
7574: return $domain;
7575: }
7576:
1.31 www 7577: # ------------------------------------------------------------- Declutters URLs
7578:
7579: sub declutter {
7580: my $thisfn=shift;
1.569 albertel 7581: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 7582: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 7583: $thisfn=~s/^\///;
1.697 albertel 7584: $thisfn=~s|^adm/wrapper/||;
7585: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 7586: $thisfn=~s/^res\///;
1.235 www 7587: $thisfn=~s/\?.+$//;
1.268 www 7588: return $thisfn;
7589: }
7590:
7591: # ------------------------------------------------------------- Clutter up URLs
7592:
7593: sub clutter {
7594: my $thisfn='/'.&declutter(shift);
1.609 banghart 7595: unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) {
1.270 www 7596: $thisfn='/res'.$thisfn;
7597: }
1.694 albertel 7598: if ($thisfn !~m|/adm|) {
1.695 albertel 7599: if ($thisfn =~ m|/ext/|) {
1.694 albertel 7600: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 7601: } else {
7602: my ($ext) = ($thisfn =~ /\.(\w+)$/);
7603: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 7604: if ($embstyle eq 'ssi'
7605: || ($embstyle eq 'hdn')
7606: || ($embstyle eq 'rat')
7607: || ($embstyle eq 'prv')
7608: || ($embstyle eq 'ign')) {
7609: #do nothing with these
7610: } elsif (($embstyle eq 'img')
1.695 albertel 7611: || ($embstyle eq 'emb')
7612: || ($embstyle eq 'wrp')) {
7613: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 7614: } elsif ($embstyle eq 'unk'
7615: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 7616: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 7617: } else {
1.718 www 7618: # &logthis("Got a blank emb style");
1.695 albertel 7619: }
1.694 albertel 7620: }
7621: }
1.31 www 7622: return $thisfn;
1.12 www 7623: }
7624:
1.787 albertel 7625: sub clutter_with_no_wrapper {
7626: my $uri = &clutter(shift);
7627: if ($uri =~ m-^/adm/-) {
7628: $uri =~ s-^/adm/wrapper/-/-;
7629: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
7630: }
7631: return $uri;
7632: }
7633:
1.557 albertel 7634: sub freeze_escape {
7635: my ($value)=@_;
7636: if (ref($value)) {
7637: $value=&nfreeze($value);
7638: return '__FROZEN__'.&escape($value);
7639: }
7640: return &escape($value);
7641: }
7642:
1.11 www 7643:
1.557 albertel 7644: sub thaw_unescape {
7645: my ($value)=@_;
7646: if ($value =~ /^__FROZEN__/) {
7647: substr($value,0,10,undef);
7648: $value=&unescape($value);
7649: return &thaw($value);
7650: }
7651: return &unescape($value);
7652: }
7653:
1.436 albertel 7654: sub correct_line_ends {
7655: my ($result)=@_;
7656: $$result =~s/\r\n/\n/mg;
7657: $$result =~s/\r/\n/mg;
1.415 albertel 7658: }
1.1 albertel 7659: # ================================================================ Main Program
7660:
1.184 www 7661: sub goodbye {
1.204 albertel 7662: &logthis("Starting Shut down");
1.443 albertel 7663: #not converted to using infrastruture and probably shouldn't be
1.870 ! albertel 7664: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 7665: #converted
1.599 albertel 7666: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 ! albertel 7667: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
! 7668: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
! 7669: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 7670: #1.1 only
1.870 ! albertel 7671: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
! 7672: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
! 7673: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
! 7674: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
! 7675: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 7676: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
7677: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 7678: &flushcourselogs();
7679: &logthis("Shutting down");
7680: }
7681:
1.852 albertel 7682: sub get_dns {
1.869 albertel 7683: my ($url,$func,$ignore_cache) = @_;
7684: if (!$ignore_cache) {
7685: my ($content,$cached)=
7686: &Apache::lonnet::is_cached_new('dns',$url);
7687: if ($cached) {
7688: &$func($content);
7689: return;
7690: }
7691: }
7692:
7693: my %alldns;
1.852 albertel 7694: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7695: foreach my $dns (<$config>) {
7696: next if ($dns !~ /^\^(\S*)/x);
1.869 albertel 7697: $alldns{$1} = 1;
7698: }
7699: while (%alldns) {
7700: my ($dns) = keys(%alldns);
7701: delete($alldns{$dns});
1.852 albertel 7702: my $ua=new LWP::UserAgent;
7703: my $request=new HTTP::Request('GET',"http://$dns$url");
7704: my $response=$ua->request($request);
7705: next if ($response->is_error());
7706: my @content = split("\n",$response->content);
1.869 albertel 7707: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 7708: &$func(\@content);
1.869 albertel 7709: return;
1.852 albertel 7710: }
7711: close($config);
1.869 albertel 7712: &logthis("unable to contact DNS defaulting to on disk file\n");
7713: open($config,"<$perlvar{'lonTabDir'}/dns_hosts.tab");
7714: my @content = <$config>;
7715: &$func(\@content);
7716: return;
1.852 albertel 7717: }
1.327 albertel 7718: # ------------------------------------------------------------ Read domain file
7719: {
1.852 albertel 7720: my $loaded;
1.846 albertel 7721: my %domain;
7722:
1.852 albertel 7723: sub parse_domain_tab {
7724: my ($lines) = @_;
7725: foreach my $line (@$lines) {
7726: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 7727:
1.846 albertel 7728: chomp($line);
1.852 albertel 7729: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 7730: my %this_domain;
7731: foreach my $field ('description', 'auth_def', 'auth_arg_def',
7732: 'lang_def', 'city', 'longi', 'lati',
7733: 'primary') {
7734: $this_domain{$field} = shift(@elements);
7735: }
7736: $domain{$name} = \%this_domain;
1.852 albertel 7737: }
7738: }
1.864 albertel 7739:
7740: sub reset_domain_info {
7741: undef($loaded);
7742: undef(%domain);
7743: }
7744:
1.852 albertel 7745: sub load_domain_tab {
1.869 albertel 7746: my ($ignore_cache) = @_;
7747: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 7748: my $fh;
7749: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
7750: my @lines = <$fh>;
7751: &parse_domain_tab(\@lines);
1.448 albertel 7752: }
1.852 albertel 7753: close($fh);
7754: $loaded = 1;
1.327 albertel 7755: }
1.846 albertel 7756:
7757: sub domain {
1.852 albertel 7758: &load_domain_tab() if (!$loaded);
7759:
1.846 albertel 7760: my ($name,$what) = @_;
7761: return if ( !exists($domain{$name}) );
7762:
7763: if (!$what) {
7764: return $domain{$name}{'description'};
7765: }
7766: return $domain{$name}{$what};
7767: }
1.327 albertel 7768: }
7769:
7770:
1.1 albertel 7771: # ------------------------------------------------------------- Read hosts file
7772: {
1.838 albertel 7773: my %hostname;
1.844 albertel 7774: my %hostdom;
1.845 albertel 7775: my %libserv;
1.852 albertel 7776: my $loaded;
7777:
7778: sub parse_hosts_tab {
7779: my ($file) = @_;
7780: foreach my $configline (@$file) {
7781: next if ($configline =~ /^(\#|\s*$ )/x);
7782: next if ($configline =~ /^\^/);
7783: chomp($configline);
7784: my ($id,$domain,$role,$name)=split(/:/,$configline);
7785: $name=~s/\s//g;
7786: if ($id && $domain && $role && $name) {
7787: $hostname{$id}=$name;
7788: $hostdom{$id}=$domain;
7789: if ($role eq 'library') { $libserv{$id}=$name; }
7790: }
7791: }
7792: }
1.864 albertel 7793:
7794: sub reset_hosts_info {
7795: &reset_domain_info();
7796: &reset_hosts_ip_info();
7797: undef(%hostname);
7798: undef(%hostdom);
7799: undef(%libserv);
7800: undef($loaded);
7801: }
1.1 albertel 7802:
1.852 albertel 7803: sub load_hosts_tab {
1.869 albertel 7804: my ($ignore_cache) = @_;
7805: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 7806: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
7807: my @config = <$config>;
7808: &parse_hosts_tab(\@config);
7809: close($config);
7810: $loaded=1;
1.1 albertel 7811: }
1.852 albertel 7812:
1.838 albertel 7813: sub hostname {
1.852 albertel 7814: &load_hosts_tab() if (!$loaded);
7815:
1.838 albertel 7816: my ($lonid) = @_;
7817: return $hostname{$lonid};
7818: }
1.845 albertel 7819:
1.838 albertel 7820: sub all_hostnames {
1.852 albertel 7821: &load_hosts_tab() if (!$loaded);
7822:
1.838 albertel 7823: return %hostname;
7824: }
1.845 albertel 7825:
7826: sub is_library {
1.852 albertel 7827: &load_hosts_tab() if (!$loaded);
7828:
1.845 albertel 7829: return exists($libserv{$_[0]});
7830: }
7831:
7832: sub all_library {
1.852 albertel 7833: &load_hosts_tab() if (!$loaded);
7834:
1.845 albertel 7835: return %libserv;
7836: }
7837:
1.841 albertel 7838: sub get_servers {
1.852 albertel 7839: &load_hosts_tab() if (!$loaded);
7840:
1.841 albertel 7841: my ($domain,$type) = @_;
7842: my %possible_hosts = ($type eq 'library') ? %libserv
7843: : %hostname;
7844: my %result;
1.842 albertel 7845: if (ref($domain) eq 'ARRAY') {
7846: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 7847: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 7848: $result{$host} = $hostname;
7849: }
7850: }
7851: } else {
7852: while ( my ($host,$hostname) = each(%possible_hosts)) {
7853: if ($hostdom{$host} eq $domain) {
7854: $result{$host} = $hostname;
7855: }
1.841 albertel 7856: }
7857: }
7858: return %result;
7859: }
1.845 albertel 7860:
1.844 albertel 7861: sub host_domain {
1.852 albertel 7862: &load_hosts_tab() if (!$loaded);
7863:
1.844 albertel 7864: my ($lonid) = @_;
7865: return $hostdom{$lonid};
7866: }
7867:
1.841 albertel 7868: sub all_domains {
1.852 albertel 7869: &load_hosts_tab() if (!$loaded);
7870:
1.841 albertel 7871: my %seen;
7872: my @uniq = grep(!$seen{$_}++, values(%hostdom));
7873: return @uniq;
7874: }
1.1 albertel 7875: }
7876:
1.847 albertel 7877: {
7878: my %iphost;
1.856 albertel 7879: my %name_to_ip;
7880: my %lonid_to_ip;
1.869 albertel 7881:
7882: my %valid_ip;
7883: sub valid_ip {
7884: my ($ip) = @_;
7885: if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
7886: return 1;
7887: }
7888: my $name = gethostbyip($ip);
7889: my $lonid = &hostname($name);
7890: if (defined($lonid)) {
7891: $valid_ip{$ip} = $lonid;
7892: return 1;
7893: }
7894: my %iphosts = &get_iphost();
7895: if (ref($iphost{$ip})) {
7896: return 1;
7897: }
7898: }
7899:
1.847 albertel 7900: sub get_hosts_from_ip {
7901: my ($ip) = @_;
7902: my %iphosts = &get_iphost();
7903: if (ref($iphosts{$ip})) {
7904: return @{$iphosts{$ip}};
7905: }
7906: return;
1.839 albertel 7907: }
1.864 albertel 7908:
7909: sub reset_hosts_ip_info {
7910: undef(%iphost);
7911: undef(%name_to_ip);
7912: undef(%lonid_to_ip);
7913: }
1.856 albertel 7914:
7915: sub get_host_ip {
7916: my ($lonid) = @_;
7917: if (exists($lonid_to_ip{$lonid})) {
7918: return $lonid_to_ip{$lonid};
7919: }
7920: my $name=&hostname($lonid);
7921: my $ip = gethostbyname($name);
7922: return if (!$ip || length($ip) ne 4);
7923: $ip=inet_ntoa($ip);
7924: $name_to_ip{$name} = $ip;
7925: $lonid_to_ip{$lonid} = $ip;
7926: return $ip;
7927: }
1.847 albertel 7928:
7929: sub get_iphost {
1.869 albertel 7930: my ($ignore_cache) = @_;
7931: if (!$ignore_cache) {
7932: if (%iphost) {
7933: return %iphost;
7934: }
7935: my ($ip_info,$cached)=
7936: &Apache::lonnet::is_cached_new('iphost','iphost');
7937: if ($cached) {
7938: %iphost = %{$ip_info->[0]};
7939: %name_to_ip = %{$ip_info->[1]};
7940: %lonid_to_ip = %{$ip_info->[2]};
7941: return %iphost;
7942: }
7943: }
1.847 albertel 7944: my %hostname = &all_hostnames();
7945: foreach my $id (keys(%hostname)) {
1.864 albertel 7946: my $name=&hostname($id);
1.847 albertel 7947: my $ip;
7948: if (!exists($name_to_ip{$name})) {
7949: $ip = gethostbyname($name);
7950: if (!$ip || length($ip) ne 4) {
7951: &logthis("Skipping host $id name $name no IP found");
7952: next;
7953: }
7954: $ip=inet_ntoa($ip);
7955: $name_to_ip{$name} = $ip;
7956: } else {
7957: $ip = $name_to_ip{$name};
1.653 albertel 7958: }
1.856 albertel 7959: $lonid_to_ip{$id} = $ip;
1.847 albertel 7960: push(@{$iphost{$ip}},$id);
1.598 albertel 7961: }
1.869 albertel 7962: &Apache::lonnet::do_cache_new('iphost','iphost',
7963: [\%iphost,\%name_to_ip,\%lonid_to_ip],
7964: 24*60*60);
7965:
1.847 albertel 7966: return %iphost;
1.598 albertel 7967: }
7968: }
7969:
1.862 albertel 7970: BEGIN {
7971:
7972: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
7973: unless ($readit) {
7974: {
7975: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
7976: %perlvar = (%perlvar,%{$configvars});
7977: }
7978:
7979:
1.1 albertel 7980: # ------------------------------------------------------ Read spare server file
7981: {
1.448 albertel 7982: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 7983:
7984: while (my $configline=<$config>) {
7985: chomp($configline);
1.284 matthew 7986: if ($configline) {
1.784 albertel 7987: my ($host,$type) = split(':',$configline,2);
1.785 albertel 7988: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 7989: push(@{ $spareid{$type} }, $host);
1.1 albertel 7990: }
7991: }
1.448 albertel 7992: close($config);
1.1 albertel 7993: }
1.11 www 7994: # ------------------------------------------------------------ Read permissions
7995: {
1.448 albertel 7996: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 7997:
7998: while (my $configline=<$config>) {
1.448 albertel 7999: chomp($configline);
8000: if ($configline) {
8001: my ($role,$perm)=split(/ /,$configline);
8002: if ($perm ne '') { $pr{$role}=$perm; }
8003: }
1.11 www 8004: }
1.448 albertel 8005: close($config);
1.11 www 8006: }
8007:
8008: # -------------------------------------------- Read plain texts for permissions
8009: {
1.448 albertel 8010: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 8011:
8012: while (my $configline=<$config>) {
1.448 albertel 8013: chomp($configline);
8014: if ($configline) {
1.742 raeburn 8015: my ($short,@plain)=split(/:/,$configline);
8016: %{$prp{$short}} = ();
8017: if (@plain > 0) {
8018: $prp{$short}{'std'} = $plain[0];
8019: for (my $i=1; $i<@plain; $i++) {
8020: $prp{$short}{'alt'.$i} = $plain[$i];
8021: }
8022: }
1.448 albertel 8023: }
1.135 www 8024: }
1.448 albertel 8025: close($config);
1.135 www 8026: }
8027:
8028: # ---------------------------------------------------------- Read package table
8029: {
1.448 albertel 8030: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 8031:
8032: while (my $configline=<$config>) {
1.483 albertel 8033: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 8034: chomp($configline);
8035: my ($short,$plain)=split(/:/,$configline);
8036: my ($pack,$name)=split(/\&/,$short);
8037: if ($plain ne '') {
8038: $packagetab{$pack.'&'.$name.'&name'}=$name;
8039: $packagetab{$short}=$plain;
8040: }
1.11 www 8041: }
1.448 albertel 8042: close($config);
1.329 matthew 8043: }
8044:
8045: # ------------- set up temporary directory
8046: {
8047: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
8048:
1.11 www 8049: }
8050:
1.794 albertel 8051: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
8052: 'compress_threshold'=> 20_000,
8053: });
1.185 www 8054:
1.281 www 8055: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 8056: $dumpcount=0;
1.22 www 8057:
1.163 harris41 8058: &logtouch();
1.672 albertel 8059: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 8060: $readit=1;
1.564 albertel 8061: {
8062: use integer;
8063: my $test=(2**32)+1;
1.568 albertel 8064: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 8065: &logthis(" Detected 64bit platform ($_64bit)");
8066: }
1.195 www 8067: }
1.1 albertel 8068: }
1.179 www 8069:
1.1 albertel 8070: 1;
1.191 harris41 8071: __END__
8072:
1.243 albertel 8073: =pod
8074:
1.191 harris41 8075: =head1 NAME
8076:
1.243 albertel 8077: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 8078:
8079: =head1 SYNOPSIS
8080:
1.243 albertel 8081: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 8082:
8083: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
8084:
1.243 albertel 8085: Common parameters:
8086:
8087: =over 4
8088:
8089: =item *
8090:
8091: $uname : an internal username (if $cname expecting a course Id specifically)
8092:
8093: =item *
8094:
8095: $udom : a domain (if $cdom expecting a course's domain specifically)
8096:
8097: =item *
8098:
8099: $symb : a resource instance identifier
8100:
8101: =item *
8102:
8103: $namespace : the name of a .db file that contains the data needed or
8104: being set.
8105:
8106: =back
8107:
1.394 bowersj2 8108: =head1 OVERVIEW
1.191 harris41 8109:
1.394 bowersj2 8110: lonnet provides subroutines which interact with the
8111: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
8112: about classes, users, and resources.
1.243 albertel 8113:
8114: For many of these objects you can also use this to store data about
8115: them or modify them in various ways.
1.191 harris41 8116:
1.394 bowersj2 8117: =head2 Symbs
1.191 harris41 8118:
1.394 bowersj2 8119: To identify a specific instance of a resource, LON-CAPA uses symbols
8120: or "symbs"X<symb>. These identifiers are built from the URL of the
8121: map, the resource number of the resource in the map, and the URL of
8122: the resource itself. The latter is somewhat redundant, but might help
8123: if maps change.
8124:
8125: An example is
8126:
8127: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
8128:
8129: The respective map entry is
8130:
8131: <resource id="19" src="/res/msu/korte/tests/part12.problem"
8132: title="Problem 2">
8133: </resource>
8134:
8135: Symbs are used by the random number generator, as well as to store and
8136: restore data specific to a certain instance of for example a problem.
8137:
8138: =head2 Storing And Retrieving Data
8139:
8140: X<store()>X<cstore()>X<restore()>Three of the most important functions
8141: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
8142: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
8143: is is the non-critical message twin of cstore. These functions are for
8144: handlers to store a perl hash to a user's permanent data space in an
8145: easy manner, and to retrieve it again on another call. It is expected
8146: that a handler would use this once at the beginning to retrieve data,
8147: and then again once at the end to send only the new data back.
8148:
8149: The data is stored in the user's data directory on the user's
8150: homeserver under the ID of the course.
8151:
8152: The hash that is returned by restore will have all of the previous
8153: value for all of the elements of the hash.
8154:
8155: Example:
8156:
8157: #creating a hash
8158: my %hash;
8159: $hash{'foo'}='bar';
8160:
8161: #storing it
8162: &Apache::lonnet::cstore(\%hash);
8163:
8164: #changing a value
8165: $hash{'foo'}='notbar';
8166:
8167: #adding a new value
8168: $hash{'bar'}='foo';
8169: &Apache::lonnet::cstore(\%hash);
8170:
8171: #retrieving the hash
8172: my %history=&Apache::lonnet::restore();
8173:
8174: #print the hash
8175: foreach my $key (sort(keys(%history))) {
8176: print("\%history{$key} = $history{$key}");
8177: }
8178:
8179: Will print out:
1.191 harris41 8180:
1.394 bowersj2 8181: %history{1:foo} = bar
8182: %history{1:keys} = foo:timestamp
8183: %history{1:timestamp} = 990455579
8184: %history{2:bar} = foo
8185: %history{2:foo} = notbar
8186: %history{2:keys} = foo:bar:timestamp
8187: %history{2:timestamp} = 990455580
8188: %history{bar} = foo
8189: %history{foo} = notbar
8190: %history{timestamp} = 990455580
8191: %history{version} = 2
8192:
8193: Note that the special hash entries C<keys>, C<version> and
8194: C<timestamp> were added to the hash. C<version> will be equal to the
8195: total number of versions of the data that have been stored. The
8196: C<timestamp> attribute will be the UNIX time the hash was
8197: stored. C<keys> is available in every historical section to list which
8198: keys were added or changed at a specific historical revision of a
8199: hash.
8200:
8201: B<Warning>: do not store the hash that restore returns directly. This
8202: will cause a mess since it will restore the historical keys as if the
8203: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 8204:
1.394 bowersj2 8205: Calling convention:
1.191 harris41 8206:
1.394 bowersj2 8207: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
8208: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 8209:
1.394 bowersj2 8210: For more detailed information, see lonnet specific documentation.
1.191 harris41 8211:
1.394 bowersj2 8212: =head1 RETURN MESSAGES
1.191 harris41 8213:
1.394 bowersj2 8214: =over 4
1.191 harris41 8215:
1.394 bowersj2 8216: =item * B<con_lost>: unable to contact remote host
1.191 harris41 8217:
1.394 bowersj2 8218: =item * B<con_delayed>: unable to contact remote host, message will be delivered
8219: when the connection is brought back up
1.191 harris41 8220:
1.394 bowersj2 8221: =item * B<con_failed>: unable to contact remote host and unable to save message
8222: for later delivery
1.191 harris41 8223:
1.394 bowersj2 8224: =item * B<error:>: an error a occured, a description of the error follows the :
1.191 harris41 8225:
1.394 bowersj2 8226: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 8227: that was requested
1.191 harris41 8228:
1.243 albertel 8229: =back
1.191 harris41 8230:
1.243 albertel 8231: =head1 PUBLIC SUBROUTINES
1.191 harris41 8232:
1.243 albertel 8233: =head2 Session Environment Functions
1.191 harris41 8234:
1.243 albertel 8235: =over 4
1.191 harris41 8236:
1.394 bowersj2 8237: =item *
8238: X<appenv()>
8239: B<appenv(%hash)>: the value of %hash is written to
8240: the user envirnoment file, and will be restored for each access this
1.620 albertel 8241: user makes during this session, also modifies the %env for the current
1.394 bowersj2 8242: process
1.191 harris41 8243:
8244: =item *
1.394 bowersj2 8245: X<delenv()>
8246: B<delenv($regexp)>: removes all items from the session
8247: environment file that matches the regular expression in $regexp. The
1.620 albertel 8248: values are also delted from the current processes %env.
1.191 harris41 8249:
1.795 albertel 8250: =item * get_env_multiple($name)
8251:
8252: gets $name from the %env hash, it seemlessly handles the cases where multiple
8253: values may be defined and end up as an array ref.
8254:
8255: returns an array of values
8256:
1.243 albertel 8257: =back
8258:
8259: =head2 User Information
1.191 harris41 8260:
1.243 albertel 8261: =over 4
1.191 harris41 8262:
8263: =item *
1.394 bowersj2 8264: X<queryauthenticate()>
8265: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 8266: authentication scheme
8267:
8268: =item *
1.394 bowersj2 8269: X<authenticate()>
8270: B<authenticate($uname,$upass,$udom)>: try to
8271: authenticate user from domain's lib servers (first use the current
8272: one). C<$upass> should be the users password.
1.191 harris41 8273:
8274: =item *
1.394 bowersj2 8275: X<homeserver()>
8276: B<homeserver($uname,$udom)>: find the server which has
8277: the user's directory and files (there must be only one), this caches
8278: the answer, and also caches if there is a borken connection.
1.191 harris41 8279:
8280: =item *
1.394 bowersj2 8281: X<idget()>
8282: B<idget($udom,@ids)>: find the usernames behind a list of IDs
8283: (IDs are a unique resource in a domain, there must be only 1 ID per
8284: username, and only 1 username per ID in a specific domain) (returns
8285: hash: id=>name,id=>name)
1.191 harris41 8286:
8287: =item *
1.394 bowersj2 8288: X<idrget()>
8289: B<idrget($udom,@unames)>: find the IDs behind a list of
8290: usernames (returns hash: name=>id,name=>id)
1.191 harris41 8291:
8292: =item *
1.394 bowersj2 8293: X<idput()>
8294: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 8295:
8296: =item *
1.394 bowersj2 8297: X<rolesinit()>
8298: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 8299:
8300: =item *
1.551 albertel 8301: X<getsection()>
8302: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 8303: course $cname, return section name/number or '' for "not in course"
8304: and '-1' for "no section"
8305:
8306: =item *
1.394 bowersj2 8307: X<userenvironment()>
8308: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 8309: passed in @what from the requested user's environment, returns a hash
8310:
1.858 raeburn 8311: =item *
8312: X<userlog_query()>
1.859 albertel 8313: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
8314: activity.log file. %filters defines filters applied when parsing the
8315: log file. These can be start or end timestamps, or the type of action
8316: - log to look for Login or Logout events, check for Checkin or
8317: Checkout, role for role selection. The response is in the form
8318: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
8319: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 8320:
1.243 albertel 8321: =back
8322:
8323: =head2 User Roles
8324:
8325: =over 4
8326:
8327: =item *
8328:
1.810 raeburn 8329: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 8330: F: full access
8331: U,I,K: authentication modes (cxx only)
8332: '': forbidden
8333: 1: user needs to choose course
8334: 2: browse allowed
1.766 albertel 8335: A: passphrase authentication needed
1.243 albertel 8336:
8337: =item *
8338:
8339: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
8340: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
8341: and course level
8342:
8343: =item *
8344:
8345: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
8346: explanation of a user role term
8347:
1.832 raeburn 8348: =item *
8349:
1.858 raeburn 8350: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
8351: All arguments are optional. Returns a hash of a roles, either for
8352: co-author/assistant author roles for a user's Construction Space
8353: (default), or if $context is 'user', roles for the user himself,
8354: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
8355: and value is set to colon-separated start and end times for the role.
8356: If no username and domain are specified, will default to current
8357: user/domain. Types, roles, and roledoms are references to arrays,
8358: of role statuses (active, future or previous), roles
8359: (e.g., cc,in, st etc.) and domains of the roles which can be used
8360: to restrict the list of roles reported. If no array ref is
8361: provided for types, will default to return only active roles.
1.834 albertel 8362:
1.243 albertel 8363: =back
8364:
8365: =head2 User Modification
8366:
8367: =over 4
8368:
8369: =item *
8370:
8371: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
8372: user for the level given by URL. Optional start and end dates (leave empty
8373: string or zero for "no date")
1.191 harris41 8374:
8375: =item *
8376:
1.243 albertel 8377: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
8378: change a users, password, possible return values are: ok,
8379: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
8380: refused
1.191 harris41 8381:
8382: =item *
8383:
1.243 albertel 8384: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 8385:
8386: =item *
8387:
1.243 albertel 8388: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) :
8389: modify user
1.191 harris41 8390:
8391: =item *
8392:
1.286 matthew 8393: modifystudent
8394:
8395: modify a students enrollment and identification information.
8396: The course id is resolved based on the current users environment.
8397: This means the envoking user must be a course coordinator or otherwise
8398: associated with a course.
8399:
1.297 matthew 8400: This call is essentially a wrapper for lonnet::modifyuser and
8401: lonnet::modify_student_enrollment
1.286 matthew 8402:
8403: Inputs:
8404:
8405: =over 4
8406:
8407: =item B<$udom> Students loncapa domain
8408:
8409: =item B<$uname> Students loncapa login name
8410:
8411: =item B<$uid> Students id/student number
8412:
8413: =item B<$umode> Students authentication mode
8414:
8415: =item B<$upass> Students password
8416:
8417: =item B<$first> Students first name
8418:
8419: =item B<$middle> Students middle name
8420:
8421: =item B<$last> Students last name
8422:
8423: =item B<$gene> Students generation
8424:
8425: =item B<$usec> Students section in course
8426:
8427: =item B<$end> Unix time of the roles expiration
8428:
8429: =item B<$start> Unix time of the roles start date
8430:
8431: =item B<$forceid> If defined, allow $uid to be changed
8432:
8433: =item B<$desiredhome> server to use as home server for student
8434:
8435: =back
1.297 matthew 8436:
8437: =item *
8438:
8439: modify_student_enrollment
8440:
8441: Change a students enrollment status in a class. The environment variable
8442: 'role.request.course' must be defined for this function to proceed.
8443:
8444: Inputs:
8445:
8446: =over 4
8447:
8448: =item $udom, students domain
8449:
8450: =item $uname, students name
8451:
8452: =item $uid, students user id
8453:
8454: =item $first, students first name
8455:
8456: =item $middle
8457:
8458: =item $last
8459:
8460: =item $gene
8461:
8462: =item $usec
8463:
8464: =item $end
8465:
8466: =item $start
8467:
8468: =back
8469:
1.191 harris41 8470:
8471: =item *
8472:
1.243 albertel 8473: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
8474: custom role; give a custom role to a user for the level given by URL. Specify
8475: name and domain of role author, and role name
1.191 harris41 8476:
8477: =item *
8478:
1.243 albertel 8479: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 8480:
8481: =item *
8482:
1.243 albertel 8483: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
8484:
8485: =back
8486:
8487: =head2 Course Infomation
8488:
8489: =over 4
1.191 harris41 8490:
8491: =item *
8492:
1.631 albertel 8493: coursedescription($courseid) : returns a hash of information about the
8494: specified course id, including all environment settings for the
8495: course, the description of the course will be in the hash under the
8496: key 'description'
1.191 harris41 8497:
8498: =item *
8499:
1.624 albertel 8500: resdata($name,$domain,$type,@which) : request for current parameter
8501: setting for a specific $type, where $type is either 'course' or 'user',
8502: @what should be a list of parameters to ask about. This routine caches
8503: answers for 5 minutes.
1.243 albertel 8504:
8505: =back
8506:
8507: =head2 Course Modification
8508:
8509: =over 4
1.191 harris41 8510:
8511: =item *
8512:
1.243 albertel 8513: writecoursepref($courseid,%prefs) : write preferences (environment
8514: database) for a course
1.191 harris41 8515:
8516: =item *
8517:
1.243 albertel 8518: createcourse($udom,$description,$url) : make/modify course
8519:
8520: =back
8521:
8522: =head2 Resource Subroutines
8523:
8524: =over 4
1.191 harris41 8525:
8526: =item *
8527:
1.243 albertel 8528: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 8529:
8530: =item *
8531:
1.243 albertel 8532: repcopy($filename) : subscribes to the requested file, and attempts to
8533: replicate from the owning library server, Might return
1.607 raeburn 8534: 'unavailable', 'not_found', 'forbidden', 'ok', or
8535: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 8536: resource. Expects the local filesystem pathname
8537: (/home/httpd/html/res/....)
8538:
8539: =back
8540:
8541: =head2 Resource Information
8542:
8543: =over 4
1.191 harris41 8544:
8545: =item *
8546:
1.243 albertel 8547: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
8548: a vairety of different possible values, $varname should be a request
8549: string, and the other parameters can be used to specify who and what
8550: one is asking about.
8551:
8552: Possible values for $varname are environment.lastname (or other item
8553: from the envirnment hash), user.name (or someother aspect about the
8554: user), resource.0.maxtries (or some other part and parameter of a
8555: resource)
1.204 albertel 8556:
8557: =item *
8558:
1.243 albertel 8559: directcondval($number) : get current value of a condition; reads from a state
8560: string
1.204 albertel 8561:
8562: =item *
8563:
1.243 albertel 8564: condval($condidx) : value of condition index based on state
1.204 albertel 8565:
8566: =item *
8567:
1.243 albertel 8568: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
8569: resource's metadata, $what should be either a specific key, or either
8570: 'keys' (to get a list of possible keys) or 'packages' to get a list of
8571: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
8572:
8573: this function automatically caches all requests
1.191 harris41 8574:
8575: =item *
8576:
1.243 albertel 8577: metadata_query($query,$custom,$customshow) : make a metadata query against the
8578: network of library servers; returns file handle of where SQL and regex results
8579: will be stored for query
1.191 harris41 8580:
8581: =item *
8582:
1.243 albertel 8583: symbread($filename) : return symbolic list entry (filename argument optional);
8584: returns the data handle
1.191 harris41 8585:
8586: =item *
8587:
1.243 albertel 8588: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 8589: a possible symb for the URL in $thisfn, and if is an encryypted
8590: resource that the user accessed using /enc/ returns a 1 on success, 0
8591: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 8592: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 8593:
1.191 harris41 8594:
8595: =item *
8596:
1.243 albertel 8597: symbclean($symb) : removes versions numbers from a symb, returns the
8598: cleaned symb
1.191 harris41 8599:
8600: =item *
8601:
1.243 albertel 8602: is_on_map($uri) : checks if the $uri is somewhere on the current
8603: course map, user must be in a course for it to work.
1.191 harris41 8604:
8605: =item *
8606:
1.243 albertel 8607: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 8608:
8609: =item *
8610:
1.243 albertel 8611: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
8612: a random seed, all arguments are optional, if they aren't sent it uses the
8613: environment to derive them. Note: if symb isn't sent and it can't get one
8614: from &symbread it will use the current time as its return value
1.191 harris41 8615:
8616: =item *
8617:
1.243 albertel 8618: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
8619: unfakeable, receipt
1.191 harris41 8620:
8621: =item *
8622:
1.620 albertel 8623: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 8624:
8625: =item *
8626:
1.243 albertel 8627: countacc($url) : count the number of accesses to a given URL
1.191 harris41 8628:
8629: =item *
8630:
1.243 albertel 8631: 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 8632:
8633: =item *
8634:
1.243 albertel 8635: 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 8636:
8637: =item *
8638:
1.243 albertel 8639: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 8640:
8641: =item *
8642:
1.243 albertel 8643: devalidate($symb) : devalidate temporary spreadsheet calculations,
8644: forcing spreadsheet to reevaluate the resource scores next time.
8645:
8646: =back
8647:
8648: =head2 Storing/Retreiving Data
8649:
8650: =over 4
1.191 harris41 8651:
8652: =item *
8653:
1.243 albertel 8654: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
8655: for this url; hashref needs to be given and should be a \%hashname; the
8656: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 8657: be derived from the env
1.191 harris41 8658:
8659: =item *
8660:
1.243 albertel 8661: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
8662: uses critical subroutine
1.191 harris41 8663:
8664: =item *
8665:
1.243 albertel 8666: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
8667: all args are optional
1.191 harris41 8668:
8669: =item *
8670:
1.717 albertel 8671: dumpstore($namespace,$udom,$uname,$regexp,$range) :
8672: dumps the complete (or key matching regexp) namespace into a hash
8673: ($udom, $uname, $regexp, $range are optional) for a namespace that is
8674: normally &store()ed into
8675:
8676: $range should be either an integer '100' (give me the first 100
8677: matching records)
8678: or be two integers sperated by a - with no spaces
8679: '30-50' (give me the 30th through the 50th matching
8680: records)
8681:
8682:
8683: =item *
8684:
8685: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
8686: replaces a &store() version of data with a replacement set of data
8687: for a particular resource in a namespace passed in the $storehash hash
8688: reference
8689:
8690: =item *
8691:
1.243 albertel 8692: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
8693: works very similar to store/cstore, but all data is stored in a
8694: temporary location and can be reset using tmpreset, $storehash should
8695: be a hash reference, returns nothing on success
1.191 harris41 8696:
8697: =item *
8698:
1.243 albertel 8699: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
8700: similar to restore, but all data is stored in a temporary location and
8701: can be reset using tmpreset. Returns a hash of values on success,
8702: error string otherwise.
1.191 harris41 8703:
8704: =item *
8705:
1.243 albertel 8706: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
8707: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 8708:
8709: =item *
8710:
1.243 albertel 8711: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8712: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 8713:
8714: =item *
8715:
1.243 albertel 8716: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
8717: namesp ($udom and $uname are optional)
1.191 harris41 8718:
8719: =item *
8720:
1.702 albertel 8721: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 8722: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 8723: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 8724:
1.702 albertel 8725: $range should be either an integer '100' (give me the first 100
8726: matching records)
8727: or be two integers sperated by a - with no spaces
8728: '30-50' (give me the 30th through the 50th matching
8729: records)
1.449 matthew 8730: =item *
8731:
8732: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
8733: $store can be a scalar, an array reference, or if the amount to be
8734: incremented is > 1, a hash reference.
8735:
8736: ($udom and $uname are optional)
1.191 harris41 8737:
8738: =item *
8739:
1.243 albertel 8740: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
8741: ($udom and $uname are optional)
1.191 harris41 8742:
8743: =item *
8744:
1.243 albertel 8745: cput($namespace,$storehash,$udom,$uname) : critical put
8746: ($udom and $uname are optional)
1.191 harris41 8747:
8748: =item *
8749:
1.748 albertel 8750: newput($namespace,$storehash,$udom,$uname) :
8751:
8752: Attempts to store the items in the $storehash, but only if they don't
8753: currently exist, if this succeeds you can be certain that you have
8754: successfully created a new key value pair in the $namespace db.
8755:
8756:
8757: Args:
8758: $namespace: name of database to store values to
8759: $storehash: hashref to store to the db
8760: $udom: (optional) domain of user containing the db
8761: $uname: (optional) name of user caontaining the db
8762:
8763: Returns:
8764: 'ok' -> succeeded in storing all keys of $storehash
8765: 'key_exists: <key>' -> failed to anything out of $storehash, as at
8766: least <key> already existed in the db (other
8767: requested keys may also already exist)
8768: 'error: <msg>' -> unable to tie the DB or other erorr occured
8769: 'con_lost' -> unable to contact request server
8770: 'refused' -> action was not allowed by remote machine
8771:
8772:
8773: =item *
8774:
1.243 albertel 8775: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
8776: reference filled in from namesp (encrypts the return communication)
8777: ($udom and $uname are optional)
1.191 harris41 8778:
8779: =item *
8780:
1.243 albertel 8781: log($udom,$name,$home,$message) : write to permanent log for user; use
8782: critical subroutine
8783:
1.806 raeburn 8784: =item *
8785:
1.860 raeburn 8786: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
8787: array reference filled in from namespace found in domain level on either
8788: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 8789:
8790: =item *
8791:
1.860 raeburn 8792: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
8793: domain level either on specified domain server ($uhome) or primary domain
8794: server ($udom and $uhome are optional)
1.806 raeburn 8795:
1.243 albertel 8796: =back
8797:
8798: =head2 Network Status Functions
8799:
8800: =over 4
1.191 harris41 8801:
8802: =item *
8803:
8804: dirlist($uri) : return directory list based on URI
8805:
8806: =item *
8807:
1.243 albertel 8808: spareserver() : find server with least workload from spare.tab
8809:
8810: =back
8811:
8812: =head2 Apache Request
8813:
8814: =over 4
1.191 harris41 8815:
8816: =item *
8817:
1.243 albertel 8818: ssi($url,%hash) : server side include, does a complete request cycle on url to
8819: localhost, posts hash
8820:
8821: =back
8822:
8823: =head2 Data to String to Data
8824:
8825: =over 4
1.191 harris41 8826:
8827: =item *
8828:
1.243 albertel 8829: hash2str(%hash) : convert a hash into a string complete with escaping and '='
8830: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 8831:
8832: =item *
8833:
1.243 albertel 8834: hashref2str($hashref) : convert a hashref into a string complete with
8835: escaping and '=' and '&' separators, supports elements that are
8836: arrayrefs and hashrefs
1.191 harris41 8837:
8838: =item *
8839:
1.243 albertel 8840: arrayref2str($arrayref) : convert an arrayref into a string complete
8841: with escaping and '&' separators, supports elements that are arrayrefs
8842: and hashrefs
1.191 harris41 8843:
8844: =item *
8845:
1.243 albertel 8846: str2hash($string) : convert string to hash using unescaping and
8847: splitting on '=' and '&', supports elements that are arrayrefs and
8848: hashrefs
1.191 harris41 8849:
8850: =item *
8851:
1.243 albertel 8852: str2array($string) : convert string to hash using unescaping and
8853: splitting on '&', supports elements that are arrayrefs and hashrefs
8854:
8855: =back
8856:
8857: =head2 Logging Routines
8858:
8859: =over 4
8860:
8861: These routines allow one to make log messages in the lonnet.log and
8862: lonnet.perm logfiles.
1.191 harris41 8863:
8864: =item *
8865:
1.243 albertel 8866: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 8867:
8868: =item *
8869:
1.243 albertel 8870: logthis() : append message to the normal lonnet.log file, it gets
8871: preiodically rolled over and deleted.
1.191 harris41 8872:
8873: =item *
8874:
1.243 albertel 8875: logperm() : append a permanent message to lonnet.perm.log, this log
8876: file never gets deleted by any automated portion of the system, only
8877: messages of critical importance should go in here.
8878:
8879: =back
8880:
8881: =head2 General File Helper Routines
8882:
8883: =over 4
1.191 harris41 8884:
8885: =item *
8886:
1.481 raeburn 8887: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
8888: (a) files in /uploaded
8889: (i) If a local copy of the file exists -
8890: compares modification date of local copy with last-modified date for
8891: definitive version stored on home server for course. If local copy is
8892: stale, requests a new version from the home server and stores it.
8893: If the original has been removed from the home server, then local copy
8894: is unlinked.
8895: (ii) If local copy does not exist -
8896: requests the file from the home server and stores it.
8897:
8898: If $caller is 'uploadrep':
8899: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
8900: for request for files originally uploaded via DOCS.
8901: - returns 'ok' if fresh local copy now available, -1 otherwise.
8902:
8903: Otherwise:
8904: This indicates a call from the content generation phase of the request.
8905: - returns the entire contents of the file or -1.
8906:
8907: (b) files in /res
8908: - returns the entire contents of a file or -1;
8909: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 8910:
1.712 albertel 8911:
8912: =item *
8913:
8914: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
8915: reference
8916:
8917: returns either a stat() list of data about the file or an empty list
8918: if the file doesn't exist or couldn't find out about it (connection
8919: problems or user unknown)
8920:
1.191 harris41 8921: =item *
8922:
1.243 albertel 8923: filelocation($dir,$file) : returns file system location of a file
8924: based on URI; meant to be "fairly clean" absolute reference, $dir is a
8925: directory that relative $file lookups are to looked in ($dir of /a/dir
8926: and a file of ../bob will become /a/bob)
1.191 harris41 8927:
8928: =item *
8929:
8930: hreflocation($dir,$file) : returns file system location or a URL; same as
8931: filelocation except for hrefs
8932:
8933: =item *
8934:
8935: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
8936:
1.243 albertel 8937: =back
8938:
1.608 albertel 8939: =head2 Usererfile file routines (/uploaded*)
8940:
8941: =over 4
8942:
8943: =item *
8944:
8945: userfileupload(): main rotine for putting a file in a user or course's
8946: filespace, arguments are,
8947:
1.620 albertel 8948: formname - required - this is the name of the element in $env where the
1.608 albertel 8949: filename, and the contents of the file to create/modifed exist
1.620 albertel 8950: the filename is in $env{'form.'.$formname.'.filename'} and the
8951: contents of the file is located in $env{'form.'.$formname}
1.608 albertel 8952: coursedoc - if true, store the file in the course of the active role
8953: of the current user
8954: subdir - required - subdirectory to put the file in under ../userfiles/
8955: if undefined, it will be placed in "unknown"
8956:
8957: (This routine calls clean_filename() to remove any dangerous
8958: characters from the filename, and then calls finuserfileupload() to
8959: complete the transaction)
8960:
8961: returns either the url of the uploaded file (/uploaded/....) if successful
8962: and /adm/notfound.html if unsuccessful
8963:
8964: =item *
8965:
8966: clean_filename(): routine for cleaing a filename up for storage in
8967: userfile space, argument is:
8968:
8969: filename - proposed filename
8970:
8971: returns: the new clean filename
8972:
8973: =item *
8974:
8975: finishuserfileupload(): routine that creaes and sends the file to
8976: userspace, probably shouldn't be called directly
8977:
8978: docuname: username or courseid of destination for the file
8979: docudom: domain of user/course of destination for the file
8980: formname: same as for userfileupload()
8981: fname: filename (inculding subdirectories) for the file
8982:
8983: returns either the url of the uploaded file (/uploaded/....) if successful
8984: and /adm/notfound.html if unsuccessful
8985:
8986: =item *
8987:
8988: renameuserfile(): renames an existing userfile to a new name
8989:
8990: Args:
8991: docuname: username or courseid of destination for the file
8992: docudom: domain of user/course of destination for the file
8993: old: current file name (including any subdirs under userfiles)
8994: new: desired file name (including any subdirs under userfiles)
8995:
8996: =item *
8997:
8998: mkdiruserfile(): creates a directory is a userfiles dir
8999:
9000: Args:
9001: docuname: username or courseid of destination for the file
9002: docudom: domain of user/course of destination for the file
9003: dir: dir to create (including any subdirs under userfiles)
9004:
9005: =item *
9006:
9007: removeuserfile(): removes a file that exists in userfiles
9008:
9009: Args:
9010: docuname: username or courseid of destination for the file
9011: docudom: domain of user/course of destination for the file
9012: fname: filname to delete (including any subdirs under userfiles)
9013:
9014: =item *
9015:
9016: removeuploadedurl(): convience function for removeuserfile()
9017:
9018: Args:
9019: url: a full /uploaded/... url to delete
9020:
1.747 albertel 9021: =item *
9022:
9023: get_portfile_permissions():
9024: Args:
9025: domain: domain of user or course contain the portfolio files
9026: user: name of user or num of course contain the portfolio files
9027: Returns:
9028: hashref of a dump of the proper file_permissions.db
9029:
9030:
9031: =item *
9032:
9033: get_access_controls():
9034:
9035: Args:
9036: current_permissions: the hash ref returned from get_portfile_permissions()
9037: group: (optional) the group you want the files associated with
9038: file: (optional) the file you want access info on
9039:
9040: Returns:
1.749 raeburn 9041: a hash (keys are file names) of hashes containing
9042: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
9043: values are XML containing access control settings (see below)
1.747 albertel 9044:
9045: Internal notes:
9046:
1.749 raeburn 9047: access controls are stored in file_permissions.db as key=value pairs.
9048: key -> path to file/file_name\0uniqueID:scope_end_start
9049: where scope -> public,guest,course,group,domains or users.
9050: end -> UNIX time for end of access (0 -> no end date)
9051: start -> UNIX time for start of access
9052:
9053: value -> XML description of access control
9054: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
9055: <start></start>
9056: <end></end>
9057:
9058: <password></password> for scope type = guest
9059:
9060: <domain></domain> for scope type = course or group
9061: <number></number>
9062: <roles id="">
9063: <role></role>
9064: <access></access>
9065: <section></section>
9066: <group></group>
9067: </roles>
9068:
9069: <dom></dom> for scope type = domains
9070:
9071: <users> for scope type = users
9072: <user>
9073: <uname></uname>
9074: <udom></udom>
9075: </user>
9076: </users>
9077: </scope>
9078:
9079: Access data is also aggregated for each file in an additional key=value pair:
9080: key -> path to file/file_name\0accesscontrol
9081: value -> reference to hash
9082: hash contains key = value pairs
9083: where key = uniqueID:scope_end_start
9084: value = UNIX time record was last updated
9085:
9086: Used to improve speed of look-ups of access controls for each file.
9087:
9088: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
9089:
9090: modify_access_controls():
9091:
9092: Modifies access controls for a portfolio file
9093: Args
9094: 1. file name
9095: 2. reference to hash of required changes,
9096: 3. domain
9097: 4. username
9098: where domain,username are the domain of the portfolio owner
9099: (either a user or a course)
9100:
9101: Returns:
9102: 1. result of additions or updates ('ok' or 'error', with error message).
9103: 2. result of deletions ('ok' or 'error', with error message).
9104: 3. reference to hash of any new or updated access controls.
9105: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
9106: key = integer (inbound ID)
9107: value = uniqueID
1.747 albertel 9108:
1.608 albertel 9109: =back
9110:
1.243 albertel 9111: =head2 HTTP Helper Routines
9112:
9113: =over 4
9114:
1.191 harris41 9115: =item *
9116:
9117: escape() : unpack non-word characters into CGI-compatible hex codes
9118:
9119: =item *
9120:
9121: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
9122:
1.243 albertel 9123: =back
9124:
9125: =head1 PRIVATE SUBROUTINES
9126:
9127: =head2 Underlying communication routines (Shouldn't call)
9128:
9129: =over 4
9130:
9131: =item *
9132:
9133: subreply() : tries to pass a message to lonc, returns con_lost if incapable
9134:
9135: =item *
9136:
9137: reply() : uses subreply to send a message to remote machine, logs all failures
9138:
9139: =item *
9140:
9141: critical() : passes a critical message to another server; if cannot
9142: get through then place message in connection buffer directory and
9143: returns con_delayed, if incapable of saving message, returns
9144: con_failed
9145:
9146: =item *
9147:
9148: reconlonc() : tries to reconnect lonc client processes.
9149:
9150: =back
9151:
9152: =head2 Resource Access Logging
9153:
9154: =over 4
9155:
9156: =item *
9157:
9158: flushcourselogs() : flush (save) buffer logs and access logs
9159:
9160: =item *
9161:
9162: courselog($what) : save message for course in hash
9163:
9164: =item *
9165:
9166: courseacclog($what) : save message for course using &courselog(). Perform
9167: special processing for specific resource types (problems, exams, quizzes, etc).
9168:
1.191 harris41 9169: =item *
9170:
9171: goodbye() : flush course logs and log shutting down; it is called in srm.conf
9172: as a PerlChildExitHandler
1.243 albertel 9173:
9174: =back
9175:
9176: =head2 Other
9177:
9178: =over 4
9179:
9180: =item *
9181:
9182: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 9183:
9184: =back
9185:
9186: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>